<?php
require_once '../config/database.php';
require_once 'verify-browser.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die(json_encode(['error' => 'Method not allowed']));
}

$data = json_decode(file_get_contents('php://input'), true);

$session_token = $data['session_token'] ?? '';
$current_question = $data['current_question'] ?? 1;
$answered = $data['answered'] ?? 0;
$time_remaining = $data['time_remaining'] ?? '00:00:00';
$window_status = $data['window_status'] ?? 'FOCUSED';
$network = $data['network'] ?? 'ONLINE';

// INSTANT CHEATING DETECTION - Terminate if window not focused
if ($window_status === 'BLURRED' || $window_status === 'HIDDEN') {
    try {
        // Log violation
        $pdo->prepare("
            INSERT INTO security_violations (session_token, violation_type, violation_severity, violation_details, action_taken)
            VALUES (?, ?, ?, ?, ?)
        ")->execute([
            $session_token,
            'window_blur',
            'critical',
            json_encode(['window_status' => $window_status, 'timestamp' => date('Y-m-d H:i:s')]),
            'terminated'
        ]);

        // TERMINATE SESSION IMMEDIATELY
        $pdo->prepare("
            UPDATE active_sessions 
            SET session_status = 'terminated',
                termination_reason = 'Cheating detected: Window focus lost (Alt+Tab or similar)',
                submitted_at = NOW()
            WHERE session_token = ?
        ")->execute([$session_token]);

        http_response_code(403);
        echo json_encode([
            'error' => 'EXAM_TERMINATED',
            'message' => 'Your exam has been terminated due to cheating detection.',
            'reason' => 'Window focus lost',
            'should_continue' => false,
            'terminate_immediately' => true
        ]);
        exit;

    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to process violation']);
        exit;
    }
}

// Convert time string to seconds
list($hours, $minutes, $seconds) = explode(':', $time_remaining);
$time_in_seconds = ($hours * 3600) + ($minutes * 60) + $seconds;

try {
    // Update progress
    $stmt = $pdo->prepare("
        UPDATE active_sessions 
        SET current_question_index = ?,
            questions_answered = ?,
            time_left_seconds = ?,
            window_focus_status = ?,
            network_connectivity = ?,
            last_activity_ping = NOW()
        WHERE session_token = ? AND session_status = 'active'
    ");

    $stmt->execute([
        $current_question,
        $answered,
        $time_in_seconds,
        $window_status,
        $network,
        $session_token
    ]);

    if ($stmt->rowCount() === 0) {
        // Session not found or already terminated
        $check = $pdo->prepare("SELECT session_status, termination_reason FROM active_sessions WHERE session_token = ?");
        $check->execute([$session_token]);
        $session = $check->fetch();

        if ($session && $session['session_status'] === 'terminated') {
            http_response_code(403);
            echo json_encode([
                'error' => 'EXAM_TERMINATED',
                'message' => 'Your exam was terminated',
                'reason' => $session['termination_reason'],
                'should_continue' => false,
                'terminate_immediately' => true
            ]);
            exit;
        }
    }

    echo json_encode([
        'success' => true,
        'message' => 'Progress updated',
        'should_continue' => true,
        'timestamp' => date('Y-m-d H:i:s')
    ]);

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