<?php
session_start();
require_once '../config/database.php';
require_once '../PhpSpreadsheet-master/src/Bootstrap.php';

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

$db = new Database();
$conn = $db->getConnection();
$role = $_SESSION['role'];
$user_id = $_SESSION['user_id'];

if($role == 'admin_dpw'){
    $sql = "SELECT i.*, g.nama_gereja FROM inventaris i 
            LEFT JOIN gereja g ON i.gereja_id = g.id 
            ORDER BY i.id DESC";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
} else {
    $sql = "SELECT i.*, g.nama_gereja 
            FROM inventaris i 
            INNER JOIN gereja g ON i.gereja_id = g.id 
            WHERE g.gembala_id = ? 
            ORDER BY i.id DESC";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$user_id]);
}

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Data Inventaris');
$sheet->setCellValue('A1', 'No')->setCellValue('B1', 'Nama Barang')->setCellValue('C1', 'Kategori')
      ->setCellValue('D1', 'Jumlah')->setCellValue('E1', 'Kondisi')->setCellValue('F1', 'Gereja')
      ->setCellValue('G1', 'Tgl Perolehan');

$sheet->getStyle('A1:G1')->getFont()->setBold(true);

$row = 2;
$no = 1;
while($d = $stmt->fetch(PDO::FETCH_ASSOC)){
    $sheet->setCellValue('A'.$row, $no++)
          ->setCellValue('B'.$row, $d['nama_barang'])
          ->setCellValue('C'.$row, $d['kategori'])
          ->setCellValue('D'.$row, $d['jumlah'])
          ->setCellValue('E'.$row, $d['kondisi'])
          ->setCellValue('F'.$row, $d['nama_gereja'])
          ->setCellValue('G'.$row, $d['tgl_perolehan'] ?? '-');
    $row++;
}

foreach(range('A','G') as $col) {
    $sheet->getColumnDimension($col)->setAutoSize(true);
}

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="laporan_inventaris_'.date('Ymd').'.xlsx"');
header('Cache-Control: max-age=0');

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