<?php
require_once("../../public/connection.php");

if (isset($_POST['export_excel'])) {
    // Fetch form data
    $class = isset($_POST['class']) ? $_POST['class'] : '';
    $term = isset($_POST['term']) ? $_POST['term'] : '';
    $session = isset($_POST['session']) ? $_POST['session'] : '';

    // Set filename
    $fileName = "student_performance_" . date("Y-m-d") . ".xls";
    
    // Set headers for download
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=$fileName");

    // Column names
    echo "Student ID\tClass\tTerm\tSession\tAverage Score\n";
    
    // Fetch data
    $query = "SELECT student_id, class, term, session, students_sub_average FROM positions WHERE 1=1";
    if (!empty($class)) $query .= " AND class = '$class'";
    if (!empty($term)) $query .= " AND term = '$term'";
    if (!empty($session)) $query .= " AND session = '$session'";
    
    $result = $connection->query($query);
    
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            echo $row['student_id'] . "\t" . $row['class'] . "\t" . $row['term'] . "\t" . $row['session'] . "\t" . $row['students_sub_average'] . "\n";
        }
    }
    
    exit();
}
?>

