<?php
require_once __DIR__ . '/includes/functions.php';
requireLogin();

$action = $_GET['action'] ?? 'export';
$delimiter = ';'; // semicolon agar kompatibel dengan Excel berlokal Indonesia

function outputCsv($filename, $headers, $rows, $delimiter) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    echo "\xEF\xBB\xBF"; // BOM agar karakter Indonesia tampil benar di Excel
    echo "sep=$delimiter\r\n"; // Memaksa Excel memakai delimiter ini, terlepas dari setting regional
    $out = fopen('php://output', 'w');
    fputcsv($out, $headers, $delimiter);
    foreach ($rows as $row) {
        fputcsv($out, $row, $delimiter);
    }
    fclose($out);
    exit;
}

$headers = ['NIS','NISN','Nama','Jenis Kelamin (L/P)','Tingkat','Kelas','Nominal SPP','Nama Ortu/Wali','No HP Ortu','Status'];

if ($action === 'template') {
    $contoh = [
        ['2025001','0012345678','Contoh Nama Siswa','L','X','IPA 1','150000','Contoh Nama Ortu','081234567890','aktif'],
        ['2025002','0012345679','Contoh Nama Siswa 2','P','XI','IPS 2','150000','Contoh Nama Ortu 2','081234567891','aktif'],
    ];
    outputCsv('template_import_siswa.csv', $headers, $contoh, $delimiter);
} else {
    $data = $pdo->query("
        SELECT s.nis, s.nisn, s.nama, s.jenis_kelamin, t.nama as tingkat_nama, k.nama as kelas_nama,
               s.nominal_spp, s.nama_ortu, s.no_hp_ortu, s.status
        FROM siswa s
        LEFT JOIN kelas k ON k.id = s.kelas_id
        LEFT JOIN tingkat t ON t.id = k.tingkat_id
        ORDER BY s.nama
    ")->fetchAll();

    $rows = array_map(function ($r) {
        return [
            $r['nis'], $r['nisn'], $r['nama'], $r['jenis_kelamin'],
            $r['tingkat_nama'] ?? '', $r['kelas_nama'] ?? '',
            $r['nominal_spp'], $r['nama_ortu'], $r['no_hp_ortu'], $r['status'],
        ];
    }, $data);

    outputCsv('data_siswa_' . date('Y-m-d') . '.csv', $headers, $rows, $delimiter);
}