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

require "../user/db.php";

// Check if student is logged in
if (!isset($_SESSION['user_id'])) {
    die("You must be logged in to access quizzes.");
}
$student_id = $_SESSION['user_id'];

// Fetch all available quizzes
$quizzes = [];
$quizQuery = $conn->query("SELECT * FROM quizzes ORDER BY created_at DESC");
while ($row = $quizQuery->fetch_assoc()) {
    $quizzes[] = $row;
}

// Handle quiz submission
if (isset($_POST['submit_quiz'])) {
    $quiz_id = $_POST['quiz_id'];
    $answers = $_POST['answers']; // array: question_id => answer

    foreach ($answers as $question_id => $answer) {
        $stmt = $conn->prepare("
            INSERT INTO quiz_submissions (quiz_id, student_id, question_id, answer)
            VALUES (?, ?, ?, ?)
        ");
        $stmt->bind_param("iiis", $quiz_id, $student_id, $question_id, $answer);
        $stmt->execute();
    }

    $success = "Your answers have been submitted! Waiting for grading.";
}

// Helper: fetch questions and options for a quiz
function getQuizQuestions($conn, $quiz_id) {
    $questions = [];
    $qQuery = $conn->prepare("SELECT * FROM quiz_questions WHERE quiz_id=?");
    $qQuery->bind_param("i", $quiz_id);
    $qQuery->execute();
    $res = $qQuery->get_result();
    while ($row = $res->fetch_assoc()) {
        // fetch options if MCQ
        $options = [];
        if ($row['question_type'] === 'mcq') {
            $optQuery = $conn->prepare("SELECT * FROM quiz_options WHERE question_id=?");
            $optQuery->bind_param("i", $row['id']);
            $optQuery->execute();
            $optRes = $optQuery->get_result();
            while ($opt = $optRes->fetch_assoc()) {
                $options[] = $opt;
            }
        }
        $row['options'] = $options;
        $questions[] = $row;
    }
    return $questions;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Quiz Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.card { background: #f9f9f9; padding: 20px; border-radius: 8px; margin-bottom: 20px; }
h2 { margin-top: 0; }
label { font-weight: bold; display: block; margin: 8px 0 4px; }
input[type="text"], textarea { width: 100%; padding: 8px; margin-bottom: 12px; }
input[type="radio"] { margin-right: 6px; }
.btn { background: #2563eb; color: #fff; padding: 10px 16px; border: none; border-radius: 6px; cursor: pointer; }
.success { color: green; }
</style>
</head>
<body>

<h1>Available Quizzes</h1>

<?php if (isset($success)) echo "<p class='success'>$success</p>"; ?>

<?php if (empty($quizzes)): ?>
    <p>No quizzes available at the moment.</p>
<?php else: ?>
    <?php foreach ($quizzes as $quiz): ?>
        <div class="card">
            <h2><?= htmlspecialchars($quiz['title']) ?></h2>
            <p><?= htmlspecialchars($quiz['instructions']) ?></p>
            <form method="POST">
                <?php 
                $questions = getQuizQuestions($conn, $quiz['id']);
                foreach ($questions as $q): 
                ?>
                    <div>
                        <label><?= htmlspecialchars($q['question_text']) ?></label>
                        <?php if ($q['question_type'] === 'mcq'): ?>
                            <?php foreach ($q['options'] as $opt): ?>
                                <div>
                                    <input type="radio" name="answers[<?= $q['id'] ?>]" value="<?= htmlspecialchars($opt['option_text']) ?>" required>
                                    <?= htmlspecialchars($opt['option_text']) ?>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <textarea name="answers[<?= $q['id'] ?>]" rows="3" required></textarea>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
                <input type="hidden" name="quiz_id" value="<?= $quiz['id'] ?>">
                <button class="btn" name="submit_quiz">Submit Quiz</button>
            </form>
        </div>
    <?php endforeach; ?>
<?php endif; ?>

</body>
</html>
