<?php
/**
 * student/take_exam.php
 * Computer Based Test (CBT) Interface
 */
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../config/database.php';

// 1. SECURITY & PARAMETER CHECK
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'student') {
    header("Location: ../auth/login.php");
    exit();
}

if (!isset($_GET['exam_id']) || empty($_GET['exam_id'])) {
    die("<div style='text-align:center; padding:50px; font-family:sans-serif;'>
            <h2>Invalid Request</h2>
            <p>No Examination ID was provided.</p>
            <a href='dashboard.php'>Return to Dashboard</a>
         </div>");
}

$exam_id = (int)$_GET['exam_id'];
$student_id = (int)$_SESSION['user_id'];

// 2. FETCH EXAM DETAILS
$exam_stmt = $pdo->prepare("SELECT * FROM exams WHERE id = ? AND status = 1 AND is_deleted = 0");
$exam_stmt->execute([$exam_id]);
$exam = $exam_stmt->fetch(PDO::FETCH_ASSOC);

if (!$exam) {
    die("<div style='text-align:center; padding:50px; font-family:sans-serif;'>
            <h2>Exam Not Found</h2>
            <p>This exam is either not yet active or has been removed.</p>
            <a href='dashboard.php'>Return to Dashboard</a>
         </div>");
}

// 3. FETCH QUESTIONS WITH RANDOM ORDER
// Added ORDER BY RAND() to ensure every student sees questions in a different sequence
$q_stmt = $pdo->prepare("SELECT id, question_text, option_a, option_b, option_c, option_d FROM questions WHERE exam_id = ? ORDER BY RAND()");
$q_stmt->execute([$exam_id]);
$questions = $q_stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($questions)) {
    die("This exam has no questions yet. Please contact your instructor.");
}

$duration_seconds = (int)$exam['duration'] * 60;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CBT | <?= htmlspecialchars($exam['exam_title']) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root { --primary: #0f172a; --accent: #2563eb; --bg: #f8fafc; --success: #10b981; --danger: #ef4444; --border: #e2e8f0; }
        * { box-sizing: border-box; outline: none; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background: var(--bg); color: var(--primary); margin: 0; overflow: hidden; }

        .exam-container { display: grid; grid-template-columns: 1fr 340px; height: 100vh; }

        .exam-content { padding: 0; overflow-y: auto; background: var(--bg); display: flex; flex-direction: column; }
        
        .top-bar { 
            position: sticky; top: 0; z-index: 10; background: rgba(255, 255, 255, 0.9); 
            backdrop-filter: blur(10px); border-bottom: 1px solid var(--border); 
            padding: 15px 40px; display: flex; justify-content: space-between; align-items: center; 
        }
        .exam-meta h1 { font-size: 18px; margin: 0; font-weight: 800; color: #1e293b; }
        .timer-badge { background: var(--primary); color: white; padding: 8px 20px; border-radius: 10px; font-weight: 800; font-size: 20px; }

        .question-scroll-area { padding: 40px; display: flex; flex-direction: column; align-items: center; flex-grow: 1; }
        .question-card { 
            background: white; width: 100%; max-width: 1000px; padding: 50px; 
            border-radius: 30px; box-shadow: 0 10px 25px -5px rgba(0,0,0,0.03); border: 1px solid var(--border); 
        }
        .q-label { color: var(--accent); font-weight: 800; font-size: 13px; text-transform: uppercase; margin-bottom: 10px; display: block; }
        .q-text { font-size: 24px; font-weight: 700; line-height: 1.4; margin-bottom: 40px; color: #0f172a; }

        .options-grid { display: grid; grid-template-columns: 1fr; gap: 15px; }
        .option-card { 
            display: flex; align-items: center; padding: 22px 28px; border: 2px solid #f1f5f9; 
            border-radius: 18px; cursor: pointer; transition: 0.2s all ease; position: relative;
        }
        .option-card:hover { border-color: #cbd5e1; background: #f8fafc; }
        .option-card strong { font-size: 18px; margin-right: 15px; color: #94a3b8; }
        
        input[type="radio"] { display: none; }
        input[type="radio"]:checked + .option-card { border-color: var(--accent); background: #eff6ff; }
        input[type="radio"]:checked + .option-card strong { color: var(--accent); }

        .bottom-section { width: 100%; max-width: 1000px; margin-top: 40px; padding-bottom: 60px; }
        .nav-controls { display: flex; justify-content: space-between; margin-bottom: 30px; }
        
        .btn-nav { padding: 14px 30px; border-radius: 14px; border: none; font-weight: 800; cursor: pointer; display: flex; align-items: center; gap: 10px; transition: 0.2s; }
        .btn-prev { background: white; color: #64748b; border: 1px solid var(--border); }
        .btn-next { background: var(--accent); color: white; }

        .navigator-box { background: white; padding: 30px; border-radius: 24px; border: 1px solid var(--border); }
        .q-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(50px, 1fr)); gap: 12px; }
        .q-num-btn { 
            aspect-ratio: 1; border-radius: 10px; border: 1px solid var(--border); 
            background: white; cursor: pointer; font-weight: 700; transition: 0.3s; 
        }
        .q-num-btn.active { background: var(--accent); color: white; border-color: var(--accent); }
        .q-num-btn.answered { background: #dcfce7; color: #166534; border-color: #bbf7d0; }

        .tool-sidebar { background: white; border-left: 1px solid var(--border); padding: 20px; overflow-y: auto; display: flex; flex-direction: column; }
        
        .calc-screen { background: #1e293b; color: #10b981; padding: 15px; border-radius: 12px; text-align: right; font-family: monospace; font-size: 18px; margin-bottom: 12px; min-height: 50px; word-wrap: break-word; }
        .calc-keys { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin-bottom: 20px; }
        .calc-keys button { padding: 10px 2px; border: none; border-radius: 8px; background: #f1f5f9; font-weight: 700; font-size: 12px; cursor: pointer; transition: 0.2s; }
        .calc-keys button:hover { background: #e2e8f0; }
        .btn-op { color: var(--accent); background: #eff6ff !important; }
        .btn-sci { background: #f8fafc !important; color: #64748b; font-style: italic; }
        .btn-danger { color: var(--danger); background: #fff1f2 !important; }

        #scratchpad { width: 100%; height: 120px; border: 1px solid var(--border); border-radius: 14px; padding: 12px; font-family: inherit; resize: none; background: #fffdf2; margin-bottom: 20px; font-size: 13px; }

        .btn-submit-exam { width: 100%; background: var(--danger); color: white; padding: 18px; border: none; border-radius: 16px; font-weight: 800; font-size: 15px; cursor: pointer; transition: 0.3s; display: flex; align-items: center; justify-content: center; gap: 10px; }
        .btn-submit-exam:hover { background: #dc2626; transform: translateY(-2px); }

        @media (max-width: 1000px) { .exam-container { grid-template-columns: 1fr; } .tool-sidebar { display: none; } }
    </style>
</head>
<body>

<div class="exam-container">
    <main class="exam-content">
        <div class="top-bar">
            <div class="exam-meta"><h1><?= htmlspecialchars($exam['exam_title']) ?></h1></div>
            <div class="timer-badge" id="timerDisplay">00:00:00</div>
        </div>

        <div class="question-scroll-area">
            <form id="examForm" action="process_result.php" method="POST" style="width:100%; display:contents;">
                <input type="hidden" name="exam_id" value="<?= $exam_id ?>">

                <?php foreach($questions as $index => $q): ?>
                    <div class="question-wrapper" id="q-div-<?= $index + 1 ?>" style="<?= $index === 0 ? 'width:100%; max-width:1000px;' : 'display:none; width:100%; max-width:1000px;' ?>">
                        <div class="question-card">
                            <span class="q-label">Question <?= $index + 1 ?> of <?= count($questions) ?></span>
                            <div class="q-text"><?= htmlspecialchars($q['question_text']) ?></div>
                            <div class="options-grid">
                                <?php foreach(['a' => $q['option_a'], 'b' => $q['option_b'], 'c' => $q['option_c'], 'd' => $q['option_d']] as $key => $val): ?>
                                    <label>
                                        <input type="radio" name="ans[<?= $q['id'] ?>]" value="<?= strtoupper($key) ?>" onchange="markNav(<?= $index + 1 ?>)">
                                        <div class="option-card"><strong><?= strtoupper($key) ?></strong> <span><?= htmlspecialchars($val) ?></span></div>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>

                <div class="bottom-section">
                    <div class="nav-controls">
                        <button type="button" class="btn-nav btn-prev" id="prevBtn" onclick="move(-1)" style="visibility:hidden;"><i class="fa fa-arrow-left"></i> Previous</button>
                        <button type="button" class="btn-nav btn-next" id="nextBtn" onclick="move(1)">Next <i class="fa fa-arrow-right"></i></button>
                    </div>

                    <div class="navigator-box">
                        <span class="q-label" style="color: #64748b; margin-bottom:15px;">Question Navigator</span>
                        <div class="q-grid">
                            <?php foreach($questions as $index => $q): ?>
                                <button type="button" class="q-num-btn" id="nav-<?= $index + 1 ?>" onclick="jumpTo(<?= $index + 1 ?>)"><?= $index + 1 ?></button>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </main>

    <aside class="tool-sidebar">
        <span class="q-label" style="color: #94a3b8;">Scientific Calculator</span>
        <div class="calc-screen" id="calcScreen">0</div>
        <div class="calc-keys">
            <button type="button" class="btn-sci" onclick="cMath('Math.sin(')">sin</button>
            <button type="button" class="btn-sci" onclick="cMath('Math.cos(')">cos</button>
            <button type="button" class="btn-sci" onclick="cMath('Math.tan(')">tan</button>
            <button type="button" class="btn-sci" onclick="cMath('Math.sqrt(')">√</button>
            
            <button type="button" class="btn-sci" onclick="cMath('Math.log10(')">log</button>
            <button type="button" class="btn-sci" onclick="cIn('**')">xʸ</button>
            <button type="button" class="btn-sci" onclick="cIn('(')">(</button>
            <button type="button" class="btn-sci" onclick="cIn(')')">)</button>

            <button type="button" class="btn-danger" style="grid-column: span 2;" onclick="cClear()">AC (Clear)</button>
            <button type="button" class="btn-danger" style="grid-column: span 2;" onclick="cDel()"><i class="fa fa-backspace"></i> Back</button>

            <button type="button" onclick="cIn('7')">7</button><button type="button" onclick="cIn('8')">8</button><button type="button" onclick="cIn('9')">9</button>
            <button type="button" class="btn-op" onclick="cIn('/')">÷</button>

            <button type="button" onclick="cIn('4')">4</button><button type="button" onclick="cIn('5')">5</button><button type="button" onclick="cIn('6')">6</button>
            <button type="button" class="btn-op" onclick="cIn('*')">×</button>

            <button type="button" onclick="cIn('1')">1</button><button type="button" onclick="cIn('2')">2</button><button type="button" onclick="cIn('3')">3</button>
            <button type="button" class="btn-op" onclick="cIn('-')">-</button>

            <button type="button" onclick="cIn('0')">0</button>
            <button type="button" onclick="cIn('.')">.</button>
            <button type="button" class="btn-op" onclick="cIn('+')">+</button>
            <button type="button" class="btn-op" onclick="cSolve()" style="background:var(--accent) !important; color:white;">=</button>
        </div>

        <span class="q-label" style="color: #94a3b8;">Scratchpad</span>
        <textarea id="scratchpad" placeholder="Rough work..."></textarea>

        <button type="button" class="btn-submit-exam" onclick="submitExam()">Submit Exam <i class="fa fa-flag-checkered"></i></button>
    </aside>
</div>

<script>
    let current = 1;
    const total = <?= count($questions) ?>;
    function jumpTo(n) {
        document.getElementById('q-div-' + current).style.display = 'none';
        document.getElementById('nav-' + current).classList.remove('active');
        current = n;
        document.getElementById('q-div-' + current).style.display = 'block';
        document.getElementById('nav-' + current).classList.add('active');
        document.getElementById('prevBtn').style.visibility = (current === 1) ? 'hidden' : 'visible';
        document.getElementById('nextBtn').innerHTML = (current === total) ? 'Review <i class="fa fa-eye"></i>' : 'Next <i class="fa fa-arrow-right"></i>';
    }
    function move(step) { let n = current + step; if(n >= 1 && n <= total) jumpTo(n); }
    function markNav(n) { document.getElementById('nav-' + n).classList.add('answered'); }
    
    let expression = "";
    function cIn(v) { expression += v; updateScreen(); }
    function cMath(m) { expression += m; updateScreen(); }
    function cClear() { expression = ""; updateScreen("0"); }
    function cDel() { 
        if (expression.length > 0) {
            expression = expression.toString().slice(0, -1);
            updateScreen();
        }
    }
    function updateScreen(override = null) { 
        document.getElementById('calcScreen').innerText = override || (expression === "" ? "0" : expression); 
    }
    function cSolve() { 
        try { 
            let res = eval(expression); 
            document.getElementById('calcScreen').innerText = Number.isInteger(res) ? res : res.toFixed(4); 
            expression = res.toString(); 
        } catch(e) { document.getElementById('calcScreen').innerText = "Syntax Error"; expression = ""; } 
    }

    let time = <?= $duration_seconds ?>;
    const countdown = setInterval(() => {
        let h = Math.floor(time / 3600), m = Math.floor((time % 3600) / 60), s = time % 60;
        document.getElementById('timerDisplay').innerText = `${h.toString().padStart(2,'0')}:${m.toString().padStart(2,'0')}:${s.toString().padStart(2,'0')}`;
        if (time <= 0) { clearInterval(countdown); document.getElementById('examForm').submit(); }
        time--;
    }, 1000);

    function submitExam() { if(confirm("Submit your examination now?")) document.getElementById('examForm').submit(); }
    jumpTo(1);
</script>
</body>
</html>