<?php
require 'koneksi.php';
require 'vendor/autoload.php'; // pastikan path ini benar

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

// Ambil parameter dari GET
$id_gudang   = $_GET['id_gudang'] ?? null;
$tahun       = $_GET['tahun'] ?? null;
$nama_gudang = $_GET['nama_gudang'] ?? null;

if (!$id_gudang || !$tahun) {
    die("Gudang dan tahun wajib diisi!");
}

// Ambil data hasil_opname
$query = "
    SELECT b.nama_barang, h.part_number, h.satuan, h.barcode,
           h.kondisi_bagus, h.kondisi_rusak, h.stock_akhir
    FROM hasil_opname h
    JOIN barang b ON b.id_barang = h.id_barang
    WHERE h.id_gudang = ? AND h.tahun = ?
";
$stmt = $conn->prepare($query);
$stmt->bind_param("ii", $id_gudang, $tahun);
$stmt->execute();
$result = $stmt->get_result();

// Buat spreadsheet baru
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

// Judul kolom
$header = ['No', 'Nama Barang', 'Part Number', 'Satuan', 'Barcode', 'Kondisi Bagus', 'Kondisi Rusak', 'Stock Akhir'];
$col = 'A';
foreach ($header as $h) {
    $sheet->setCellValue($col . '1', $h);
    $col++;
}

// Isi data
$row = 2;
$no = 1;
while ($data = $result->fetch_assoc()) {
    $sheet->setCellValue("A{$row}", $no++);
    $sheet->setCellValue("B{$row}", $data['nama_barang']);
    $sheet->setCellValue("C{$row}", $data['part_number']);
    $sheet->setCellValue("D{$row}", $data['satuan']);
    $sheet->setCellValue("E{$row}", $data['barcode']);
    $sheet->setCellValue("F{$row}", $data['kondisi_bagus']);
    $sheet->setCellValue("G{$row}", $data['kondisi_rusak']);
    $sheet->setCellValue("H{$row}", $data['stock_akhir']);
    $row++;
}

// Nama file
$clean_nama_gudang = preg_replace('/[^A-Za-z0-9_-]/', '_', $nama_gudang); // Biar aman dari karakter aneh
$filename = "Opname_{$clean_nama_gudang}_Tahun_{$tahun}.xlsx";

// Output
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment; filename=\"$filename\"");
header('Cache-Control: max-age=0');

$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
exit;
?>
