<?php
// Include necessary files and connect to the database
include("includes/db.php");

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["classId"])) {
    $classId = $_POST["classId"];

    // Fetch student details for the selected class from the database
    $query = "SELECT * FROM students WHERE class_id = '$classId'";
    $result = $conn->query($query);

    if ($result->num_rows > 0) {
        // Set CSV headers
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=student_details_pr.csv');
        
        // Create a file pointer connected to the output stream
        $output = fopen('php://output', 'w');
        
        // CSV column headers
        fputcsv($output, array('Student ID','Iemis No', 'Name', 'Sym No', 'marks_pr'));
        
        // Fetch and format student details as CSV rows
        while ($row = $result->fetch_assoc()) {
            fputcsv($output, array(
                $row['student_id'],
                $row['regd_id'],
                $row['name'],
                $row['symbol_no'],
               
            ));
        }

        // Close the file pointer
        fclose($output);
    } else {
        echo "No data available for the selected class.";
    }
} else {
    header("Location: bulk_marks_pr.php");
}

// Close the database connection
$conn->close();
?>
