<?php
session_start();
require_once "../includes/db.php";
if (!isset($_SESSION['admin'])) { header("Location: index.php"); exit; }

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

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

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

$sql = "SELECT s.name, s.nic_number, e.title, r.score, r.grade, r.status, r.created_at
        FROM results r
        JOIN students s ON s.id = r.student_id
        JOIN exams e ON e.id = r.exam_id";

$params = [];
$types  = "";

if (!empty($filter_date)) {
  $sql .= " WHERE DATE(r.created_at)=?";
  $params[] = $filter_date; $types .= "s";
}
$sql .= " ORDER BY r.created_at DESC";

$stmt = $conn->prepare($sql);
if (!empty($params)) { $stmt->bind_param($types, ...$params); }
$stmt->execute();
$res = $stmt->get_result();

while($row = $res->fetch_assoc()){
  fputcsv($out, [$row['name'],$row['nic_number'],$row['title'],$row['score'],$row['grade'],$row['status'],$row['created_at']]);
}
fclose($out);
exit;
