<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\API\v1\EmployeeController;
use App\Http\Controllers\Controller;
use App\Jobs\ProcessEmployeeAttendance;
use App\Models\Dealership;
use App\Models\PayrollDate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AttendancePostingCronController extends Controller
{
    public function index()
    {
        $date_for_testing = '2025-01-03';
        $now = date('Y-m-d', strtotime($date_for_testing));
        $dealers = [103];

        $employeesController = new EmployeeController();
        $employeeRequest = new Request(['dealership_id' => $dealers]);
        $employees = json_decode($employeesController->getAllEmployees($employeeRequest)->getContent(), true);

        // Fetch payroll dates for all dealers at once
        $payrollDates = PayrollDate::whereIn('dealer_id', $dealers)
            ->whereDate('date_from', '<=', $now)
            ->whereDate('date_to', '>=', $now)
            ->get()
            ->keyBy('dealer_id');

        foreach ($dealers as $dealer) {
            $payroll_date = $payrollDates[$dealer] ?? PayrollDate::whereDate('date_from', '<=', $now)
                ->whereDate('date_to', '>=', $now)
                ->first();

            if (!$payroll_date) {
                continue;
            }

            $dealerEmployees = array_filter($employees, fn($emp) => $emp['dealer_id'] == $dealer);

            foreach ($dealerEmployees as $employee) {
                $forRequest = [
                    'employee_id' => $employee['employee_id'],
                    'company_id' => (string) $employee['company_id'],
                    'dealership_id' => (string) $employee['dealer_id'],
                    'department_id' => (string) $employee['department_id'],
                    'payroll_date' => $payroll_date->payroll_date,
                    'start_date' => $payroll_date->date_from,
                    'end_date' => $payroll_date->date_to,
                ];

                // ✅ Dispatch the job without running queue:work manually
                ProcessEmployeeAttendance::dispatch($forRequest)->onQueue('attendance-processing');
            }
        }

        return response()->json(['message' => 'Jobs dispatched successfully']);
    }
}
