<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: ../index.html?error=session");
    exit;
}

require_once '../database/koneksi.php';

$sql = "SELECT no, tanggal_perolehan, kategori, sumber_dana, kantor, 
        jenis_barang, jenis_inventory, harga_perolehan 
        FROM inventory 
        ORDER BY no ASC";

$result = $koneksi->query($sql);

// Set headers untuk download
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="inventory_acf_' . date('Y-m-d') . '.csv"');

// Create output stream
$output = fopen('php://output', 'w');

// UTF-8 BOM untuk Excel
fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

// Header CSV
$headers = ['No', 'Tanggal Perolehan', 'Kategori', 'Sumber Dana', 'Kantor', 
            'Jenis Barang', 'Jenis Inventory', 'Harga Perolehan'];
fputcsv($output, $headers);

// Data rows
while ($row = $result->fetch_assoc()) {
    fputcsv($output, [
        $row['no'],
        $row['tanggal_perolehan'],
        $row['kategori'],
        $row['sumber_dana'],
        $row['kantor'],
        $row['jenis_barang'],
        $row['jenis_inventory'],
        $row['harga_perolehan']
    ]);
}

fclose($output);
$koneksi->close();
exit;
?>