<?php
/**
 * Leave Allocation Cron — runs daily
 * On 1st of each month: allocates monthly portion of annual/sick/family leave
 * Schedule: 0 1 1 * * php /path/to/site/cron/allocate_leave.php
 * OR run daily: 0 1 * * * php /path/to/site/cron/allocate_leave.php
 */

define('RUNNING_CRON', true);
require_once __DIR__ . '/../api/config/db.php';

$today     = new DateTime();
$dom       = (int)$today->format('j');  // day of month
$year      = (int)$today->format('Y');
$month     = (int)$today->format('n');

// Only run on the 1st of the month (bypass with EWG_FORCE_CRON=1 for manual testing)
if ($dom !== 1 && getenv('EWG_FORCE_CRON') !== '1') {
    echo date('Y-m-d H:i:s') . " — Not 1st of month, skipping.\n";
    if (defined("RUNNING_AS_INCLUDE")) throw new CronExitException(0); else exit(0);
}

echo date('Y-m-d H:i:s') . " — Leave allocation cron starting for $year-$month...\n";

try {
    $db = getDB();

    // Get settings
    $sStmt = $db->query("SELECT setting_key, setting_value FROM settings WHERE setting_group='leave'");
    $settings = [];
    foreach ($sStmt->fetchAll() as $s) $settings[$s['setting_key']] = (float)$s['setting_value'];

    $annualDays   = $settings['annual_leave_days']   ?? 15;   // days/year
    $sickDays     = $settings['sick_leave_days']     ?? 30;   // days/3 years
    $familyDays   = $settings['family_leave_days']   ?? 3;    // days/year
    $maternityDays= $settings['maternity_leave_days'] ?? 120; // lump sum when used
    $paternityDays= $settings['paternity_leave_days'] ?? 10;

    // Monthly accrual rates
    $annualMonthly  = round($annualDays  / 12, 2);
    $sickMonthly    = round($sickDays    / 36, 2); // 3 years = 36 months
    $familyMonthly  = round($familyDays  / 12, 2);

    // Get all active employees
    $empStmt = $db->query("SELECT id, start_date FROM employees WHERE status='active'");
    $employees = $empStmt->fetchAll();
    $count = 0;

    foreach ($employees as $emp) {
        $empId = (int)$emp['id'];
        // Only accrue if employee started before this month
        $startDate = new DateTime($emp['start_date']);
        if ($startDate > $today) continue;

        // Upsert annual leave balance (accrue monthly)
        $db->prepare("
            INSERT INTO employee_leave_balance (employee_id, year, leave_type, allocated, used, carried_over)
            VALUES (?, ?, 'annual', ?, 0, 0)
            ON DUPLICATE KEY UPDATE allocated = allocated + ?
        ")->execute([$empId, $year, $annualMonthly, $annualMonthly]);

        // Sick leave
        $db->prepare("
            INSERT INTO employee_leave_balance (employee_id, year, leave_type, allocated, used, carried_over)
            VALUES (?, ?, 'sick', ?, 0, 0)
            ON DUPLICATE KEY UPDATE allocated = allocated + ?
        ")->execute([$empId, $year, $sickMonthly, $sickMonthly]);

        // Family responsibility (yearly, only allocate in January)
        if ($month === 1) {
            $db->prepare("
                INSERT INTO employee_leave_balance (employee_id, year, leave_type, allocated, used, carried_over)
                VALUES (?, ?, 'family', ?, 0, 0)
                ON DUPLICATE KEY UPDATE allocated = ?
            ")->execute([$empId, $year, $familyDays, $familyDays]);
        }

        // On January, carry over unused annual leave (up to 5 days max per BCEA)
        if ($month === 1) {
            $prevYear = $year - 1;
            $prevBal = $db->prepare("SELECT allocated, used, carried_over FROM employee_leave_balance WHERE employee_id=? AND year=? AND leave_type='annual'");
            $prevBal->execute([$empId, $prevYear]);
            $prev = $prevBal->fetch();
            if ($prev) {
                $unused  = max(0, (float)$prev['allocated'] + (float)$prev['carried_over'] - (float)$prev['used']);
                $carryOver = min($unused, 5); // Max 5 days carry over
                if ($carryOver > 0) {
                    $db->prepare("
                        INSERT INTO employee_leave_balance (employee_id, year, leave_type, allocated, used, carried_over)
                        VALUES (?, ?, 'annual', 0, 0, ?)
                        ON DUPLICATE KEY UPDATE carried_over = carried_over + ?
                    ")->execute([$empId, $year, $carryOver, $carryOver]);
                }
            }
        }

        $count++;
    }

    echo date('Y-m-d H:i:s') . " — Done. Processed $count employees.\n";
} catch (Exception $e) {
    echo date('Y-m-d H:i:s') . " — ERROR: " . $e->getMessage() . "\n";
    if (defined("RUNNING_AS_INCLUDE")) throw new CronExitException(1); else exit(1);
}