<?php
session_start();
require_once "../includes/db.php";

if (!isset($_SESSION['admin'])) {
    header("Location: index.php");
    exit;
}

$filter_date = $_GET['date'] ?? '';
$query = "SELECT r.*, s.name, s.nic_number, e.title 
          FROM results r 
          JOIN students s ON r.student_id = s.id
          JOIN exams e ON r.exam_id = e.id";

if ($filter_date) {
    $query .= " WHERE DATE(r.date_taken) = ?";
}

$stmt = $conn->prepare($query);
if ($filter_date) {
    $stmt->bind_param("s", $filter_date);
}
$stmt->execute();
$results = $stmt->get_result();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Exam Results</title>
    <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
    <h3>Exam Results</h3>

    <form method="GET" class="row g-3 mb-3">
        <div class="col-auto">
            <input type="date" name="date" class="form-control" value="<?= htmlspecialchars($filter_date) ?>">
        </div>
        <div class="col-auto">
            <button type="submit" class="btn btn-primary">Filter</button>
            <a href="view_results.php" class="btn btn-secondary">Reset</a>
        </div>
        <div class="col-auto">
            <a href="export_results.php?date=<?= urlencode($filter_date) ?>" class="btn btn-success">Download CSV</a>
        </div>
    </form>

    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Student</th>
                <th>NIC</th>
                <th>Exam</th>
                <th>Score</th>
                <th>Grade</th>
                <th>Status</th>
                <th>Date Taken</th>
            </tr>
        </thead>
        <tbody>
            <?php while($row = $results->fetch_assoc()): ?>
                <tr>
                    <td><?= $row['name'] ?></td>
                    <td><?= $row['nic_number'] ?></td>
                    <td><?= $row['title'] ?></td>
                    <td><?= $row['score'] ?></td>
                    <td><?= $row['grade'] ?></td>
                    <td><?= $row['status'] ?></td>
                    <td><?= $row['date_taken'] ?></td>
                </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>
</body>
</html>
