<?php
/**
 * Cron Entry Point for Auto-Requisition
 * File: cron/run_auto_requisition.php
 *
 * Add to cPanel Cron Jobs (runs every 6 hours):
 *   0 */6 * * *  php /home/YOURACCOUNT/public_html/cron/run_auto_requisition.php >> /home/YOURACCOUNT/logs/auto_req.log 2>&1
 *
 * Or daily at midnight:
 *   0 0 * * *    php /home/YOURACCOUNT/public_html/cron/run_auto_requisition.php >> /home/YOURACCOUNT/logs/auto_req.log 2>&1
 *
 * NOTE: Replace YOURACCOUNT with your actual cPanel username.
 *       Create the /logs/ directory manually in cPanel File Manager.
 */

// Only allow CLI execution
if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    exit("Access denied.\n");
}

define('AREQ_LPO_DIR', dirname(__DIR__) . '/lpo_pdfs/');
if (!is_dir(AREQ_LPO_DIR)) { mkdir(AREQ_LPO_DIR, 0755, true); }

// Bootstrap
$base = dirname(__DIR__);
require_once $base . '/layouts/dbconn.php';
require_once $base . '/vendor/autoload.php';
require_once $base . '/generate_lpo_pdf.php';

echo "\n[" . date('Y-m-d H:i:s') . "] Auto-Requisition Cron Started\n";
echo str_repeat('-', 50) . "\n";

define('AREQ_AJAX_CONTEXT', true); // suppress browser checks in engine
$result = require $base . '/auto_requisition_check.php';

echo "Created  : {$result['created']}\n";
echo "Emailed  : {$result['emailed']}\n";
echo "Skipped  : {$result['skipped']}\n";
echo "Failed   : {$result['failed']}\n";

if (!empty($result['details'])) {
    echo "\nDetails:\n";
    foreach ($result['details'] as $d) echo "  - {$d}\n";
}
if (!empty($result['errors'])) {
    echo "\nErrors:\n";
    foreach ($result['errors'] as $e) echo "  ! {$e}\n";
}

echo "\n[" . date('Y-m-d H:i:s') . "] Done.\n";