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

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

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="exam_results.csv"');

$output = fopen('php://output', 'w');
fputcsv($output, ['Student', 'NIC', 'Exam', 'Score', 'Grade', 'Status', 'Date Taken']);

$filter_date = $_GET['date'] ?? '';

$query = "SELECT s.name, s.nic_number, e.title, r.score, r.grade, r.status, r.date_taken
          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);
    $stmt->bind_param("s", $filter_date);
} else {
    $stmt = $conn->prepare($query);
}

$stmt->execute();
$data = $stmt->get_result();

while ($row = $data->fetch_assoc()) {
    fputcsv($output, $row);
}
fclose($output);
exit;
?>
