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

header('Content-Type: application/json');

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);

$student_code = $data['student_code'] ?? '';
$student_email = $data['student_email'] ?? '';
$student_name = $data['student_name'] ?? '';
$roll_no = $data['roll_no'] ?? '';
$exam_code = $data['exam_code'] ?? '';

if (empty($exam_code)) {
    http_response_code(400);
    die(json_encode(['success' => false, 'message' => 'Exam code is required']));
}

if (empty($student_code) && empty($student_email)) {
    http_response_code(400);
    die(json_encode(['success' => false, 'message' => 'Student code or email is required']));
}

/**
 * Shuffle questions and options using session token as seed
 */
function shuffleQuestionsWithSeed($questions, $seed) {
    $numericSeed = crc32($seed);
    mt_srand($numericSeed);
    
    $shuffledQuestions = $questions;
    $count = count($shuffledQuestions);
    for ($i = $count - 1; $i > 0; $i--) {
        $j = mt_rand(0, $i);
        $temp = $shuffledQuestions[$i];
        $shuffledQuestions[$i] = $shuffledQuestions[$j];
        $shuffledQuestions[$j] = $temp;
    }
    
    foreach ($shuffledQuestions as &$question) {
        $question = shuffleOptionsWithSeed($question, $seed . $question['id']);
    }
    
    return $shuffledQuestions;
}

/**
 * Shuffle options A,B,C,D for a question
 */
function shuffleOptionsWithSeed($question, $seed) {
    $numericSeed = crc32($seed);
    mt_srand($numericSeed);
    
    $options = [
        'A' => $question['option_a'] ?? '',
        'B' => $question['option_b'] ?? '',
        'C' => $question['option_c'] ?? '',
        'D' => $question['option_d'] ?? ''
    ];
    
    $correctAnswers = $question['correct_answers'] ?? 'A';
    $correctLetters = array_map('trim', explode(',', strtoupper($correctAnswers)));
    $isMultiAnswer = isset($question['is_multi_answer']) ? (bool)$question['is_multi_answer'] : (count($correctLetters) > 1);
    
    $keys = array_keys($options);
    $count = count($keys);
    for ($i = $count - 1; $i > 0; $i--) {
        $j = mt_rand(0, $i);
        $temp = $keys[$i];
        $keys[$i] = $keys[$j];
        $keys[$j] = $temp;
    }
    
    $newOptions = [];
    $oldToNew = [];
    $newLetters = ['A', 'B', 'C', 'D'];
    
    foreach ($newLetters as $idx => $newLetter) {
        $oldLetter = $keys[$idx];
        $newOptions[$newLetter] = $options[$oldLetter];
        $oldToNew[$oldLetter] = $newLetter;
    }
    
    $newCorrectAnswers = [];
    foreach ($correctLetters as $oldCorrect) {
        if (isset($oldToNew[$oldCorrect])) {
            $newCorrectAnswers[] = $oldToNew[$oldCorrect];
        }
    }
    sort($newCorrectAnswers);
    
    return [
        'question_id' => $question['id'],
        'question_order' => $question['id'],
        'question_prompt' => $question['title'],
        'choice_a' => $newOptions['A'],
        'choice_b' => $newOptions['B'],
        'choice_c' => $newOptions['C'],
        'choice_d' => $newOptions['D'],
        'point_value' => $question['point_value'] ?? 1.00,
        'is_multi_answer' => $isMultiAnswer,
        'correct_shuffled' => implode(',', $newCorrectAnswers)
    ];
}

try {
    $learner = null;
    
    if (!empty($student_email)) {
        $stmt = $pdo->prepare("SELECT learner_id, full_name, email_address FROM learners WHERE email_address = ?");
        $stmt->execute([$student_email]);
        $learner = $stmt->fetch();
        
        if (!$learner && !empty($student_name)) {
            $auto_code = 'BGNU_' . substr(md5($student_email), 0, 8);
            $stmt = $pdo->prepare("INSERT INTO learners (student_code, full_name, email_address, password_hash, account_type) VALUES (?, ?, ?, ?, 'student')");
            $stmt->execute([$auto_code, $student_name, $student_email, password_hash('dino_temp_' . time(), PASSWORD_DEFAULT)]);
            $learner_id = $pdo->lastInsertId();
            $learner = [
                'learner_id' => $learner_id,
                'full_name' => $student_name,
                'email_address' => $student_email
            ];
        }
    }
    
    if (!$learner && !empty($student_code)) {
        $stmt = $pdo->prepare("SELECT learner_id, full_name, email_address FROM learners WHERE student_code = ?");
        $stmt->execute([$student_code]);
        $learner = $stmt->fetch();
    }

    if (!$learner) {
        http_response_code(404);
        die(json_encode(['success' => false, 'message' => 'Student not found. Please ensure your account is registered.']));
    }

    // Get assessment
    $stmt = $pdo->prepare("SELECT * FROM assessments WHERE exam_code = ? AND assessment_status = 'active'");
    $stmt->execute([$exam_code]);
    $assessment = $stmt->fetch();

    // If FLUTTER2026 doesn't exist, create it automatically
    if (!$assessment && $exam_code === 'FLUTTER2026') {
        $stmt = $pdo->prepare("
            INSERT INTO assessments (exam_code, assessment_title, created_by, total_duration_mins, question_count, scheduled_start, scheduled_end, passing_threshold, assessment_status)
            VALUES ('FLUTTER2026', 'Flutter Basics Exam', ?, 30, 30, NOW(), DATE_ADD(NOW(), INTERVAL 1 YEAR), 50.00, 'active')
        ");
        $stmt->execute([$learner['learner_id']]);
        
        // Fetch the newly created assessment
        $stmt = $pdo->prepare("SELECT * FROM assessments WHERE exam_code = 'FLUTTER2026'");
        $stmt->execute();
        $assessment = $stmt->fetch();
    }

    if (!$assessment) {
        http_response_code(404);
        die(json_encode(['success' => false, 'message' => 'Exam not found or not active']));
    }

    // Check if already started
    $stmt = $pdo->prepare("SELECT * FROM active_sessions WHERE learner_id = ? AND assessment_id = ? AND session_status = 'active'");
    $stmt->execute([$learner['learner_id'], $assessment['assessment_id']]);
    $existing = $stmt->fetch();

    if ($existing) {
        // Resume - get all 30 questions from flutter_questions
        $stmt = $pdo->prepare("SELECT id, title, option_a, option_b, option_c, option_d, correct_answers, is_multi_answer, point_value FROM flutter_questions ORDER BY id ASC LIMIT 30");
        $stmt->execute();
        $questions = $stmt->fetchAll();
        
        $shuffledQuestions = shuffleQuestionsWithSeed($questions, $existing['session_token']);
        
        echo json_encode([
            'success' => true,
            'resumed' => true,
            'session_token' => $existing['session_token'],
            'current_question' => $existing['current_question_index'],
            'time_remaining_seconds' => $existing['time_left_seconds'],
            'exam' => [
                'exam_code' => $assessment['exam_code'],
                'title' => $assessment['assessment_title'],
                'duration_minutes' => $assessment['total_duration_mins'],
                'total_questions' => count($shuffledQuestions),
                'seconds_per_question' => 60
            ],
            'questions' => $shuffledQuestions
        ]);
        exit;
    }

    // Create new session
    $session_token = bin2hex(random_bytes(32));
    $time_seconds = $assessment['total_duration_mins'] * 60;
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

    $stmt = $pdo->prepare("
        INSERT INTO active_sessions (
            session_token, learner_id, assessment_id, time_left_seconds,
            session_started_at, ip_address
        ) VALUES (?, ?, ?, ?, NOW(), ?)
    ");
    $stmt->execute([
        $session_token,
        $learner['learner_id'],
        $assessment['assessment_id'],
        $time_seconds,
        $ip_address
    ]);

    // Get all 30 questions from flutter_questions
    $stmt = $pdo->prepare("SELECT id, title, option_a, option_b, option_c, option_d, correct_answers, is_multi_answer, point_value FROM flutter_questions ORDER BY id ASC LIMIT 30");
    $stmt->execute();
    $questions = $stmt->fetchAll();

    $shuffledQuestions = shuffleQuestionsWithSeed($questions, $session_token);

    echo json_encode([
        'success' => true,
        'session_token' => $session_token,
        'exam' => [
            'exam_code' => $assessment['exam_code'],
            'title' => $assessment['assessment_title'],
            'duration_minutes' => $assessment['total_duration_mins'],
            'total_questions' => count($shuffledQuestions),
            'seconds_per_question' => 60
        ],
        'questions' => $shuffledQuestions,
        'started_at' => date('Y-m-d H:i:s')
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
