<?php
// Handle deletion
if (isset($_POST['delete_exam_id'])) {
    $exam_id = intval($_POST['delete_exam_id']);

    // Delete related data first
    $connection->query("DELETE FROM cbt_student_answers WHERE exam_id = $exam_id");
    $connection->query("DELETE FROM cbt_exam_results WHERE exam_id = $exam_id");
    $connection->query("DELETE FROM cbt_exam_questions WHERE exam_id = $exam_id");

    // Delete exam itself
    if ($connection->query("DELETE FROM cbt_exams WHERE id = $exam_id")) {
        $_SESSION['msg'] = "Exam deleted successfully.";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Failed to delete exam.";
        $_SESSION['type'] = "error";
    }
    echo "<script>location.href='cbt_list_exam.php';</script>";
    exit;
}

// Handle update
if (isset($_POST['update_exam'])) {
    $id = intval($_POST['exam_id']);
    $title = $_POST['title'];
    $duration = $_POST['duration'];
    $total_marks = $_POST['total_marks'];
    $exam_date = $_POST['exam_date'];
    $start_time = $_POST['start_time'];
    $end_time = $_POST['end_time'];

    $stmt = $connection->prepare("UPDATE cbt_exams SET title=?, duration=?, total_marks=?, exam_date=?, start_time=?, end_time=? WHERE id=?");
    $stmt->bind_param("siisssi", $title, $duration, $total_marks, $exam_date, $start_time, $end_time, $id);
    if ($stmt->execute()) {
        $_SESSION['msg'] = "Exam updated successfully.";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Update failed.";
        $_SESSION['type'] = "error";
    }
    echo "<script>location.href='cbt_list_exam.php';</script>";
    exit;
}
?>

<div class="page-title">
    <div>
        <h1><i class="icon-notebook"></i> CBT Exams</h1>
        <p>All Created Exams</p>
    </div>
</div>

<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-hover">
                <thead class="table-dark">
                    <tr>
                        <th>#</th>
                        <th>Title</th>
                        <th>Class</th>
                        <th>Subject</th>
                        <th>Date</th>
                        <th>Status</th>
                        <th>Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $sql = "
                        SELECT e.*, c.classes AS class_name, s.subjects AS subject_name
                        FROM cbt_exams e
                        JOIN classes c ON e.class_id = c.id
                        JOIN school_subjects s ON e.subject_id = s.id
                        ORDER BY e.exam_date DESC, e.start_time ASC
                    ";
                    $result = $connection->query($sql);
                    $sn = 1;
                    if ($result->num_rows > 0):
                        while ($exam = $result->fetch_assoc()):
                    ?>
                        <tr>
                            <td><?= $sn++; ?></td>
                            <td><?= $exam['title']; ?></td>
                            <td><?= $exam['class_name']; ?></td>
                            <td><?= $exam['subject_name']; ?></td>
                            <td><?= $exam['exam_date']; ?></td>
                            <td><span class="badge bg-<?= $exam['status'] == 'active' ? 'success' : ($exam['status'] == 'completed' ? 'secondary' : 'warning'); ?>">
                                <?= ucfirst($exam['status']); ?></span>
                            </td>
                            <td><?= date("d M Y", strtotime($exam['created_at'])); ?></td>
                            <td>
                                <!-- View -->
                                <button class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#viewExam<?= $exam['id']; ?>">View</button>

                                <!-- Edit -->
                                <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#editExam<?= $exam['id']; ?>">Edit</button>

                                <!-- Delete -->
                                <form method="POST" style="display:inline;">
                                    <input type="hidden" name="delete_exam_id" value="<?= $exam['id']; ?>">
                                    <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Delete this exam?')">Delete</button>
                                </form>

                                <!-- Edit Modal -->
                                <div class="modal fade" id="editExam<?= $exam['id']; ?>" tabindex="-1" aria-hidden="true">
                                    <div class="modal-dialog modal-lg">
                                        <form method="POST">
                                            <input type="hidden" name="exam_id" value="<?= $exam['id']; ?>">
                                            <input type="hidden" name="update_exam" value="1">
                                            <div class="modal-content">
                                                <div class="modal-header bg-warning">
                                                    <h5 class="modal-title">Edit Exam</h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                </div>
                                                <div class="modal-body row g-3">
                                                    <div class="col-md-6">
                                                        <label>Title</label>
                                                        <input type="text" name="title" class="form-control" value="<?= htmlspecialchars($exam['title']); ?>" required>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label>Duration</label>
                                                        <input type="number" name="duration" class="form-control" value="<?= $exam['duration']; ?>" required>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label>Total Marks</label>
                                                        <input type="number" name="total_marks" class="form-control" value="<?= $exam['total_marks']; ?>" required>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label>Date</label>
                                                        <input type="date" name="exam_date" class="form-control" value="<?= $exam['exam_date']; ?>" required>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label>Start Time</label>
                                                        <input type="time" name="start_time" class="form-control" value="<?= $exam['start_time']; ?>" required>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label>End Time</label>
                                                        <input type="time" name="end_time" class="form-control" value="<?= $exam['end_time']; ?>" required>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="submit" class="btn btn-success">Update</button>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>

                                <!-- View Modal -->
                                <div class="modal fade" id="viewExam<?= $exam['id']; ?>" tabindex="-1" aria-hidden="true">
                                    <div class="modal-dialog modal-lg">
                                        <div class="modal-content">
                                            <div class="modal-header bg-info text-white">
                                                <h5 class="modal-title">View Exam</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                            </div>
                                            <div class="modal-body">
                                                <p><strong>Title:</strong> <?= $exam['title']; ?></p>
                                                <p><strong>Class:</strong> <?= $exam['class_name']; ?></p>
                                                <p><strong>Subject:</strong> <?= $exam['subject_name']; ?></p>
                                                <p><strong>Date:</strong> <?= $exam['exam_date']; ?></p>
                                                <p><strong>Time:</strong> <?= $exam['start_time']; ?> - <?= $exam['end_time']; ?></p>
                                                <p><strong>Duration:</strong> <?= $exam['duration']; ?> mins</p>
                                                <p><strong>Total Marks:</strong> <?= $exam['total_marks']; ?></p>
                                                <p><strong>Status:</strong> <?= ucfirst($exam['status']); ?></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    <?php endwhile; else: ?>
                        <tr><td colspan="8" class="text-center">No exams found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

