<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Inertia\Inertia;

class DashboardController extends Controller
{
    public function index()
    {
        $dateStr = request('date', now()->format('Y-m-d'));
        $today = \Carbon\Carbon::parse($dateStr)->startOfDay();


        // Workforce Stats
        $totalEmployees = \App\Models\User::where('type', \App\Enums\UserType::EMPLOYEE)->where('status', 'active')->count();
        $attendanceToday = \App\Models\Attendance::whereDate('date', $today)->get();

        $presentCount = $attendanceToday->whereIn('status', ['Present', 'Late'])->count();
        $lateCount = $attendanceToday->where('status', 'Late')->count();
        $absentCount = max(0, $totalEmployees - $presentCount);
        $attendanceRate = $totalEmployees > 0 ? round(($presentCount / $totalEmployees) * 100) : 0;

        // Approval Hub Counts
        $leaveCount = \App\Models\LeaveRequest::where('status', 'pending_admin')->count();
        $payrollCount = \App\Models\Payroll::where('status', 'pending')->count();
        $loanCount = \App\Models\Loan::where('status', 'pending')->count();
        $incrementCount = \App\Models\SalaryIncrement::where('status', 'pending')->count();
        $bonusCount = \App\Models\BonusGeneration::where('status', 'pending')->count();

        // Approval Queue (Latest 10 combined)
        $approvalQueue = collect();

        // Add Leaves
        $leaves = \App\Models\LeaveRequest::with('user', 'leaveType')
            ->where('status', 'pending_admin')
            ->latest()
            ->take(5)
            ->get()
            ->map(function ($item) {
                return [
                    'id' => $item->id,
                    'name' => $item->user->name,
                    'dept' => $item->user->employeeProfile->department->name ?? 'N/A',
                    'type' => 'Leave',
                    'details' => $item->leaveType->name . " (" . $item->total_days . " Days)",
                    'color' => 'emerald',
                    'icon' => 'fa-calendar-alt',
                    'created_at' => $item->created_at,
                ];
            });
        $approvalQueue = $approvalQueue->concat($leaves);

        // Add Loans
        $loans = \App\Models\Loan::with('employee')
            ->where('status', 'pending')
            ->latest()
            ->take(5)
            ->get()
            ->map(function ($item) {
                return [
                    'id' => $item->id,
                    'name' => $item->employee->name,
                    'dept' => $item->employee->employeeProfile->department->name ?? 'N/A',
                    'type' => 'Loan',
                    'details' => "$" . number_format($item->amount, 2) . " " . $item->type,
                    'color' => 'amber',
                    'icon' => 'fa-hand-holding-usd',
                    'created_at' => $item->created_at,
                ];
            });
        $approvalQueue = $approvalQueue->concat($loans);

        // Add Increments
        $increments = \App\Models\SalaryIncrement::with('employee')
            ->where('status', 'pending')
            ->latest()
            ->take(5)
            ->get()
            ->map(function ($item) {
                return [
                    'id' => $item->id,
                    'name' => $item->employee->name,
                    'dept' => $item->employee->employeeProfile->department->name ?? 'N/A',
                    'type' => 'Increment',
                    'details' => "+" . ($item->increment_amount ?? 0) . " " . ($item->increment_type === 'percentage' ? '%' : 'Fixed'),
                    'color' => 'indigo',
                    'icon' => 'fa-chart-line',
                    'created_at' => $item->created_at,
                ];
            });
        $approvalQueue = $approvalQueue->concat($increments);

        // Add Bonuses
        $bonuses = \App\Models\BonusGeneration::with('generatedBy', 'bonus')
            ->where('status', 'pending')
            ->latest()
            ->take(5)
            ->get()
            ->map(function ($item) {
                return [
                    'id' => $item->id,
                    'name' => $item->generatedBy->name,
                    'dept' => 'HR Operations',
                    'type' => 'Bonus',
                    'details' => ($item->bonus->name ?? 'Monthly Bonus') . " Payout",
                    'color' => 'rose',
                    'icon' => 'fa-gift',
                    'created_at' => $item->created_at,
                ];
            });
        $approvalQueue = $approvalQueue->concat($bonuses);

        $approvalQueue = $approvalQueue->sortByDesc('created_at')->take(10)->values();

        return Inertia::render('Admin/Pages/Dashboard', [
            'stats' => [
                'total_employees' => $totalEmployees,
                'present_today' => $presentCount,
                'late_today' => $lateCount,
                'absent_today' => $absentCount,
                'attendance_rate' => $attendanceRate,
            ],
            'approvalHub' => [
                'leave' => $leaveCount,
                'salary' => $payrollCount,
                'loan' => $loanCount,
                'increment' => $incrementCount,
                'bonus' => $bonusCount,
            ],
            'approvalQueue' => $approvalQueue,
            'filters' => ['date' => $dateStr],
        ]);

    }
}
