<?php
// live_dashboard_data.php – JSON feed for live_dashboard.php. Auth-gated.
require_once __DIR__ . '/auth.php';
require_login();

$user    = current_user();
$isSuper = is_super_admin();

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

$params = [];
$facilityScope = '';
if (!$isSuper && $user['facility_id']) {
    $facilityScope = ' AND c.facility_id = ?';
    $params[]      = $user['facility_id'];
}

$sql = "
    SELECT
        s.id, s.station, s.status, s.start_time, s.duration_minutes, s.last_action,
        s.grading_started_at, s.submitted_at,
        c.candidate_number, c.name AS candidate_name,
        u.full_name AS examiner_name,
        GREATEST(
            TIMESTAMPDIFF(SECOND, NOW(), DATE_ADD(s.start_time, INTERVAL s.duration_minutes MINUTE)),
            0
        ) AS remaining_seconds
    FROM osce_sessions s
    JOIN candidates c ON c.id = s.candidate_id
    LEFT JOIN users u ON u.id = s.examiner_id
    WHERE 1=1 $facilityScope
    ORDER BY s.start_time DESC
    LIMIT 200
";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll();
    $out = [];
    foreach ($rows as $r) {
        $out[] = [
            'id'                 => (int)$r['id'],
            'candidate_number'   => $r['candidate_number'],
            'candidate_name'     => $r['candidate_name'],
            'station_name'       => $r['station'],
            'examiner_name'      => $r['examiner_name'],
            'status'             => $r['status'],
            'start_time'         => $r['start_time'],
            'grading_started_at' => $r['grading_started_at'],
            'submitted_at'       => $r['submitted_at'],
            'duration_minutes'   => (int)$r['duration_minutes'],
            'remaining_seconds'  => (int)$r['remaining_seconds'],
            'last_action'        => $r['last_action'],
        ];
    }

    // Recent grading mutations (edits, undos, deletes) for the side panel
    $mods = [];
    try {
        $modSql = "
            SELECT l.id, l.event_type, l.message, l.created_at, l.user_id,
                   u.full_name AS user_name
            FROM osce_logs l
            LEFT JOIN users u ON u.id = l.user_id
            WHERE l.event_type IN ('grade_save','grade_undo','attempt_edit','attempt_soft_delete','attempt_restore','station_check_in')
              AND l.created_at >= (NOW() - INTERVAL 30 MINUTE)
            ORDER BY l.id DESC
            LIMIT 25
        ";
        $modStmt = $pdo->query($modSql);
        $mods = $modStmt->fetchAll();
    } catch (Throwable $e) {
        $mods = [];
    }

    echo json_encode([
        'ok'           => true,
        'rows'         => $out,
        'mods'         => $mods,
        'server_time'  => date('c'),
    ]);
} catch (Throwable $e) {
    error_log('live_dashboard_data: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'server_error']);
}
