<?php
require("../../includes/config.php");

// 1. Get current filter values
$search = isset($_GET['search']) ? "%{$_GET['search']}%" : "%";
$class_id = isset($_GET['class_id']) ? $_GET['class_id'] : "";
$section = isset($_GET['section']) ? $_GET['section'] : "";

// 2. Prepare the SQL (Same as your fetch API)
$sql = "SELECT e.roll_no, s.student_name, c.class_name, e.section_name, s.parent_phone, s.admission_date 
        FROM students s
        JOIN enrollments e ON s.id = e.student_id
        JOIN classes c ON e.class_id = c.id
        WHERE (s.student_name LIKE :search OR e.roll_no LIKE :search)
        AND e.academic_year_id = :year_id";

if (!empty($class_id)) $sql .= " AND e.class_id = :class_id";
if (!empty($section)) $sql .= " AND e.section_name = :section";

$stmt = $pdo->prepare($sql);
$params = [':search' => $search, ':year_id' => APP_YEAR_ID];
if (!empty($class_id)) $params[':class_id'] = $class_id;
if (!empty($section)) $params[':section'] = $section;
$stmt->execute($params);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 3. Set headers to force download
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=Student_List_' . date('Y-m-d') . '.csv');

// 4. Create the file
$output = fopen('php://output', 'w');
// Add column headers to the Excel file
fputcsv($output, ['Roll No', 'Student Name', 'Class', 'Section', 'Parent Phone', 'Admission Date']);

foreach ($data as $row) {
    fputcsv($output, $row);
}
fclose($output);
exit;
?>