<?php
require 'db_config.php';
$table = $_GET['table'] ?? '';
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename={$table}_export.xls");

function fetchRows($conn, $sql){
    $res = $conn->query($sql);
    if (!$res) return [];
    $html = '';
    while($r=$res->fetch_assoc()){
        $html.="<tr>";
        foreach($r as $v) $html.="<td>".htmlspecialchars($v)."</td>";
        $html.="</tr>";
    }
    return $html;
}

echo "<table border='1'><thead>";
if ($table==='attendance') {
    echo "<tr><th>ID</th><th>User ID</th><th>Time</th><th>Type</th><th>Name</th></tr></thead><tbody>";
    echo fetchRows($conn, "SELECT * FROM attendance ORDER BY id DESC");
} elseif ($table==='meal') {
    echo "<tr><th>ID</th><th>User ID</th><th>Full Name</th><th>Meal Type</th><th>Time</th></tr></thead><tbody>";
    echo fetchRows($conn, "SELECT * FROM meal_deductions ORDER BY id DESC");
} elseif ($table==='promo') {
    echo "<tr><th>ID</th><th>User ID</th><th>Name</th><th>Collected</th><th>Status</th><th>Time</th></tr></thead><tbody>";
    echo fetchRows($conn, "SELECT * FROM promotional_materials ORDER BY id DESC");
} else {
    echo "<tr><th>Error: Unknown Table</th></tr></thead><tbody>";
}
echo "</tbody></table>";
