<?php
declare(strict_types=1);
/**
 * cron_check.php — LudoKing server-side cron
 * - Close expired assigned rooms (10 min)
 * - Reset ghost "assigned" rooms
 * - Close waiting rooms idle > 15 min
 * - Delete screenshots older than 24h from disk + DB
 */
require_once __DIR__ . '/../db.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

$secret = trim((string)($_GET['secret'] ?? $_POST['secret'] ?? ''));
$expectedSecret = lk_setting('cron_secret', '');
if ($expectedSecret !== '' && !hash_equals($expectedSecret, $secret)) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'Forbidden']);
    exit;
}

$pdo = lk_pdo();
$closed   = 0;
$reset    = 0;
$expired  = 0;
$ssDeleted = 0;

try {
    // 1) Close assigned rooms whose expires_at has passed
    $closed = (int)$pdo->exec("
        UPDATE rooms SET status='closed', closed_at=NOW()
        WHERE status='assigned'
          AND expires_at IS NOT NULL
          AND expires_at < NOW()
    ");

    // 2) Reset ghost assigned rows
    $reset = (int)$pdo->exec("
        UPDATE rooms SET
            is_assigned=0, status='waiting',
            assigned_at=NULL, expires_at=NULL,
            assigned_to=NULL, instance_id=NULL
        WHERE is_assigned=1
          AND status='waiting'
          AND assigned_at IS NOT NULL
          AND assigned_at < DATE_SUB(NOW(), INTERVAL 30 MINUTE)
    ");

    // 3) Close stale waiting rooms (expires_at passed OR 15 min since created if no expires_at)
    $expired = (int)$pdo->exec("
        UPDATE rooms SET status='closed', closed_at=NOW()
        WHERE status='waiting'
          AND is_assigned=0
          AND (
            (expires_at IS NOT NULL AND expires_at < NOW())
            OR (expires_at IS NULL AND created_at < DATE_SUB(NOW(), INTERVAL 15 MINUTE))
          )
    ");

    // 4) Delete screenshots older than 24h
    //    Find rooms with screenshot_path set and created_at > 24h ago
    $uploadBase = __DIR__ . '/../';
    $staleShots = $pdo->query("
        SELECT id, screenshot_path
        FROM rooms
        WHERE screenshot_path IS NOT NULL
          AND screenshot_path != ''
          AND created_at < DATE_SUB(NOW(), INTERVAL 24 HOUR)
    ");
    $staleRows = $staleShots ? $staleShots->fetchAll(PDO::FETCH_ASSOC) : [];

    $idsToClean = [];
    foreach ($staleRows as $row) {
        $path = trim((string)($row['screenshot_path'] ?? ''));
        if ($path !== '') {
            $fullPath = $uploadBase . $path;
            if (is_file($fullPath)) {
                @unlink($fullPath);
                $ssDeleted++;
            }
        }
        $idsToClean[] = (int)$row['id'];
    }

    // Clear screenshot_path in DB for cleaned rows
    if (!empty($idsToClean)) {
        $ph = implode(',', array_fill(0, count($idsToClean), '?'));
        $pdo->prepare("UPDATE rooms SET screenshot_path=NULL WHERE id IN ($ph)")
            ->execute($idsToClean);
    }

    echo json_encode([
        'ok'               => true,
        'closed_expired'   => $closed,
        'reset_ghost'      => $reset,
        'expired_waiting'  => $expired,
        'screenshots_deleted' => $ssDeleted,
        'time'             => date('Y-m-d H:i:s'),
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
