<?php
include '../includes/conn.php';
include '../includes/header.php';

requireRole('teacher');

$teacher_id = $_SESSION['user_id'];

// Get selected session and term from GET, fallback to null
$selected_session = $_GET['session_id'] ?? null;
$selected_term = $_GET['term_id'] ?? null;

// Fetch available sessions and terms for dropdown
$sessions = $pdo->query("SELECT id, name FROM sessions ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
$terms = $pdo->query("SELECT id, name FROM terms ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

// Fetch exams with optional filtering
$query = "
    SELECT 
        e.id AS exam_id,
        e.title,
        e.created_at,
        c.name AS class_name,
        s.name AS session_name,
        t.name AS term_name,
        COUNT(r.id) AS total_attempts,
        COALESCE(AVG(r.score), 0) AS avg_score,
        COALESCE(MAX(r.score), 0) AS max_score,
        COALESCE(MIN(r.score), 0) AS min_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 cbt_exam_results r ON e.id = r.exam_id
    WHERE e.teacher_id = ?
";

$params = [$teacher_id];

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);

// Prepare chart data
$chart_labels = [];
$chart_data = [];
$pass_fail_data = [];

foreach ($exams as $exam) {
    $chart_labels[] = htmlspecialchars($exam['title'] . ' (' . $exam['class_name'] . ')');
    $chart_data[] = round($exam['avg_score'], 2);

    // Calculate pass/fail counts
    $pass_stmt = $pdo->prepare("SELECT 
                                    SUM(CASE WHEN score >= 50 THEN 1 ELSE 0 END) AS passed,
                                    SUM(CASE WHEN score < 50 THEN 1 ELSE 0 END) AS failed
                                 FROM cbt_exam_results
                                 WHERE exam_id = ?");
    $pass_stmt->execute([$exam['exam_id']]);
    $pf = $pass_stmt->fetch(PDO::FETCH_ASSOC);
    $pass_fail_data[] = [
        'passed' => (int)$pf['passed'],
        'failed' => (int)$pf['failed']
    ];
}

// Prepare line chart data
$line_labels = $chart_labels;
$line_data = $chart_data;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Exam Reports</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="bg-light">
<div class="container mt-5">
    <h2 class="mb-4">Exam Reports</h2>

    <!-- Filter Form -->
    <form class="row g-3 mb-4" method="get">
        <div class="col-md-4">
            <label for="session_id" class="form-label">Select 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-4">
            <label for="term_id" class="form-label">Select 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-md-4 align-self-end">
            <button type="submit" class="btn btn-primary">Filter</button>
        </div>
    </form>

    <?php if (!empty($exams)): ?>
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card shadow-sm">
                    <div class="card-body">
                        <h5 class="card-title">Average Score Per Exam</h5>
                        <canvas id="avgScoreChart"></canvas>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card shadow-sm">
                    <div class="card-body">
                        <h5 class="card-title">Score Trend</h5>
                        <canvas id="scoreTrendChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <!-- Exams Table -->
    <?php if (empty($exams)): ?>
        <div class="alert alert-info">No exams found.</div>
    <?php else: ?>
        <table class="table table-bordered table-striped">
            <thead class="table-dark">
                <tr>
                    <th>Exam Title</th>
                    <th>Class</th>
                    <th>Session</th>
                    <th>Term</th>
                    <th>Date Created</th>
                    <th>Total Attempts</th>
                    <th>Average Score</th>
                    <th>Highest</th>
                    <th>Lowest</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($exams as $exam): ?>
                    <tr>
                        <td><?= htmlspecialchars($exam['title']) ?></td>
                        <td><?= htmlspecialchars($exam['class_name']) ?></td>
                        <td><?= htmlspecialchars($exam['session_name']) ?></td>
                        <td><?= htmlspecialchars($exam['term_name']) ?></td>
                        <td><?= htmlspecialchars($exam['created_at']) ?></td>
                        <td><?= $exam['total_attempts'] ?></td>
                        <td><?= number_format($exam['avg_score'], 2) ?>%</td>
                        <td><?= $exam['max_score'] ?>%</td>
                        <td><?= $exam['min_score'] ?>%</td>
                        <td>
                            <a href="exam_details.php?exam_id=<?= $exam['exam_id'] ?>" class="btn btn-sm btn-primary">View Details</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<script>
// Bar chart
const avgCtx = document.getElementById('avgScoreChart').getContext('2d');
new Chart(avgCtx, {
    type: 'bar',
    data: {
        labels: <?= json_encode($chart_labels) ?>,
        datasets: [{
            label: 'Average Score (%)',
            data: <?= json_encode($chart_data) ?>,
            backgroundColor: 'rgba(13, 110, 253, 0.7)',
            borderColor: 'rgba(13, 110, 253, 1)',
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        plugins: { legend: { display: false } },
        scales: { y: { beginAtZero: true, max: 100 } }
    }
});

// Line chart
const lineCtx = document.getElementById('scoreTrendChart').getContext('2d');
new Chart(lineCtx, {
    type: 'line',
    data: {
        labels: <?= json_encode($line_labels) ?>,
        datasets: [{
            label: 'Average Score (%)',
            data: <?= json_encode($line_data) ?>,
            fill: false,
            borderColor: 'rgba(220, 53, 69, 0.8)',
            tension: 0.3,
            pointBackgroundColor: 'rgba(220, 53, 69, 1)',
            pointRadius: 5
        }]
    },
    options: {
        responsive: true,
        plugins: { legend: { display: false } },
        scales: { y: { beginAtZero: true, max: 100 } }
    }
});


</script>
</body>
</html>
