<?php
require_once __DIR__ . '/config.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['institution_id'])) {
    die("Unauthorized access. Institution ID missing.");
}

$institution_id = $_SESSION['institution_id'];
$errors = [];
$success = "";
$class_section = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $class_section = trim($_POST['class_section']);

    if (empty($class_section)) {
        $errors[] = "Class / Section is required.";
    } else {

        $generated_quiz_name = "LS-Quiz-" . time();  // auto generate name internally
        $fixed_questions = 20;
        $subject_tag = "Learning-Style"; // hidden tag

        $stmt = $conn->prepare("
            INSERT INTO quizzes (institution_id, quiz_name, class_section, subject, total_questions)
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt->bind_param("isssi", $institution_id, $generated_quiz_name, $class_section, $subject_tag, $fixed_questions);

        if ($stmt->execute()) {
            $success = "Learning-Style quiz created successfully!";
            $class_section = "";
        } else {
            $errors[] = "Database error: " . $stmt->error;
        }

        $stmt->close();
    }
}

$q = $conn->prepare("SELECT id, quiz_name, class_section, subject, total_questions, created_at 
                     FROM quizzes WHERE institution_id = ? ORDER BY created_at DESC");
$q->bind_param("i", $institution_id);
$q->execute();
$result = $q->get_result();
$quizzes = $result->fetch_all(MYSQLI_ASSOC);
$q->close();

?>
<!DOCTYPE html>
<html>
<head>
    <title>Create Learning-Style Quiz</title>
</head>

<body>

<h2>Create Manual Learning-Style Quiz</h2>

<?php if (!empty($success)): ?>
    <p style="color:green;"><?= $success ?></p>
<?php endif; ?>

<?php if (!empty($errors)): ?>
    <?php foreach ($errors as $e): ?>
        <p style="color:red;"><?= $e ?></p>
    <?php endforeach; ?>
<?php endif; ?>

<form method="POST">

    <label>Class / Section *</label><br>
    <input type="text" name="class_section" value="<?= htmlspecialchars($class_section) ?>" required>
    <br><br>

    <label>Total Questions</label><br>
    <input type="number" value="20" disabled>
    <br><br>

    <button type="submit">Create Quiz</button>
</form>

<hr>

<h3>Existing Learning-Style Quizzes</h3>
<table border="1" cellpadding="5">
    <tr>
        <th>Class</th>
        <th>Questions</th>
        <th>Created</th>
        <th>Action</th>
    </tr>

    <?php foreach ($quizzes as $q): ?>
    <tr>
        <td><?= htmlspecialchars($q['class_section']) ?></td>
        <td><?= $q['total_questions'] ?></td>
        <td><?= $q['created_at'] ?></td>
        <td>
            <a href="manual_enter_answers.php?quiz_id=<?= $q['id'] ?>">Enter Answers</a>
        </td>
    </tr>
    <?php endforeach; ?>
</table>

</body>
</html>
