<?php
include '../../config/conn.php';
include '../../lib/function.php';

if (!isset($_POST['columns']) || count($_POST['columns']) === 0) {
    die("Tidak ada kolom yang dipilih.");
}

$selected_columns = $_POST['columns'];
$column_list = implode(", ", $selected_columns);

// Header untuk Excel
header("Content-type: application/vnd-ms-excel");
header("Content-Disposition: attachment; filename=data_santri_export.xls");

// Ambil data dari database
$query = mysqli_query($conn, "SELECT $column_list FROM santri ORDER BY nama");

echo "<table border='1'>";
echo "<thead><tr>";
foreach ($selected_columns as $col) {
    echo "<th>" . ucfirst(str_replace("_", " ", $col)) . "</th>";
}
echo "</tr></thead><tbody>";

while ($row = mysqli_fetch_assoc($query)) {
    echo "<tr>";
    foreach ($selected_columns as $col) {
        $value = $row[$col];
        // Format khusus untuk jenis kelamin
        if ($col === 'jenkel') {
            $value = $value === 'l' ? 'Laki-laki' : 'Perempuan';
        }
        // Format aman Excel untuk angka panjang (NIK, no_hp, no_kk)
        if (in_array($col, ['nik_santri', 'nik_ayah', 'nik_ibu', 'no_hp', 'no_kk'])) {
            $value = "'" . $value;
        }
        echo "<td>$value</td>";
    }
    echo "</tr>";
}
echo "</tbody></table>";

echo "<br><br>Data diekspor pada: " . date('d-m-Y H:i:s');
?>
