<?php

namespace App\Http\Controllers\Api;

use App\Enums\DailyPatrolSummaryStatus;
use App\Http\Controllers\Controller;
use App\Models\DailyPatrolSummary;
use App\Models\Flat;
use App\Models\Guard;
use App\Models\Owner;
use App\Models\PatrollingLocation;
use App\Models\PatrollingLog;
use App\Models\Vehicle;
use App\Models\Visitor;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function __invoke(): JsonResponse
    {
        $today = Carbon::today();
        $sevenDaysAgo = Carbon::today()->subDays(6);

        // Basic counts
        $totalOwners = Owner::count();
        $totalFlats = Flat::count();
        $registeredVehicles = Vehicle::where('is_active', true)->count();
        $totalGuards = Guard::count();
        $patrollingLocations = PatrollingLocation::where('is_active', true)->count();
        $todaysVisitors = Visitor::whereDate('created_at', $today)->count();
        $totalPatrolSummaries = DailyPatrolSummary::count();

        // Today's completed patrols
        $todaysCompletedPatrols = DailyPatrolSummary::whereDate('patrol_date', $today)
            ->where('status', DailyPatrolSummaryStatus::COMPLETED->value)
            ->count();

        // Average completion rate
        $avgCompletionRate = DailyPatrolSummary::where('total_locations', '>', 0)
            ->selectRaw('AVG((completed_locations / total_locations) * 100) as avg_rate')
            ->value('avg_rate') ?? 0;

        // Visitor trends for last 7 days
        $visitorData = Visitor::select(
            DB::raw('DATE(created_at) as date'),
            DB::raw('COUNT(*) as count')
        )
            ->whereBetween('created_at', [$sevenDaysAgo, $today->copy()->endOfDay()])
            ->groupBy(DB::raw('DATE(created_at)'))
            ->pluck('count', 'date');

        $visitorTrends = collect();
        for ($i = 6; $i >= 0; $i--) {
            $date = Carbon::today()->subDays($i);
            $visitorTrends->push([
                'date' => $date->format('M d'),
                'visitors' => $visitorData->get($date->toDateString(), 0)
            ]);
        }

        // Patrol log status distribution for pie chart
        $patrolStatusDistribution = PatrollingLog::select(
            'status',
            DB::raw('COUNT(*) as count')
        )
            ->groupBy('status')
            ->get()
            ->map(function ($item) {
                return [
                    'status' => $item->status,
                    'count' => $item->count,
                    'label' => ucfirst(str_replace('_', ' ', $item->status->value))
                ];
            });

        return response()->json([
            'statistics' => [
                'total_owners' => $totalOwners,
                'total_flats' => $totalFlats,
                'registered_vehicles' => $registeredVehicles,
                'total_guards' => $totalGuards,
                'patrolling_locations' => $patrollingLocations,
                'todays_visitors' => $todaysVisitors,
                'total_patrol_summaries' => $totalPatrolSummaries,
                'todays_completed_patrols' => $todaysCompletedPatrols,
                'avg_completion_rate' => round($avgCompletionRate, 2)
            ],
            'charts' => [
                'visitor_trends' => $visitorTrends,
                'patrol_status_distribution' => $patrolStatusDistribution
            ]
        ]);
    }
}
