<?php
declare(strict_types=1);
/**
 * rooms_live.php — lightweight JSON endpoint polled by rooms.php every 10s
 * Returns the current first page of rooms (up to 50) for live table update.
 * Auth: same session cookie as admin panel.
 */
require_once __DIR__ . '/../auth.php';
require_admin();
require_once __DIR__ . '/../db.php';

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

$pdo = lk_pdo();

$filterStatus = (string)($_GET['status'] ?? 'all');
if (!in_array($filterStatus, ['all','waiting','assigned','started','closed'], true)) $filterStatus = 'all';
$search = trim((string)($_GET['q'] ?? ''));

$where  = '1=1';
$params = [];
if ($filterStatus !== 'all') { $where .= ' AND status=?'; $params[] = $filterStatus; }
if ($search !== '') {
    $where .= ' AND (room_code LIKE ? OR COALESCE(instance_id,"") LIKE ? OR COALESCE(assigned_to,"") LIKE ?)';
    $s = "%$search%";
    $params = array_merge($params, [$s, $s, $s]);
}

try {
    $st = $pdo->prepare("
        SELECT id, room_code, status, is_assigned,
               instance_id, assigned_to, expires_at, created_at, screenshot_path,
               (expires_at IS NOT NULL AND expires_at < NOW()) AS db_is_expired
        FROM rooms
        WHERE $where
        ORDER BY id DESC
        LIMIT 50
    ");
    $st->execute($params);
    $rows = $st->fetchAll(PDO::FETCH_ASSOC);

    // Counts for tab badges
    $counts = [];
    foreach (['waiting','assigned','started','closed'] as $s2) {
        $c = $pdo->prepare("SELECT COUNT(*) FROM rooms WHERE status=?");
        $c->execute([$s2]);
        $counts[$s2] = (int)$c->fetchColumn();
    }
    $counts['all'] = array_sum($counts);

    echo json_encode(['ok'=>true,'rows'=>$rows,'counts'=>$counts,'ts'=>time()],
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok'=>false,'error'=>$e->getMessage()]);
}
