<?php
require_once __DIR__ . '/config/config.php';

header("Content-Type: text/csv; charset=UTF-8");
header("Content-Disposition: attachment; filename=kwitansi_export.csv");
header("Pragma: no-cache");
header("Expires: 0");

$output = fopen("php://output", "w");

/* BOM UTF-8 (ANTI KARAKTER ANEH EXCEL) */
fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

/* HEADER CSV (URUTAN FIX) */
fputcsv($output, [
    'tanggal',
    'kode_kegiatan',
    'kode_rekening',
    'nobukti',
    'uraian',
    'jumb',
    'satuanb',
    'pengeluaran',
    'yang_menerima'
]);

/* QUERY PER KOLOM (JANGAN SELECT *) */
$sql = "SELECT 
            tanggal,
            kode_kegiatan,
            kode_rekening,
            nobukti,
            uraian,
            jumb,
            satuanb,
            pengeluaran,
            yang_menerima
        FROM kwitansi
        ORDER BY id_kw ASC";

$q = $conn->query($sql);

while ($r = $q->fetch_assoc()) {
    fputcsv($output, [
        $r['tanggal'],
        $r['kode_kegiatan'],
        $r['kode_rekening'],
        $r['nobukti'],
        $r['uraian'],
        $r['jumb'],
        $r['satuanb'],
        number_format($r['pengeluaran'], 0, '', ''), // angka polos
        $r['yang_menerima']
    ]);
}

fclose($output);
exit;
