<?php
    session_start();

    include("../scripts/connection.php");
    include("../scripts/functions.php");
    $user_data = check_admin($con);

    if(isset($_GET['table'])) {
        $table = $_GET['table'];
    }

    ob_start('ob_gzhandler'); #compressing data which is sent to the browser, the browser will decompress the data automatically
    header('Content-type: text/csv; charset="UTF-8" ');
    header('Content-Disposition: attachment; filename="table.csv" ');

function download_table($stmt) {
    $output = fopen('php://output', 'w');
    $header = true;
    while ($row = $stmt->fetch()) {
        if ($header) {
            fputcsv($output, array_keys($row));
            $header = false;
        }
        fputcsv($output, $row);
    }
    fclose($output);
}

    if($table == "total-score") {
        $total_score = get_total_score($con);
        download_table($total_score);
    } else {
        $station = get_station($con, $table);
        download_table($station);
    }
?>