<?php
$pageTitle = "Admin - Manage Exams";
include '../../includes/conn.php';

// Include header
include '../includes/header.php';

requireRole('admin'); // only admins can access

// Fetch filters
$selected_teacher = $_GET['teacher_id'] ?? null;
$selected_class = $_GET['class_id'] ?? null;
$selected_session = $_GET['session_id'] ?? null;
$selected_term = $_GET['term_id'] ?? null;


// Fetch filter options
$teachers = $pdo->query("SELECT id, first_name , last_name FROM users WHERE role='teacher'")->fetchAll(PDO::FETCH_ASSOC);
$classes = $pdo->query("SELECT id, name FROM classrooms")->fetchAll(PDO::FETCH_ASSOC);
$sessions = $pdo->query("SELECT id, name FROM sessions")->fetchAll(PDO::FETCH_ASSOC);
$terms = $pdo->query("SELECT id, name FROM terms")->fetchAll(PDO::FETCH_ASSOC);


// Build exam query with optional filters
$query = "
    SELECT e.id AS exam_id, e.title, e.status, 
           c.name AS class_name, s.name AS session_name, t.name AS term_name,
           t.name AS term_name, CONCAT(u.first_name,' ',u.last_name) AS teacher_name, COUNT(r.id) AS total_attempts,
           COALESCE(AVG(r.score),0) AS avg_score
    FROM cbt_exams e
    LEFT JOIN classrooms c ON e.classroom_id = c.id
    LEFT JOIN sessions s ON e.session_id = s.id
    LEFT JOIN terms t ON e.term_id = t.id
    LEFT JOIN users u ON e.teacher_id = u.id
    LEFT JOIN cbt_exam_results r ON e.id = r.exam_id
    WHERE 1
";


$params = [];

// Apply filters
if ($selected_teacher) { $query .= " AND e.teacher_id = ?"; $params[] = $selected_teacher; }
if ($selected_class) { $query .= " AND e.classroom_id = ?"; $params[] = $selected_class; }
if ($selected_session) { $query .= " AND e.session_id = ?"; $params[] = $selected_session; }
if ($selected_term) { $query .= " AND e.term_id = ?"; $params[] = $selected_term; }

$query .= " GROUP BY e.id ORDER BY e.created_at DESC";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$exams = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container mt-4">
    <h2>Admin Exam Management</h2>

    <!-- Filters -->
    <form class="row g-3 mb-4" method="get">
        <div class="col-md-3">
            <label for="teacher_id" class="form-label">Teacher</label>
            <select name="teacher_id" id="teacher_id" class="form-select">
                <option value="">All Teachers</option>
                <?php foreach ($teachers as $t): ?>
                    <option value="<?= $t['id'] ?>" <?= ($selected_teacher == $t['id']) ? 'selected' : '' ?>><?= htmlspecialchars($t['first_name']) ?> <?= htmlspecialchars($t['last_name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3">
            <label for="class_id" class="form-label">Class</label>
            <select name="class_id" id="class_id" class="form-select">
                <option value="">All Classes</option>
                <?php foreach ($classes as $c): ?>
                    <option value="<?= $c['id'] ?>" <?= ($selected_class == $c['id']) ? 'selected' : '' ?>><?= htmlspecialchars($c['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3">
            <label for="session_id" class="form-label">Session</label>
            <select name="session_id" id="session_id" class="form-select">
                <option value="">All Sessions</option>
                <?php foreach ($sessions as $s): ?>
                    <option value="<?= $s['id'] ?>" <?= ($selected_session == $s['id']) ? 'selected' : '' ?>><?= htmlspecialchars($s['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3">
            <label for="term_id" class="form-label">Term</label>
            <select name="term_id" id="term_id" class="form-select">
                <option value="">All Terms</option>
                <?php foreach ($terms as $t): ?>
                    <option value="<?= $t['id'] ?>" <?= ($selected_term == $t['id']) ? 'selected' : '' ?>><?= htmlspecialchars($t['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-12">
            <button class="btn btn-primary">Filter</button>
        </div>
    </form>

    <!-- Exams Table -->
    <?php if(empty($exams)): ?>
        <div class="alert alert-info">No exams found.</div>
    <?php else: ?>
        <table class="table table-striped table-bordered">
            <thead class="table-dark">
                <tr>
                    <th>Exam Title</th>
                    <th>Teacher</th>
                    <th>Class</th>
                    <th>Session</th>
                    <th>Term</th>
                    <th>Total Attempts</th>
                    <th>Average Score</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($exams as $exam): ?>
                    <tr>
                        <td><?= htmlspecialchars($exam['title']) ?></td>
                        <td><?= htmlspecialchars($exam['teacher_name']) ?></td>
                        <td><?= htmlspecialchars($exam['class_name']) ?></td>
                        <td><?= htmlspecialchars($exam['session_name']) ?></td>
                        <td><?= htmlspecialchars($exam['term_name']) ?></td>
                        <td><?= $exam['total_attempts'] ?></td>
                        <td><?= number_format($exam['avg_score'],2) ?>%</td>
                        <td>
                            <a href="delete_exam.php?exam_id=<?= $exam['exam_id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure?')">Delete</a>
                            <a href="exam_details.php?exam_id=<?= $exam['exam_id'] ?>" class="btn btn-sm btn-primary">Details</a>
                            <button
                            class="btn btn-sm toggle-status <?= $exam['status'] ? 'btn-success' : 'btn-secondary' ?>" 
                                    data-exam-id="<?= $exam['exam_id'] ?>" 
                                    data-status="<?= $exam['status'] ?>">
                                <?= $exam['status'] ? 'Active' : 'Inactive' ?>
                            </button>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    $('.toggle-status').click(function() {
        var btn = $(this);
        var examId = btn.data('exam-id');
        var currentStatus = btn.data('status');
        var newStatus = currentStatus == 1 ? 0 : 1;

        $.ajax({
            url: 'toggle_exam_ajax.php',
            type: 'POST',
            data: { exam_id: examId, status: newStatus },
            success: function(response) {
                if(response == 'success'){
                    // Update button appearance and text
                    btn.data('status', newStatus);
                    if(newStatus == 1){
                        btn.removeClass('btn-secondary').addClass('btn-success').text('Active');
                    } else {
                        btn.removeClass('btn-success').addClass('btn-secondary').text('Inactive');
                    }
                } else {
                    alert('Error updating status.');
                }
            },
            error: function() {
                alert('AJAX request failed.');
            }
        });
    });
});
</script>


<?php include '../includes/footer.php'; ?>
