<?php
if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    exit("CLI only\n");
}

$rootPath = dirname(__DIR__);
require_once $rootPath . '/core/db/db.php';
require_once $rootPath . '/core/lib/common.php';
require_once $rootPath . '/core/lib/task_center.php';

$db = \Core\Db\DB::getInstance();
cmsEnsureTaskCenterSchema($db);

$task = 'all';
$force = false;
foreach (array_slice($argv, 1) as $argument) {
    if (strpos($argument, '--task=') === 0) { $task = trim(substr($argument, 7)); }
    if ($argument === '--force') { $force = true; }
}

$allowed = ['all', 'scheduled_publish', 'database_backup'];
if (!in_array($task, $allowed, true)) {
    fwrite(STDERR, "Unknown task. Use --task=all|scheduled_publish|database_backup\n");
    exit(2);
}

$lockDir = $rootPath . '/data/cache';
if (!is_dir($lockDir)) { @mkdir($lockDir, 0755, true); }
$lockHandle = @fopen($lockDir . '/task-scheduler.lock', 'c+');
if (!$lockHandle || !flock($lockHandle, LOCK_EX | LOCK_NB)) {
    if (is_resource($lockHandle)) { fclose($lockHandle); }
    fwrite(STDOUT, "Scheduler is already running.\n");
    exit(0);
}

$output = [];
$actor = ['id' => 0, 'name' => 'system'];

try {
    if ($task === 'all' || $task === 'scheduled_publish') {
        $output['scheduled_publish'] = cmsRunTask($db, 'scheduled_publish', $rootPath, $actor, 'scheduler');
    }

    if ($task === 'all' || $task === 'database_backup') {
        $enabledRow = $db->fetch("SELECT config_value FROM {$db->table('config')} WHERE config_key = 'auto_backup_enabled'");
        $enabled = intval($enabledRow['config_value'] ?? 0) === 1;
        if (!$enabled && !$force) {
            $output['database_backup'] = ['success' => true, 'skipped' => true, 'message' => 'Automatic backup is disabled.'];
        } else {
            $intervalRow = $db->fetch("SELECT config_value FROM {$db->table('config')} WHERE config_key = 'auto_backup_interval'");
            $intervals = ['hourly' => 3600, 'daily' => 86400, 'weekly' => 604800, 'monthly' => 2592000];
            $intervalKey = (string) ($intervalRow['config_value'] ?? 'daily');
            $interval = $intervals[$intervalKey] ?? $intervals['daily'];
            $last = cmsTaskRecentRuns($db, 1, 'database_backup', 'success');
            $lastRun = intval($last[0]['started_at'] ?? 0);
            if (!$force && $lastRun > 0 && $lastRun > time() - $interval) {
                $output['database_backup'] = ['success' => true, 'skipped' => true, 'message' => 'Backup is not due yet.', 'next_at' => $lastRun + $interval];
            } else {
                $output['database_backup'] = cmsRunTask($db, 'database_backup', $rootPath, $actor, 'scheduler');
            }
        }
    }
} catch (Throwable $e) {
    fwrite(STDERR, $e->getMessage() . "\n");
    flock($lockHandle, LOCK_UN);
    fclose($lockHandle);
    exit(1);
}

echo json_encode($output, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
$failed = false;
foreach ($output as $result) { if (empty($result['success'])) { $failed = true; } }
flock($lockHandle, LOCK_UN);
fclose($lockHandle);
exit($failed ? 1 : 0);
