<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\AppSetting;
use App\Models\AttendanceEvent;
use App\Models\Site;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        $sites = Site::orderBy('name')->get();

        $siteId = $user->isSecurity() ? $user->site_id : $request->query('site_id');

        $today = Carbon::today()->toDateString();

        $todaysEvents = AttendanceEvent::with(['employee', 'site', 'device'])
            ->whereDate('ts', $today)
            ->notCorrected()
            ->when($siteId, fn ($q) => $q->where('site_id', $siteId))
            ->orderBy('ts')
            ->get();

        $lastPerEmployee = $todaysEvents->groupBy('employee_id')->map(fn ($events) => $events->last());
        $whoIsIn = $lastPerEmployee->filter(fn ($e) => $e->direction === 'IN')->sortBy(fn ($e) => $e->employee->name);

        $shiftStart = Carbon::parse($today.' '.AppSetting::current()->shift_start);
        $firstInPerEmployee = $todaysEvents->where('direction', 'IN')->groupBy('employee_id')->map(fn ($events) => $events->first());
        $lateList = $firstInPerEmployee->filter(fn ($e) => $e->ts->gt($shiftStart))->sortBy(fn ($e) => $e->employee->name);

        $recentPunches = $todaysEvents->sortByDesc('ts')->take(20);

        return view('dashboard', [
            'sites' => $sites,
            'selectedSiteId' => $siteId,
            'presentCount' => $whoIsIn->count(),
            'whoIsIn' => $whoIsIn,
            'lateList' => $lateList,
            'recentPunches' => $recentPunches,
            'isSecurity' => $user->isSecurity(),
        ]);
    }
}
