<?php
include 'includes/db.php';

if (isset($_GET['exam_id'], $_GET['class_ids'])) {
    $exam_id = $_GET['exam_id'];
    $class_ids = explode(',', $_GET['class_ids']);

    // Set headers for CSV download
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="student_data.csv"');

    $output = fopen("php://output", "w");

    // Write the headers to the CSV file manually
    $headers = ['student_id', 'student_name', 'class_id', 'class_name', 'exam_id', 'symbol_no'];
    echo implode(',', $headers) . "\n";

    // Create placeholders for SQL IN clause
    $class_placeholders = implode(',', array_fill(0, count($class_ids), '?'));

    // Prepare the SQL query to fetch student details
    $stmt = $conn->prepare("SELECT s.student_id, s.name, c.class_name, c.Class_id
                            FROM students s
                            JOIN classes c ON s.class_id = c.Class_id
                            WHERE s.class_id IN ($class_placeholders)
                            ORDER BY s.name"); // Order alphabetically by student name

    // Bind parameters for the class IDs
    $types = str_repeat('i', count($class_ids));
    $stmt->bind_param($types, ...$class_ids);
    $stmt->execute();
    $result = $stmt->get_result();

    // Write student data to the CSV file
    while ($row = $result->fetch_assoc()) {
        // Prepare the row data for CSV
        $rowData = [
            $row['student_id'],
            $row['name'],         // student_name
            $row['Class_id'],     // class_id
            $row['class_name'],   // class_name
            $exam_id,             // exam_id (from the query parameter)
            ''                    // symbol_no (blank)
        ];

        // Output the row data as a CSV string
        echo implode(',', $rowData) . "\n";
    }

    // Close the output stream
    fclose($output);
    exit;
}
?>
