<?php
session_start();
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include "../include/config.php";

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

// Load student info and filters
$email   = $_SESSION['email'] ?? '';
$program = $_SESSION['program'] ?? '';
$period  = $_SESSION['period'] ?? '';
$intake  = $_SESSION['intake'] ?? '';
$course  = $_SESSION['course'] ?? '';
$year    = $_SESSION['year'] ?? '';

$success = "";
$error = "";

// Handle exam submission
if (isset($_POST['submit_exam'])) {
    foreach ($_POST['answers'] as $question_id => $answer) {
        $qid = intval($question_id);
        $ans = $conn->real_escape_string($answer);
        $student_email = $conn->real_escape_string($email);

        // Insert or update student's answer
        $sql = "INSERT INTO exam_answers (student_email, question_id, answer, submitted_at)
                VALUES ('$student_email', '$qid', '$ans', NOW())
                ON DUPLICATE KEY UPDATE answer='$ans', submitted_at=NOW()";

        if (!$conn->query($sql)) {
            $error = "Error saving answers: " . $conn->error;
        }
    }

    if (!$error) {
        $_SESSION['success'] = "Exam submitted successfully!";
        header("location: online_exam.php");
        exit();
    } else {
        $_SESSION['error'] = $error;
        header("location: online_exam.php");
        exit();
    }
}

// Fetch exam questions based on program/course/intake/year/term
$sql = "SELECT * FROM exam_questions 
        WHERE program='$program' 
          AND course='$course' 
          AND intake='$intake' 
          AND year='$year' 
          AND term='$period'
           AND email='$email'
        ORDER BY id ASC";
$result = $conn->query($sql);

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Online Exam</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
<?php include "../include/nav.php"; ?>
<div class="content">
<div class="container mt-5">
<h3 class="mb-4 text-primary"><i class="fa fa-pencil-alt"></i> Online Exam</h3>

<!-- Success / Error Messages -->
<?php if(isset($_SESSION['success'])): ?>
<div class="alert alert-success text-center">
<i class="fa fa-check-circle"></i> <?= $_SESSION['success']; ?>
</div>
<?php unset($_SESSION['success']); endif; ?>

<?php if(isset($_SESSION['error'])): ?>
<div class="alert alert-danger text-center">
<i class="fa fa-exclamation-triangle"></i> <?= $_SESSION['error']; ?>
</div>
<?php unset($_SESSION['error']); endif; ?>

<?php if ($result->num_rows > 0) { ?>
<form method="post">
<div class="list-group">
<?php $sn = 1; while($row = $result->fetch_assoc()) { 
    // Fetch previously submitted answer if any
    $qid = $row['id'];
    $ans_res = $conn->query("SELECT answer FROM exam_answers WHERE student_email='$email' AND question_id='$qid' LIMIT 1");
    $prev_answer = $ans_res && $ans_res->num_rows > 0 ? $ans_res->fetch_assoc()['answer'] : '';
?>
<div class="list-group-item mb-3">
    <p><strong>Q<?= $sn++; ?>:</strong> <?= htmlspecialchars($row['question']); ?></p>

    <?php if ($row['type'] == 'multiple_choice') {
        $options = json_decode($row['options'], true); // options stored as JSON
        foreach ($options as $opt) { ?>
        <div class="form-check">
            <input class="form-check-input" type="radio" name="answers[<?= $qid ?>]" value="<?= htmlspecialchars($opt) ?>" <?= $prev_answer==$opt?"checked":"" ?> required>
            <label class="form-check-label"><?= htmlspecialchars($opt) ?></label>
        </div>
    <?php } } else { ?>
        <textarea class="form-control" name="answers[<?= $qid ?>]" rows="3" required><?= htmlspecialchars($prev_answer) ?></textarea>
    <?php } ?>
</div>
<?php } ?>
</div>

<div class="mt-3 text-center">
    <button type="submit" name="submit_exam" class="btn btn-success"><i class="fa fa-paper-plane"></i> Submit Exam</button>
</div>
</form>
<?php } else { ?>
<p class="text-center text-muted">No exam available for your course/program/intake/year/term.</p>
<?php } ?>

</div>
</div>
</body>
</html>
