<?php

namespace App\Controllers\Admin;

use App\Controllers\Controller;
use App\Jobs\CleanupDismissedEmployeeRecords;
use App\Jobs\FinalPayrollCalculation;
use App\Models\Employee;
use App\Models\TerminationLog;
use Illuminate\Http\Request;

class DismissalDashboardController extends Controller
{
    public function index()
    {
        $stats = [
            'total_dismissed' => TerminationLog::count(),
            'dismissed_this_month' => TerminationLog::whereMonth('termination_date', now()->month)->count(),
            'pending_payroll' => Employee::whereNotNull('dismissed_at')
                ->whereDoesntHave('terminationLogs', function($q) {
                    $q->whereNotNull('metadata->final_payroll');
                })->count(),
            'awaiting_cleanup' => Employee::whereNotNull('dismissed_at')
                ->where('dismissed_at', '<', now()->subDays(90))->count(),
        ];
        
        $recentDismissals = TerminationLog::with('employee', 'performedBy')
            ->latest()
            ->limit(10)
            ->get();
        
        return view('admin.dismissal.dashboard', compact('stats', 'recentDismissals'));
    }
    
    public function triggerCleanup(Request $request)
    {
        $days = $request->input('days', 90);
        
        CleanupDismissedEmployeeRecords::dispatch($days, true);
        
        return redirect()->back()->with('success', "Cleanup job dispatched for employees dismissed > {$days} days ago");
    }
    
    public function retryPayroll(Employee $employee)
    {
        FinalPayrollCalculation::dispatch($employee);
        
        return redirect()->back()->with('success', "Final payroll calculation queued for {$employee->name}");
    }
    
    public function retryAllPendingPayroll()
    {
        $pending = Employee::whereNotNull('dismissed_at')
            ->whereDoesntHave('terminationLogs', function($q) {
                $q->whereNotNull('metadata->final_payroll');
            })
            ->get();
        
        foreach ($pending as $employee) {
            FinalPayrollCalculation::dispatch($employee);
        }
        
        return redirect()->back()->with('success', "Queued {$pending->count()} final payroll calculations");
    }
}