<?php
require_once '../config/database.php';
header('Content-Type: application/json');

// Simple auth check for dashboard
session_start();
if (!isset($_SESSION['account_type']) || $_SESSION['account_type'] !== 'instructor') {
    http_response_code(401);
    die(json_encode(['error' => 'Unauthorized']));
}

try {
    // Get all active sessions with student details
    $stmt = $pdo->query("
        SELECT 
            s.session_id,
            l.student_code,
            l.full_name,
            a.exam_code,
            a.assessment_title,
            s.current_question_index,
            a.question_count,
            s.questions_answered,
            s.time_left_seconds,
            s.window_focus_status,
            s.network_connectivity,
            s.session_started_at,
            s.last_activity_ping,
            s.session_status,
            s.termination_reason,
            TIMESTAMPDIFF(SECOND, s.last_activity_ping, NOW()) AS seconds_since_ping
        FROM active_sessions s
        JOIN learners l ON s.learner_id = l.learner_id
        JOIN assessments a ON s.assessment_id = a.assessment_id
        WHERE s.session_status = 'active'
        ORDER BY s.last_activity_ping DESC
    ");

    $sessions = $stmt->fetchAll();

    // Determine status for each student
    $live_sessions = [];
    foreach ($sessions as $session) {
        // Format time remaining
        $hours = floor($session['time_left_seconds'] / 3600);
        $minutes = floor(($session['time_left_seconds'] % 3600) / 60);
        $seconds = $session['time_left_seconds'] % 60;
        $time_formatted = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);

        // Determine status based on window focus and heartbeat
        $status = '🟢 Active';
        $status_code = 'active';

        if ($session['seconds_since_ping'] > 60) {
            $status = '🔴 Disconnected';
            $status_code = 'disconnected';
        } elseif ($session['window_focus_status'] !== 'FOCUSED') {
            $status = '⚠️ Warning';
            $status_code = 'warning';
        }

        $live_sessions[] = [
            'id' => $session['session_id'],
            'student_id' => $session['student_code'],
            'student_name' => $session['full_name'],
            'exam_code' => $session['exam_code'],
            'progress' => $session['current_question_index'] . ' / ' . $session['question_count'],
            'answered_count' => $session['questions_answered'],
            'time_left' => $time_formatted,
            'status' => $status,
            'status_code' => $status_code,
            'window_status' => $session['window_focus_status'],
            'network' => $session['network_connectivity'],
            'last_ping_seconds_ago' => $session['seconds_since_ping']
        ];
    }

    echo json_encode([
        'success' => true,
        'total_active' => count($live_sessions),
        'sessions' => $live_sessions,
        'timestamp' => date('Y-m-d H:i:s')
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to fetch sessions', 'details' => $e->getMessage()]);
}
?>
