<?php

namespace App\Http\Controllers\Employee;

use App\Http\Controllers\Controller;
use App\Models\Attendance;
use App\Models\EmployeeProfile;
use App\Models\LeaveRequest;
use App\Services\AttendanceService;
use Illuminate\Http\Request;
use Inertia\Inertia;

class DashboardController extends Controller
{
    public function __construct(protected AttendanceService $attendanceService) {}

    public function index(Request $request)
    {
        $user = $request->user();
        $managedEmployeeIds = EmployeeProfile::query()
            ->where('manager_id', $user->id)
            ->pluck('user_id');
        $isManager = $managedEmployeeIds->isNotEmpty();

        $attendanceApprovalCount = $isManager
            ? Attendance::query()
                ->whereIn('user_id', $managedEmployeeIds)
                ->where('anomaly_status', 'pending_manager')
                ->count()
            : 0;
        $leaveApprovalCount = $isManager
            ? LeaveRequest::query()
                ->whereIn('user_id', $managedEmployeeIds)
                ->where('status', 'pending_manager')
                ->count()
            : 0;

        return Inertia::render('Employee/Pages/Dashboard', [
            'today_attendance' => $this->attendanceService->getTodayStatus($user),
            'stats' => $this->attendanceService->getDashboardStats($user),
            'history' => $this->attendanceService->getLogHistory($user, $request->input('date')),
            'filters' => $request->only(['date']),
            'quick_access' => [
                'attendance_approvals' => [
                    'has_access' => $isManager,
                    'total_count' => $attendanceApprovalCount,
                    'pending_count' => $attendanceApprovalCount,
                ],
                'leave_approvals' => [
                    'has_access' => $isManager,
                    'total_count' => $leaveApprovalCount,
                    'pending_count' => $leaveApprovalCount,
                ],
            ],
        ]);
    }
}
