<?php
/**
 * MJ ERP HUB - Cron Sync Runner
 *
 * cPanel Cron Job (recommended, if SSH/CLI available):
 *   php /home/USERNAME/public_html/mj-erp/cron/run_sync.php
 *   Suggested schedule: every 30 minutes (cron expression: 30 mins interval)
 *
 * If your host ONLY allows "URL cron" (wget/curl a URL, no CLI):
 *   https://erp.yourdomain.com/cron/run_sync.php?token=YOUR_CRON_TOKEN
 *   Set CRON_TOKEN below to a long random string and use it in the cron URL.
 *   Cron jobs run via web must never be left without this token check.
 */

define('CRON_TOKEN', 'CHANGE_ME_TO_A_LONG_RANDOM_STRING');

$isCli = (php_sapi_name() === 'cli');

if (!$isCli) {
    // Web-triggered cron must present the correct token
    if (!isset($_GET['token']) || $_GET['token'] !== CRON_TOKEN) {
        http_response_code(403);
        die('Forbidden');
    }
    header('Content-Type: text/plain');
}

require_once __DIR__ . '/../config/config.php';

$start = microtime(true);
echo "MJ ERP Sync started at " . date('Y-m-d H:i:s') . "\n";

$results = SyncEngine::runAll();

foreach ($results as $r) {
    $line = sprintf("[%s] %-10s %-10s -> %s", strtoupper($r['status']), $r['system'], $r['type'], $r['message']);
    echo $line . "\n";
}

$elapsed = round(microtime(true) - $start, 2);
echo "Sync completed in {$elapsed}s\n";