<?php
declare(strict_types=1);

/**
 * Cron Runner — execute via: php cron/runner.php
 * Should be called by system crontab every hour (or as configured).
 */

$basePath = dirname(__DIR__);
require_once $basePath . '/vendor/autoload.php';

$app = \App\Core\App::getInstance();
$app->boot();

$db = $app->db();
$jobFiles = glob($basePath . '/cron/jobs/*.php');

echo "[" . date('Y-m-d H:i:s') . "] Cron runner started. Found " . count($jobFiles) . " jobs.\n";

foreach ($jobFiles as $jobFile) {
    $className = pathinfo($jobFile, PATHINFO_FILENAME);
    require_once $jobFile;

    $fullClass = "CronJobs\\{$className}";
    if (!class_exists($fullClass)) {
        echo "  [SKIP] Class {$fullClass} not found in {$jobFile}\n";
        continue;
    }

    $job = new $fullClass($db);

    if (!$job->shouldRun()) {
        continue;
    }

    $startTime = microtime(true);
    $logId = $db->insert('cron_job_log', [
        'job_name'   => $className,
        'started_at' => date('Y-m-d H:i:s'),
        'status'     => 'running',
    ]);

    echo "  [RUN] {$className}...";

    try {
        $result = $job->run();
        $elapsed = (int) ((microtime(true) - $startTime) * 1000);

        $db->update('cron_job_log', [
            'finished_at'       => date('Y-m-d H:i:s'),
            'status'            => 'completed',
            'records_processed' => $result['processed'] ?? 0,
            'execution_time_ms' => $elapsed,
        ], '`id` = ?', [$logId]);

        echo " OK ({$elapsed}ms, " . ($result['processed'] ?? 0) . " records)\n";
    } catch (\Throwable $e) {
        $elapsed = (int) ((microtime(true) - $startTime) * 1000);

        $db->update('cron_job_log', [
            'finished_at'       => date('Y-m-d H:i:s'),
            'status'            => 'failed',
            'error_message'     => $e->getMessage(),
            'execution_time_ms' => $elapsed,
        ], '`id` = ?', [$logId]);

        echo " FAILED: {$e->getMessage()}\n";
        \App\Core\Logger::error("Cron job {$className} failed: {$e->getMessage()}");
    }
}

// Process notification queue
echo "  [RUN] NotificationQueueProcessor...";
$queueResult = \App\Modules\Notifications\Services\SmsService::processQueue(100);
echo " sent={$queueResult['sent']}, failed={$queueResult['failed']}\n";

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