<?php

namespace App\Http\Controllers\Employee;

use App\Http\Controllers\Controller;
use App\Models\LeaveRequest;
use App\Models\User;
use App\Services\AttendanceService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class MyTeamController extends Controller
{
    public function __construct(private readonly AttendanceService $attendanceService) {}

    public function index(Request $request): Response
    {
        $user = $request->user();

        if (! $user->isManager()) {
            abort(403, 'You are not authorized to access this page.');
        }

        $selectedDate = $request->filled('date')
            ? Carbon::parse($request->string('date'))->toDateString()
            : Carbon::today()->toDateString();

        $teamMembers = User::query()
            ->whereHas('employeeProfile', function ($query) use ($user) {
                $query->where('manager_id', $user->id);
            })
            ->with([
                'employeeProfile.departmentRel:id,name',
                'attendances' => function ($query) use ($selectedDate) {
                    $query->whereDate('date', $selectedDate);
                },
            ])
            ->orderBy('name')
            ->get();

        $leaveUserIds = LeaveRequest::query()
            ->whereIn('user_id', $teamMembers->pluck('id'))
            ->where('status', 'approved')
            ->whereDate('start_date', '<=', $selectedDate)
            ->whereDate('end_date', '>=', $selectedDate)
            ->pluck('user_id')
            ->flip();

        $rows = $teamMembers->map(function (User $member) use ($leaveUserIds, $selectedDate) {
            $attendance = $member->attendances->first();
            $finalStatus = $this->attendanceService->resolveDailyStatus(
                $attendance,
                $leaveUserIds->has($member->id),
                $selectedDate
            );

            return [
                'id' => $member->id,
                'name' => $member->name,
                'email' => $member->email,
                'department' => $member->employeeProfile?->departmentRel?->name,
                'clock_in' => $attendance?->clock_in,
                'clock_out' => $attendance?->clock_out,
                'total_hours' => $attendance?->total_hours ?? 0,
                'status' => $finalStatus,
            ];
        })->values();

        $stats = [
            'employees' => $rows->count(),
            'present' => $rows->where('status', 'present')->count(),
            'late' => $rows->where('status', 'late')->count(),
            'leave' => $rows->where('status', 'leave')->count(),
            'absent' => $rows->where('status', 'absent')->count(),
        ];

        return Inertia::render('Employee/Pages/MyTeam/Index', [
            'team' => $rows,
            'stats' => $stats,
            'filters' => [
                'date' => $selectedDate,
            ],
        ]);
    }
}
