<?php
date_default_timezone_set('Africa/Lusaka');
session_start();
include "../include/config.php";

if(!isset($_SESSION['studentid'])){
    header("location:../index.php");
    exit();
}
$studentid = $_SESSION['studentid'];

$exam_id = intval($_GET['exam_id'] ?? 0);
if(!$exam_id){
    die("Invalid exam selected.");
}

$exam = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM exam_schedule WHERE id='$exam_id'"));
if(!$exam){
    die("Exam not found.");
}

$check_submitted = mysqli_fetch_assoc(mysqli_query(
    $conn,
    "SELECT * FROM exam_results_summary WHERE exam_id='$exam_id' AND student_id='$studentid'"
));
if($check_submitted){
    die("<div style='margin:50px;font-family:sans-serif;color:red;'>
        <h3>You already submitted this exam.</h3>
        <p>Score: <b>{$check_submitted['score']} / {$check_submitted['total']}</b></p>
        <p>Submitted on: {$check_submitted['submitted_at']}</p>
        <a href='viewexam.php'>Back to Exams</a>
    </div>");
}

// Helper functions for answer comparison
function normalizeAnswer($answer) {
    if(empty($answer)) return '';
    
    // Convert to lowercase
    $answer = strtolower(trim($answer));
    
    // Remove all types of whitespace and normalize spaces
    $answer = preg_replace('/\s+/', ' ', $answer);
    $answer = trim($answer);
    
    // Remove common punctuation that might cause mismatches
    $answer = preg_replace('/[.,;:!?]\s*$/', '', $answer);
    
    return $answer;
}

function compareAnswers($student_answer, $correct_answer) {
    if(empty($student_answer) || empty($correct_answer)) {
        return false;
    }
    
    $student_normalized = normalizeAnswer($student_answer);
    $correct_normalized = normalizeAnswer($correct_answer);
    
    // Exact match
    if($student_normalized === $correct_normalized) {
        return true;
    }
    
    // Similarity check for text answers (allows minor typos)
    similar_text($student_normalized, $correct_normalized, $similarity);
    if($similarity > 90) {
        return true;
    }
    
    return false;
}

// Initialize session storage for this exam
if(!isset($_SESSION['exam_data'][$exam_id])) {
    $_SESSION['exam_data'][$exam_id] = [
        'questions' => [],
        'correct_answers' => [],
        'student_answers' => [],
        'shuffled_options' => []
    ];
}

// Decode question IDs stored as JSON
$question_ids = json_decode($exam['question_ids'], true); 
$question_ids = array_map('intval', $question_ids); 

// ✅ Initialize exam session data ONCE per exam
if(empty($_SESSION['exam_data'][$exam_id]['questions'])){
    shuffle($question_ids); // random order
    
    // ✅ Store correct answers in session for grading (not exposed to student)
    $correct_answers = [];
    $questions_data = [];
    
    if(count($question_ids) > 0){
        $ids = implode(',', $question_ids);
        // ✅ DON'T select the answer field to prevent exposure
        $q_res = mysqli_query($conn, "SELECT id, question, type, options FROM exam_questions WHERE id IN ($ids)");
        while($row = mysqli_fetch_assoc($q_res)){
            // Get correct answer separately for grading (not exposed to frontend)
            $correct_answer_res = mysqli_query($conn, "SELECT answer FROM exam_questions WHERE id = '{$row['id']}'");
            $correct_answer_row = mysqli_fetch_assoc($correct_answer_res);
            $correct_answers[$row['id']] = normalizeAnswer(trim($correct_answer_row['answer']));
            
            $questions_data[$row['id']] = [
                'question' => $row['question'],
                'type' => $row['type'],
                'options' => $row['type'] == 'multiple_choice' ? json_decode($row['options'], true) : null
            ];
        }
    }
    
    $_SESSION['exam_data'][$exam_id]['questions'] = $question_ids; // shuffled order
    $_SESSION['exam_data'][$exam_id]['correct_answers'] = $correct_answers;
    $_SESSION['exam_data'][$exam_id]['questions_data'] = $questions_data;
    
    // ✅ Load any previously saved answers from database
    $saved_answers = [];
    $answers_result = mysqli_query($conn, "SELECT question_id, answer FROM exam_results 
                                          WHERE exam_id='$exam_id' AND student_id='$studentid'");
    while($row = mysqli_fetch_assoc($answers_result)){
        if(!empty(trim($row['answer']))) {
            $_SESSION['exam_data'][$exam_id]['student_answers'][$row['question_id']] = trim($row['answer']);
        }
    }
}

$question_ids = $_SESSION['exam_data'][$exam_id]['questions'];
$questions_data = $_SESSION['exam_data'][$exam_id]['questions_data'];

// Build questions array in shuffled order (WITHOUT ANSWERS)
$questions = [];
foreach($question_ids as $qid) {
    if(isset($questions_data[$qid])) {
        $questions[] = [
            'id' => $qid,
            'question' => $questions_data[$qid]['question'],
            'type' => $questions_data[$qid]['type'],
            'options' => $questions_data[$qid]['options']
        ];
    }
}

// ✅ Save answer on Next/Prev navigation
if(isset($_POST['save_and_next']) || isset($_POST['save_and_prev'])){
    $q_id = intval($_POST['current_question']);
    $answer = $_POST['answers'][$q_id] ?? '';
    $escaped_answer = $conn->real_escape_string(trim($answer));
    
    // ✅ Store in session immediately
    $_SESSION['exam_data'][$exam_id]['student_answers'][$q_id] = trim($answer);
    
    // ✅ Also save to database for persistence
    mysqli_query($conn, "INSERT INTO exam_results 
        (exam_id, student_id, question_id, answer, submitted_at) 
        VALUES ('$exam_id','$studentid','$q_id','$escaped_answer', NOW())
        ON DUPLICATE KEY UPDATE answer='$escaped_answer', submitted_at=NOW()");

    $next_index = intval($_POST['q_index']);
    if(isset($_POST['save_and_next'])) $next_index++;
    if(isset($_POST['save_and_prev'])) $next_index--;

    header("Location: ?exam_id=$exam_id&q=$next_index");
    exit();
}

// ✅ Final submission - IMPROVED answer comparison
if(isset($_POST['submit_exam'])){
    // ✅ Save any final answers from the form
    if (!empty($_POST['answers'])) {
        foreach ($_POST['answers'] as $q_id => $answer) {
            $escaped_answer = $conn->real_escape_string(trim($answer));
            $_SESSION['exam_data'][$exam_id]['student_answers'][$q_id] = trim($answer);
            
            mysqli_query($conn, "INSERT INTO exam_results 
                (exam_id, student_id, question_id, answer, submitted_at) 
                VALUES ('$exam_id','$studentid','$q_id','$escaped_answer', NOW())
                ON DUPLICATE KEY UPDATE answer='$escaped_answer', submitted_at=NOW()");
        }
    }

    $correct_count = 0;
    $total_questions = count($questions);

    // ✅ Use session-stored answers and correct answers for comparison
    $student_answers = $_SESSION['exam_data'][$exam_id]['student_answers'] ?? [];
    $correct_answers = $_SESSION['exam_data'][$exam_id]['correct_answers'] ?? [];
    
    foreach($questions as $q){
        $q_id = $q['id'];
        $student_answer = isset($student_answers[$q_id]) ? $student_answers[$q_id] : '';
        $correct_answer = $correct_answers[$q_id] ?? '';
        
        // ✅ Enhanced comparison with multiple normalization strategies
        if(compareAnswers($student_answer, $correct_answer)){
            $correct_count++;
        }
    }

    // ✅ Update results table with CA marks
    $course  = $conn->real_escape_string($exam['course']);
    $intake  = $conn->real_escape_string($exam['intake']);
    $program = $conn->real_escape_string($exam['program']);
    $year    = $conn->real_escape_string($exam['year']);
    $term    = $conn->real_escape_string($exam['period']);
    $new_ca  = intval($correct_count);

    $result_check = mysqli_query($conn, "SELECT ca, ca1, ca2 
                                         FROM results 
                                         WHERE studentid='$studentid' 
                                         AND course='$course' 
                                         AND intake='$intake' 
                                         AND term='$term' 
                                         AND year='$year'");

    if(mysqli_num_rows($result_check) > 0) {
        $row = mysqli_fetch_assoc($result_check);
        
        // Check in order: ca → ca1 → ca2
        if(empty($row['ca']) || $row['ca'] === '' || $row['ca'] === null) {
            $conn->query("UPDATE results 
                          SET ca = $new_ca 
                          WHERE studentid='$studentid' 
                          AND course='$course' 
                          AND intake='$intake' 
                          AND term='$term' 
                          AND year='$year'");
        } 
        else if(empty($row['ca1']) || $row['ca1'] === '' || $row['ca1'] === null) {
            $conn->query("UPDATE results 
                          SET ca1 = $new_ca 
                          WHERE studentid='$studentid' 
                          AND course='$course' 
                          AND intake='$intake' 
                          AND term='$term' 
                          AND year='$year'");
        }
        else if(empty($row['ca2']) || $row['ca2'] === '' || $row['ca2'] === null) {
            $conn->query("UPDATE results 
                          SET ca2 = $new_ca 
                          WHERE studentid='$studentid' 
                          AND course='$course' 
                          AND intake='$intake' 
                          AND term='$term' 
                          AND year='$year'");
        }
        else {
            $conn->query("UPDATE results 
                          SET ca = $new_ca 
                          WHERE studentid='$studentid' 
                          AND course='$course' 
                          AND intake='$intake' 
                          AND term='$term' 
                          AND year='$year'");
        }
    } else {
        $conn->query("INSERT INTO results 
                      (studentid, course, intake, term, year, ca) 
                      VALUES ('$studentid', '$course', '$intake', '$term', '$year', $new_ca)");
    }

    mysqli_query($conn, "INSERT INTO exam_results_summary 
        (exam_id, student_id, score, total, submitted_at, status)
        VALUES ('$exam_id','$studentid','$correct_count','$total_questions', NOW(),'locked')");
    
    // ✅ CLEANUP: Remove session data for this exam
    unset($_SESSION['exam_data'][$exam_id]);
    
    echo "<script>alert('Exam submitted! You scored $correct_count out of $total_questions');window.location='viewexam.php';</script>";
    exit();
}

// Exam availability
$current_time = date('H:i:s');
if($current_time < $exam['start_time']){
    $available = false;
    $msg = "Exam not available yet. Starts at " . $exam['start_time'];
} elseif($current_time > $exam['end_time']){
    $available = false;
    $msg = "Exam has ended at " . $exam['end_time'];
} else {
    $available = true;
}

// Countdown
$endTimestamp = strtotime($exam['exam_date'] . ' ' . $exam['end_time']);
$timeLeft = max(0, $endTimestamp - time());

// Current question index
$current_index = isset($_GET['q']) ? intval($_GET['q']) : 0;
if ($current_index < 0) $current_index = 0;
if ($current_index >= count($questions)) $current_index = count($questions) - 1;

// Get current answer from session
$current_answer = $_SESSION['exam_data'][$exam_id]['student_answers'][$questions[$current_index]['id']] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Online Exam</title>
    <link rel="stylesheet" href="../../boostrap/1.css">
    <link rel="stylesheet" href="../../boostrap/2.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300&family=Source+Sans+Pro:wght@300&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="icon" href="favicon.png" type="image/png">
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <meta name="theme-color" content="#238665">
    <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Signika+Negative:wght@300..700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="res/bootstrap@5.2.0.min.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Rowdies:wght@300;400;700&display=swap" rel="stylesheet">
</head>
<style>
body{background:#f8f9fc;font-family:'Segoe UI',sans-serif;}
.card{border-radius:10px;box-shadow:0 0.15rem 1.75rem rgba(58,59,69,0.15);}
.card-header{background:linear-gradient(90deg,#4e73df,#6f42c1);color:white;}
.option-label{display:block;padding:12px 15px;margin-bottom:8px;border:1px solid #e3e6f0;border-radius:8px;cursor:pointer;}
.option-input{display:none;}
.option-input:checked + .option-label{background:rgba(78,115,223,0.1);border-color:#4e73df;color:#4e73df;font-weight:600;}
#timer{font-weight:bold;color:#e74a3b;padding:8px 15px;border-radius:8px;background:rgba(231,74,59,0.1);}
.answered{background-color:#d4edda!important;border-color:#c3e6cb!important;}
/* ✅ Prevent right-click and text selection */
body {
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
</style>
</head>
<body oncontextmenu="return false;">
    <?php include "../include/nav.php"; ?>
    <div class="content" style="padding:20px">
<div class="container mt-4">
    <?php if(!$available): ?>
        <div class="alert alert-warning text-center"><?= $msg ?></div>
    <?php elseif(empty($questions)): ?>
        <div class="alert alert-danger text-center">No questions assigned for this exam.</div>
    <?php else: ?>
        <div class="alert alert-info d-flex justify-content-between">
            <div><i class="fas fa-clock me-2"></i>Time: <span id="timer"></span></div>
            <div>Q<?= $current_index+1 ?> of <?= count($questions) ?></div>
        </div>

        <div class="progress mb-3">
            <div class="progress-bar" role="progressbar" style="width: <?= (($current_index+1)/count($questions))*100 ?>%"></div>
        </div>

        <form method="post" id="examForm">
            <?php 
            $q = $questions[$current_index]; 
            $q_id = $q['id'];
            ?>
            <div class="card">
                <div class="card-header">Question <?= $current_index+1 ?></div>
                <div class="card-body">
                    <p class="fw-bold"><?= htmlspecialchars($q['question']) ?></p>
                    <?php if($q['type']=='multiple_choice'): ?>
                        <?php 
                        $options = $q['options'];
                        // ✅ Shuffle options for each question (store in session)
                        if(!isset($_SESSION['exam_data'][$exam_id]['shuffled_options'][$q_id])){
                            shuffle($options);
                            $_SESSION['exam_data'][$exam_id]['shuffled_options'][$q_id] = $options;
                        }
                        $options = $_SESSION['exam_data'][$exam_id]['shuffled_options'][$q_id];
                        ?>
                        <?php foreach($options as $i=>$opt): ?>
                            <input type="radio" id="opt<?=$q_id?>_<?=$i?>" class="option-input"
                                   name="answers[<?=$q_id?>]" value="<?= htmlspecialchars($opt) ?>"
                                   <?= (trim($current_answer) === trim($opt)) ? 'checked' : '' ?>>
                            <label for="opt<?=$q_id?>_<?=$i?>" class="option-label">
                                <strong><?=chr(65+$i)?>.</strong> <?=htmlspecialchars($opt)?>
                            </label>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <input type="text" class="form-control" name="answers[<?=$q_id?>]" 
                               value="<?= htmlspecialchars($current_answer) ?>" placeholder="Type your answer"
                               autocomplete="off" spellcheck="false">
                    <?php endif; ?>
                </div>
            </div>
            <div class="d-flex justify-content-between mt-3">
                <?php if($current_index>0): ?>
                    <button type="submit" name="save_and_prev" value="1" class="btn btn-secondary">Previous</button>
                <?php else: ?>
                    <div></div>
                <?php endif; ?>
                
                <?php if($current_index<count($questions)-1): ?>
                    <button type="submit" name="save_and_next" value="1" class="btn btn-warning">Next</button>
                <?php else: ?>
                    <button type="submit" name="submit_exam" class="btn btn-success" 
                            onclick="return confirm('Are you sure you want to submit the exam? This action cannot be undone.')">
                        Submit Exam
                    </button>
                <?php endif; ?>
                <input type="hidden" name="current_question" value="<?=$q_id?>">
                <input type="hidden" name="q_index" value="<?=$current_index?>">
            </div>
        </form>

        <!-- Question navigation -->
        <div class="d-flex flex-wrap gap-2 mt-4 justify-content-center">
            <?php for($i=0;$i<count($questions);$i++): 
                $q_id = $questions[$i]['id'];
                $is_answered = isset($_SESSION['exam_data'][$exam_id]['student_answers'][$q_id]) && !empty(trim($_SESSION['exam_data'][$exam_id]['student_answers'][$q_id]));
            ?>
                <a href="?exam_id=<?=$exam_id?>&q=<?=$i?>" 
                   class="rounded-circle d-flex align-items-center justify-content-center 
                          <?= $i==$current_index ? 'bg-primary text-white' : ($is_answered ? 'bg-success text-white' : 'bg-light') ?>" 
                   style="width:40px;height:40px;text-decoration:none;"
                   title="<?= $is_answered ? 'Answered' : 'Not answered' ?>">
                   <?=$i+1?>
                </a>
            <?php endfor; ?>
        </div>

        <script>
        let timeLeft = <?=$timeLeft?>;
        let timerDisplay = document.getElementById("timer");
        let examForm = document.getElementById("examForm");
        
        function updateTimer(){
            let hours = Math.floor(timeLeft / 3600);
            let minutes = Math.floor((timeLeft % 3600) / 60);
            let seconds = timeLeft % 60;
            
            timerDisplay.textContent = 
                (hours > 0 ? hours + "h " : "") + 
                (minutes > 0 ? minutes + "m " : "") + 
                seconds + "s";
                
            if(timeLeft <= 0){
                clearInterval(countdown);
                alert("Time is up! Your exam will be submitted automatically.");
                examForm.submit();
            }
            timeLeft--;
        }
        
        let countdown = setInterval(updateTimer, 1000); 
        updateTimer();

        // Auto-save when changing answers
        document.querySelectorAll('input[type="radio"], input[type="text"]').forEach(input => {
            input.addEventListener('change', function() {
                setTimeout(() => {
                    document.querySelector('button[name="save_and_next"]')?.click();
                }, 500);
            });
        });

        // ✅ Prevent F12, Ctrl+Shift+I, etc.
        document.addEventListener('keydown', function(e) {
            if (e.key === 'F12' || 
                (e.ctrlKey && e.shiftKey && e.key === 'I') || 
                (e.ctrlKey && e.shiftKey && e.key === 'C') ||
                (e.ctrlKey && e.key === 'u')) {
                e.preventDefault();
                return false;
            }
        });
        </script>
    <?php endif; ?>
</div>
</body>
</html>