<?php
// includes/cron_update_trans_period.php
//
// Intended to run once daily via cPanel Cron Jobs, NOT via a browser.
// Rolls trans_period.min_date forward to the current day, for every
// company that has auto-lock enabled (trans_period_auto_lock.YN = 1)
// AND whose configured timelock has already passed for the current run.
//
// IMPORTANT: if different companies can have different timelock values,
// this cron needs to run more frequently than once/day (e.g. every 15-30
// min) so each company gets caught shortly after its own timelock passes,
// not just companies whose timelock happens to be before this cron's
// single fixed run time. See conversation notes before deploying.
// See cron setup notes for schedule + server-timezone caveat.

require_once __DIR__ . "/db.php"; // provides $pdo

try {
    $stmt = $pdo->prepare("
        UPDATE trans_period p
        JOIN trans_period_auto_lock t
            ON p.co_id = t.co_id
        SET p.min_date = DATE_SUB(CURDATE(), INTERVAL 1 DAY)
        WHERE t.YN = 1
          AND CURTIME() > t.time_lock
    ");
    $stmt->execute();

    $rows_affected = $stmt->rowCount();
    $msg = "[cron_update_trans_period] OK — min_date updated for {$rows_affected} company(ies) with auto-lock enabled.";
    error_log($msg);
    echo $msg . "\n";

} catch (PDOException $e) {
    error_log("[cron_update_trans_period] FAILED: " . $e->getMessage());
    // Non-zero exit code is what actually signals failure to cron/cPanel's
    // failure-notification emails — http_response_code() would be a no-op here.
    exit(1);
}