<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
requireLogin('admin');

$data = json_decode($_POST['export_json'] ?? '[]', true);
if (empty($data)) {
    die('Tidak ada data untuk diexport.');
}

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=belum_daftar_kkn_' . date('Ymd') . '.csv');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

echo "\xEF\xBB\xBF";
echo "No,NIM,Nama,Prodi,Kecamatan,Kabupaten,DPL\n";
foreach ($data as $i => $r) {
    echo implode(',', [
        $i+1,
        '"'.str_replace('"','""',$r['nim']).'"',
        '"'.str_replace('"','""',$r['nama']).'"',
        '"'.str_replace('"','""',$r['prodi']).'"',
        '"'.str_replace('"','""',$r['kecamatan']).'"',
        '"'.str_replace('"','""',$r['kabupaten']).'"',
        '"'.str_replace('"','""',$r['dpl_nama']).'"',
    ]) . "\n";
}
exit;
