<?php
/**
 * SMART CRON RUNNER
 * HANYA INI YANG PERLU DIDAFTARKAN DI cPanel!
 * 
 * Script ini berjalan setiap menit, mengecek cron_registry.php,
 * lalu mengeksekusi cron yang waktunya sudah tiba.
 */
if (php_sapi_name() !== 'cli') die('Access denied. Run via CLI.');

require_once __DIR__ . '/cron_registry.php';

$now = new DateTime();
$currentMinute = (int)$now->format('i');
$currentHour   = (int)$now->format('G');
$currentDay    = (int)$now->format('j');
$currentMonth  = (int)$now->format('n');
$currentWeekday= (int)$now->format('w'); // 0=Minggu

$logDir = __DIR__ . '/logs';
if (!is_dir($logDir)) mkdir($logDir, 0755, true);

foreach ($cronRegistry as $slug => $cron) {
    // Parse schedule (format: menit jam tanggal bulan hari-minggu)
    $parts = preg_split('/\s+/', trim($cron['schedule']));
    if (count($parts) !== 5) continue;
    
    list($sMin, $sHour, $sDay, $sMonth, $sWeek) = $parts;
    
    // Cek kecocokan waktu
    $match = true;
    if ($sMin !== '*' && (int)$sMin !== $currentMinute) $match = false;
    if ($sHour !== '*' && (int)$sHour !== $currentHour) $match = false;
    if ($sDay !== '*' && (int)$sDay !== $currentDay) $match = false;
    if ($sMonth !== '*' && (int)$sMonth !== $currentMonth) $match = false;
    if ($sWeek !== '*' && (int)$sWeek !== $currentWeekday) $match = false;
    
    if (!$match) continue;
    
    // Cek apakah sudah dijalankan hari ini (mencegah duplikasi)
    $today = $now->format('Y-m-d');
    $lockFile = $logDir . '/' . $slug . '_' . $today . '.lock';
    
    if (file_exists($lockFile)) {
        continue; // Sudah dijalankan hari ini, lewati
    }
    
    // Eksekusi cron
    $logFile = $logDir . '/' . $slug . '_' . $today . '.log';
    
    ob_start();
    echo "=== Executing: {$cron['name']} | " . $now->format('Y-m-d H:i:s') . " ===\n";
    
    try {
    if (file_exists($cron['file'])) {
        $GLOBALS['CRON_MANAGER_EXEC'] = true;
        include $cron['file'];
        unset($GLOBALS['CRON_MANAGER_EXEC']);
        } else {
            echo "ERROR: File {$cron['file']} tidak ditemukan!\n";
        }
    } catch (\Throwable $e) {
        echo "ERROR: " . $e->getMessage() . "\n";
    }
    
    echo "=== Finished ===\n";
    $output = ob_get_clean();
    
    // Simpan log
    file_put_contents($logFile, $output, FILE_APPEND);
    
    // Buat lock file agar tidak dijalankan lagi di hari yang sama
    file_put_contents($lockFile, $now->format('Y-m-d H:i:s'));
}