<?php
declare(strict_types=1);
/**
 * room_info.php — Bot polls this to detect room closed/expired
 * Query by: instance_id (bot's device serial, e.g. emulator-5556)
 * OR room_code fallback (if instance_id not matched)
 */
require_once __DIR__ . '/../db.php';

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

function ri_out(array $d, int $s = 200): void {
    http_response_code($s);
    echo json_encode($d, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$instanceId = trim((string)($_GET['instance_id'] ?? $_POST['instance_id'] ?? ''));
$roomCode   = trim((string)($_GET['room_code']   ?? $_POST['room_code']   ?? ''));

if ($instanceId === '' && $roomCode === '') {
    ri_out(['ok'=>false,'error'=>'instance_id or room_code required'], 400);
}

$pdo = lk_pdo();

try {
    $room = null;

    // ── Column list shared across both queries ──
    // Also fetch (expires_at < NOW()) from MySQL so compare is on DB clock (no PHP timezone skew)
    $cols = "id, room_code, status, is_assigned,
             assigned_to, assigned_at, expires_at,
             started_at, closed_at, screenshot_path, instance_id,
             UNIX_TIMESTAMP(expires_at) AS expires_at_epoch_db,
             (expires_at IS NOT NULL AND expires_at < NOW()) AS db_is_expired";

    // 1) room_code is always the most specific match — prefer it first
    //    (instance_id can match OLD closed rooms from same emulator — causes wrong expire detection)
    if ($roomCode !== '') {
        $r = $pdo->prepare("
            SELECT $cols
            FROM rooms
            WHERE room_code=?
            ORDER BY id DESC LIMIT 1
        ");
        $r->execute([$roomCode]);
        $room = $r->fetch(PDO::FETCH_ASSOC) ?: null;
    }

    // 2) Fallback: instance_id — only used when bot has no room_code yet (startup)
    if (!$room && $instanceId !== '') {
        $r = $pdo->prepare("
            SELECT $cols
            FROM rooms
            WHERE instance_id=?
            ORDER BY id DESC LIMIT 1
        ");
        $r->execute([$instanceId]);
        $room = $r->fetch(PDO::FETCH_ASSOC) ?: null;
    }

    if (!$room) {
        ri_out(['ok'=>false,'error'=>'Room not found']);
    }

    // ── Use DB-computed expiry (MySQL NOW() vs expires_at — avoids PHP timezone skew) ──
    $isExpired    = (bool)(int)($room['db_is_expired'] ?? 0);
    $expiresEpoch = $room['expires_at_epoch_db'] ? (int)$room['expires_at_epoch_db'] : null;

    // ── Inline expire: bot polls every 5s — if time passed, close it NOW ──
    if ($isExpired && (string)($room['status'] ?? '') === 'assigned') {
        try {
            $pdo->prepare("UPDATE rooms SET status='closed', closed_at=NOW() WHERE id=? AND status='assigned'")
                ->execute([(int)$room['id']]);
            $room['status'] = 'closed';
        } catch (Throwable $e) {}
    }

    $room['expires_at_epoch'] = $expiresEpoch ?: null;
    $room['is_expired']       = $isExpired;
    $room['server_time']      = time(); // bot uses this instead of local time

    // bot.py reads js.get('data') — must return under 'data' key
    ri_out([
        'ok'   => true,
        'data' => $room,
        'room' => $room,
    ]);
} catch (Throwable $e) {
    ri_out(['ok'=>false,'error'=>$e->getMessage()], 500);
}
