<?php
session_start();
require_once "config.php";

if (!isset($_SESSION['student_id'])) {
    header("Location: student_login.php");
    exit;
}

$student_id = $_SESSION['student_id'];
$exam_id = intval($_GET['exam_id'] ?? 0);

// Get exam
$stmt = $dbh->prepare("SELECT * FROM exams WHERE id=? AND status='published'");
$stmt->execute([$exam_id]);
$exam = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$exam) {
    echo "<div class='text-center text-red-600 font-bold p-6'>Exam not found or not available.</div>";
    exit;
}

// Ensure student hasn’t already submitted
$stmt = $dbh->prepare("SELECT * FROM exam_attempts WHERE exam_id=? AND student_id=? AND status='submitted'");
$stmt->execute([$exam_id, $student_id]);
if ($stmt->fetch()) {
    echo "<div class='text-center text-red-600 font-bold p-6'>You already submitted this exam.</div>";
    exit;
}

// Load questions
$stmt = $dbh->prepare("SELECT q.* FROM exam_questions eq 
    JOIN questions q ON eq.question_id = q.id 
    WHERE eq.exam_id=? ORDER BY eq.q_order ASC");
$stmt->execute([$exam_id]);
$questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle final submission
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['final_submit'])) {
    $answers = $_POST['answers'] ?? [];
    $score = 0;
    $total = count($questions);

    foreach ($questions as $q) {
        $qid = $q['id'];
        $student_ans = trim(strtolower($answers[$qid] ?? ''));
        $correct = trim(strtolower($q['correct_answer']));

        $mark = 0;
        if ($q['type']==='objective' && $student_ans === $correct) {
            $mark = 1;
            $score++;
        }

        // Save each answer
        $stmt = $dbh->prepare("INSERT INTO student_answers (student_id, question_id, answer_text, marked_score, marked_by, marked_at) 
            VALUES (?, ?, ?, ?, ?, NOW())
            ON DUPLICATE KEY UPDATE answer_text=VALUES(answer_text), marked_score=VALUES(marked_score), marked_at=NOW()");
        $stmt->execute([$student_id, $qid, $student_ans, $mark, $exam['teacher_id']]);
    }

    // Save attempt
    $stmt = $dbh->prepare("INSERT INTO exam_attempts (exam_id, student_id, started_at, submitted_at, status, score, time_taken_seconds) 
        VALUES (?, ?, NOW(), NOW(), 'submitted', ?, ?)");
    $stmt->execute([$exam_id, $student_id, $score, intval($_POST['time_taken'])]);

  // Post-submission review page
echo "
<div class='min-h-screen bg-gray-100 flex items-center justify-center py-10'>
  <div class='max-w-5xl w-full bg-white shadow-xl rounded-2xl p-8'>

    <!-- Score Summary -->
    <div class='text-center mb-8'>
      <h2 class='text-4xl font-extrabold text-gray-800 mb-3'>Exam Completed 🎉</h2>
      <p class='text-lg text-gray-600 mb-5'>Here’s a breakdown of your performance:</p>
      <div class='inline-block px-6 py-3 rounded-full text-xl font-semibold shadow-md 
        ".($score >= ($total/2) 
          ? "bg-green-100 text-green-700" 
          : "bg-red-100 text-red-700")."'>
        You scored <span class='font-bold'>$score</span> / <span class='font-bold'>$total</span>
      </div>
    </div>

    <!-- Answer Review -->
    <div>
      <h3 class='text-2xl font-bold text-gray-700 mb-6'>Answer Review</h3>";

foreach ($questions as $i => $q) {
    $qid = $q['id'];
    $student_ans_raw = $answers[$qid] ?? '';
    $student_ans = htmlspecialchars($student_ans_raw ?: 'Not answered');
    $correct = htmlspecialchars($q['correct_answer']);
    $isCorrect = (strtolower(trim($student_ans_raw)) === strtolower(trim($q['correct_answer'])));

    echo "
      <div class='mb-6 p-6 rounded-xl border transition transform hover:scale-[1.01] 
        ".($isCorrect 
            ? "bg-green-50 border-green-300" 
            : "bg-red-50 border-red-300")."'>
        
        <p class='font-semibold text-gray-800 text-lg mb-3'>
          ".($i+1).". {$q['question_text']}
        </p>";

    if ($isCorrect) {
        echo "
        <p class='text-green-700 font-medium'>
          ✅ Your Answer: <span class='font-bold'>$student_ans</span>
        </p>";
    } else {
        echo "
        <p class='text-red-700 font-medium'>
          ❌ Your Answer: <span class='font-bold'>$student_ans</span>
        </p>
        <p class='text-green-700 font-medium'>
          ✅ Correct Answer: <span class='font-bold'>$correct</span>
        </p>";
    }

    echo "</div>";
}

echo "
    </div>
    

    <!-- Back to Dashboard -->
    <div class='text-center mt-10'>
      <a href='student_dashboard.php' 
         class='inline-block px-8 py-3 bg-blue-600 text-white rounded-xl text-lg font-semibold shadow-md hover:bg-blue-700 transition'>
        Back to Dashboard
      </a>
    </div>

  </div>
</div>";
?>
<script>
  // Redirect to another page after 5 seconds
  setTimeout(function() {
    window.location.href = "student_dashboard.php"; // change to your target page
  }, 2000);
</script>
<?php
exit;

}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Take Exam</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
#timer {
    font-size: 2.5rem;
    font-weight: bold;
    position: fixed;
    top: 15px; right: 20px;
    padding: 12px 24px;
    border-radius: 14px;
    background: #1e293b;
    color: white;
    z-index: 1000;
    transition: all .5s ease;
}
#timer.warning { background:#f59e0b; animation:pulse 1s infinite; }
#timer.danger { background:#dc2626; animation:shake .6s infinite; }
@keyframes pulse {0%,100%{transform:scale(1);}50%{transform:scale(1.2);} }
@keyframes shake {0%,100%{transform:translateX(0);}25%{transform:translateX(-5px);}50%{transform:translateX(5px);}75%{transform:translateX(-5px);} }
</style>
</head>
<body class="bg-gray-100">

<div class="max-w-5xl mx-auto py-8">
    <h1 class="text-3xl font-bold mb-6 text-center"><?=htmlspecialchars($exam['title'])?></h1>

    <!-- Toggle Mode -->
    <div class="mb-6 text-center">
        <button id="toggleMode" class="bg-blue-600 text-white px-4 py-2 rounded">Switch to One-by-One Mode</button>
    </div>

    <!-- Exam Form -->
    <form method="POST" id="examForm">
        <input type="hidden" name="final_submit" value="1">
        <input type="hidden" name="time_taken" id="time_taken" value="0">

        <!-- All Questions Mode -->
        <div id="allMode">
            <?php foreach ($questions as $i=>$q): ?>
            <div class="mb-6 p-4 bg-white shadow rounded">
                <p class="font-semibold"><?=($i+1)?>. <?=$q['question_text']?></p>
                <?php if ($q['type']==='objective'):
                    $opts = json_decode($q['options'], true) ?: [];
                    foreach ($opts as $opt): ?>
                        <label class="inline">
                            <input type="radio" name="answers[<?=$q['id']?>]" value="<?=htmlspecialchars($opt)?>" class="mr-2">
                            <?=htmlspecialchars($opt)?>
                        </label>
                <?php endforeach; endif; ?>
                <?php if ($q['type']==='fill' || $q['type']==='theory'): ?>
                    <textarea name="answers[<?=$q['id']?>]" class="w-full border p-2 mt-2 rounded"></textarea>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- One-by-One Mode -->
        <div id="oneMode" class="hidden">
            <?php foreach ($questions as $i=>$q): ?>
            <div class="one-question hidden" data-index="<?=$i?>">
                <div class="p-4 bg-white shadow rounded mb-6">
                    <p class="font-semibold"><?=($i+1)?>. <?=$q['question_text']?></p>
                    <?php if ($q['type']==='objective'):
                        $opts = json_decode($q['options'], true) ?: [];
                        foreach ($opts as $opt): ?>
                            <label class="inline">
                                <input type="radio" name="answers[<?=$q['id']?>]" value="<?=htmlspecialchars($opt)?>" class="mr-2">
                                <?=htmlspecialchars($opt)?>
                            </label>
                    <?php endforeach; endif; ?>
                    <?php if ($q['type']==='fill' || $q['type']==='theory'): ?>
                        <textarea name="answers[<?=$q['id']?>]" class="w-full border p-2 mt-2 rounded"></textarea>
                    <?php endif; ?>
                </div>
                <div class="flex justify-between">
                    <button type="button" class="prevBtn bg-gray-600 text-white px-3 py-1 rounded">Prev</button>
                    <button type="button" class="nextBtn bg-blue-600 text-white px-3 py-1 rounded">Next</button>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <div class="mt-6 text-center">
            <button type="submit" class="bg-green-600 text-white px-5 py-2 rounded">Submit Exam</button>
        </div>
    </form>
</div>

<div id="timer"></div>

<script>
let duration = <?=$exam['duration_minutes']?>*60;
let elapsed = 0;
let timerEl = document.getElementById('timer');
let form = document.getElementById('examForm');

function updateTimer() {
    let remaining = duration - elapsed;
    let m = Math.floor(remaining/60), s = remaining%60;
    timerEl.textContent = `${m}:${s<10?'0'+s:s}`;
    if (remaining<=60 && remaining>40) timerEl.classList.add("warning");
    else if (remaining<=40) { timerEl.classList.remove("warning"); timerEl.classList.add("danger"); }
    if (remaining<=0) { clearInterval(timer); document.getElementById('time_taken').value=elapsed; form.submit(); }
    elapsed++;
}
let timer=setInterval(updateTimer,1000);

// Mode toggle
let toggle=document.getElementById('toggleMode');
let all=document.getElementById('allMode');
let one=document.getElementById('oneMode');
let oneQuestions=document.querySelectorAll('.one-question');
let current=0;
toggle.onclick=()=>{
    if(all.classList.contains('hidden')){
        all.classList.remove('hidden'); one.classList.add('hidden'); toggle.textContent="Switch to One-by-One Mode";
    }else{
        all.classList.add('hidden'); one.classList.remove('hidden'); toggle.textContent="Switch to All-at-Once Mode";
        showQuestion(0);
    }
};
function showQuestion(i){
    oneQuestions.forEach((q,idx)=>q.classList.toggle('hidden', idx!==i));
    current=i;
}
document.querySelectorAll('.nextBtn').forEach(btn=>btn.onclick=()=>{if(current<oneQuestions.length-1)showQuestion(current+1);});
document.querySelectorAll('.prevBtn').forEach(btn=>btn.onclick=()=>{if(current>0)showQuestion(current-1);});

// Auto-save every 30s
setInterval(()=>{
    let formData=new FormData(form);
    fetch("save_progress.php?exam_id=<?=$exam_id?>",{method:"POST",body:formData});
},30000);
</script>
</body>
</html>
