<?php
// get/template_spareparts.php

// 1. Cek apakah file autoload ada
 $autoloadPath = __DIR__ . '/../vendor/autoload.php';

if (!file_exists($autoloadPath)) {
    // Tampilkan pesan error yang jelas jika library belum diinstall
    die("
        <div style='font-family: Arial; padding: 50px; text-align: center; background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; border-radius: 10px; max-width: 600px; margin: 50px auto;'>
            <h2>Library Tidak Ditemukan</h2>
            <p>File <code>vendor/autoload.php</code> tidak ada.</p>
            <hr>
            <p><strong>Cara Mengatasi:</strong></p>
            <p>Buka terminal di folder project Anda, lalu jalankan perintah:</p>
            <div style='background: #333; color: #fff; padding: 10px; border-radius: 5px; font-family: monospace; text-align: left; display: inline-block; padding: 10px 20px;'>
                composer require phpoffice/phpspreadsheet
            </div>
        </div>
    ");
}

// 2. Load library
require_once $autoloadPath;

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

// 3. Proses membuat file
 $spreadsheet = new Spreadsheet();
 $sheet = $spreadsheet->getActiveSheet();

// Set Header Kolom
 $headers = [
    'A1' => 'Part Number',
    'B1' => 'Nama Barang',
    'C1' => 'Kategori',
    'D1' => 'Lokasi',
    'E1' => 'Material Group',
    'F1' => 'Stock',
    'G1' => 'Min Stock',
    'H1' => 'Unit',
    'I1' => 'Harga',
    'J1' => 'Deskripsi'
];

foreach ($headers as $cell => $value) {
    $sheet->setCellValue($cell, $value);
}

// Style Header Bold
 $sheet->getStyle('A1:J1')->getFont()->setBold(true);

// Set Width Auto
foreach (range('A', 'J') as $columnID) {
    $sheet->getColumnDimension($columnID)->setAutoSize(true);
}

// Contoh Data
 $sheet->setCellValue('A2', 'BP-001');
 $sheet->setCellValue('B2', 'Bearing 6205');
 $sheet->setCellValue('C2', 'Mechanical'); // Harus sesuai data master
 $sheet->setCellValue('D2', 'Warehouse A1'); // Harus sesuai data master
 $sheet->setCellValue('E2', 'OTOMOTIF'); // Harus sesuai data master
 $sheet->setCellValue('F2', '10');
 $sheet->setCellValue('G2', '5');
 $sheet->setCellValue('H2', 'pcs');
 $sheet->setCellValue('I2', '150000');
 $sheet->setCellValue('J2', 'Deep groove ball bearing');

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

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