<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use App\Models\FollowUp;
use App\Models\Lead;
use Illuminate\Http\Request;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function summary(Request $request)
    {
        $user = $request->user()->load('subscription');

        // 🔒 Pro-only check
        if ($user->plan !== 'pro') {
            return response()->json([
                'success' => false,
                'data' => null,
                'error' => 'Upgrade to Pro to access analytics'
            ], 403);
        }

        // Follow-ups
        $totalFollowUps = FollowUp::where('user_id', $user->id)->count();
        $completedFollowUps = FollowUp::where('user_id', $user->id)
            ->where('status', 'done')
            ->count();
        $pendingFollowUps = FollowUp::where('user_id', $user->id)
            ->where('status', 'pending')
            ->count();

        // Upcoming
        $today = Carbon::today();
        $endOfWeek = Carbon::now()->endOfWeek();

        $todayCount = FollowUp::where('user_id', $user->id)
            ->whereDate('scheduled_at', $today)
            ->count();

        $thisWeekCount = FollowUp::where('user_id', $user->id)
            ->whereBetween('scheduled_at', [$today, $endOfWeek])
            ->count();

        // Leads
        $wonLeads = Lead::where('user_id', $user->id)
            ->where('status', 'won')
            ->count();

        return response()->json([
            'success' => true,
            'data' => [
                'followUps' => [
                    'total' => $totalFollowUps,
                    'completed' => $completedFollowUps,
                    'pending' => $pendingFollowUps,
                ],
                'upcoming' => [
                    'today' => $todayCount,
                    'this_week' => $thisWeekCount,
                ],
                'leads' => [
                    'won' => $wonLeads,
                ],
            ],
            'error' => null,
        ]);
    }
}
