<?php
// CORS Headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once '../config/database.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'] ?? '';
$student_email = $data['student_email'] ?? '';
$student_name = $data['student_name'] ?? '';
$roll_no = $data['roll_no'] ?? '';
$exam_code = $data['exam_code'] ?? '';
$answers = $data['answers'] ?? [];
$time_remaining = $data['time_remaining'] ?? 0;
$current_question = $data['current_question'] ?? 0;
$total_questions = $data['total_questions'] ?? 0;

if (empty($session_token)) {
    http_response_code(400);
    die(json_encode(['error' => 'Session token required']));
}

try {
    // Calculate answered count
    $answered_count = 0;
    foreach ($answers as $qid => $choices) {
        if (is_array($choices) && count($choices) > 0) {
            $answered_count++;
        }
    }

    $answers_json = json_encode($answers);
    $now = date('Y-m-d H:i:s');

    // Check if progress record exists
    $stmt = $pdo->prepare("SELECT id FROM exam_progress WHERE session_token = ?");
    $stmt->execute([$session_token]);
    $existing = $stmt->fetch();

    if ($existing) {
        // Update existing progress
        $stmt = $pdo->prepare("
            UPDATE exam_progress SET 
                answers_json = ?,
                time_remaining = ?,
                current_question = ?,
                answered_count = ?,
                last_sync = ?
            WHERE session_token = ?
        ");
        $stmt->execute([
            $answers_json,
            $time_remaining,
            $current_question,
            $answered_count,
            $now,
            $session_token
        ]);
    } else {
        // Insert new progress record
        $stmt = $pdo->prepare("
            INSERT INTO exam_progress (
                session_token, student_email, student_name, roll_no, exam_code,
                answers_json, time_remaining, current_question, total_questions,
                answered_count, last_sync, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $session_token,
            $student_email,
            $student_name,
            $roll_no,
            $exam_code,
            $answers_json,
            $time_remaining,
            $current_question,
            $total_questions,
            $answered_count,
            $now,
            $now
        ]);
    }

    // ALSO save each answer to learner_responses table for grading
    foreach ($answers as $qid => $choices) {
        if (is_array($choices) && count($choices) > 0) {
            $selected_choice = implode(',', $choices);
            $stmt = $pdo->prepare("
                INSERT INTO learner_responses (session_token, question_id, selected_choice, response_time_seconds, answered_at)
                VALUES (?, ?, ?, 0, NOW())
                ON DUPLICATE KEY UPDATE 
                    selected_choice = VALUES(selected_choice),
                    answered_at = NOW()
            ");
            $stmt->execute([$session_token, intval($qid), $selected_choice]);
        }
    }

    // Also update time in active_sessions
    $stmt = $pdo->prepare("
        UPDATE active_sessions SET 
            time_left_seconds = ?,
            current_question_index = ?,
            questions_answered = ?
        WHERE session_token = ?
    ");
    $stmt->execute([$time_remaining, $current_question, $answered_count, $session_token]);

    echo json_encode([
        'success' => true,
        'message' => 'Progress synced',
        'answers_saved' => $answered_count,
        'synced_at' => $now
    ]);

} catch (PDOException $e) {
    error_log("sync-progress.php error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Database error', 'details' => $e->getMessage()]);
}
?>
