<?php
// ============================================================
// cron/process_late_penalties.php
// ============================================================
// Runs the late-arrival cascade AUTOMATICALLY for every company —
// no HR login or button click needed. Set this up as a cPanel Cron
// Job to run once a month (see setup instructions at the bottom of
// this file).
//
// Processes the PREVIOUS calendar month (run on the 1st → processes
// last month, once it's fully finished). Safe to re-run — already
// processed days are always skipped (see late_penalty_log).
//
// This file must be run from the command line / cron, NOT from a
// browser — it has no login screen and no session, by design.
// ============================================================

if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    die("This script can only be run from the command line (cron), not a browser.\n");
}

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/late_penalty_engine.php';

$db = Database::getInstance();

// Previous month (if today is Aug 1st, this processes July).
$month = (int)date('n', strtotime('first day of last month'));
$year  = (int)date('Y', strtotime('first day of last month'));

echo "[" . date('Y-m-d H:i:s') . "] Starting automatic late-penalty processing for {$month}/{$year}\n";

$companies = $db->fetchAll("SELECT id, name FROM companies WHERE is_active=1");
$totalProcessed = 0;

foreach ($companies as $company) {
    try {
        $results = processLatePenaltiesForCompany($db, (int)$company['id'], $month, $year, null);
        $count = count($results);
        $totalProcessed += $count;
        echo "  - {$company['name']}: {$count} employee(s) had late penalties applied.\n";
    } catch (Throwable $e) {
        echo "  ! ERROR processing {$company['name']} (id={$company['id']}): " . $e->getMessage() . "\n";
    }
}

echo "[" . date('Y-m-d H:i:s') . "] Done. Total employees affected: {$totalProcessed}\n";

// ============================================================
// CPANEL CRON JOB SETUP (do this once):
//
// 1. cPanel → Cron Jobs
// 2. Common Settings: "Once Per Month" is close, but pick these exact
//    fields so it runs at 2 AM on the 1st of every month:
//      Minute: 0
//      Hour:   2
//      Day:    1
//      Month:  *
//      Weekday: *
// 3. Command — use the FULL server path to PHP and to this file, e.g.:
//      /usr/local/bin/php /home/adrieltech/public_html/seyalix/cron/process_late_penalties.php >> /home/adrieltech/public_html/seyalix/cron/late_penalty.log 2>&1
//    (cPanel → "Errors" or your PHP version's CLI path may differ —
//    if unsure, cPanel's Cron Jobs page usually shows the exact PHP
//    binary path for your account, e.g. /usr/local/bin/ea-php82)
// 4. Save. The log file (late_penalty.log) will show what ran each
//    month, so you can check it any time via File Manager.
// ============================================================
