<?php
require_once __DIR__ . '/../../core/init.php';
require_once __DIR__ . '/../../vendor/autoload.php';

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

// --- CẬP NHẬT SQL: Bỏ quy cách ---
$sql = "SELECT 
            p.prd_name, p.prd_code, p.prd_image_url, p.prd_sls AS prd_inventory, 
            p.prd_origin_price, p.prd_sell_price, p.prd_sell_price2, 
            g.prd_group_name, m.prd_manuf_name, u.prd_unit_name, 
            p.prd_size, p.prd_color
        FROM cms_products p 
        LEFT JOIN cms_products_group g ON p.prd_group_id = g.id 
        LEFT JOIN cms_products_manufacture m ON p.prd_manufacture_id = m.id
        LEFT JOIN cms_products_unit u ON p.prd_unit_id = u.id
        WHERE p.deleted = 0
        ORDER BY p.id DESC";
$result = $conn->query($sql);

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Danh Sach San Pham');

// --- TIÊU ĐỀ CỘT ---
$headers = [
    'A' => 'Tên sản phẩm',
    'B' => 'Mã sản phẩm',
    'C' => 'Đường dẫn Ảnh',
    'D' => 'Tồn kho',
    'E' => 'Giá vốn',
    'F' => 'Giá bán lẻ',
    'G' => 'Giá bán sỉ',
    'H' => 'Danh mục',
    'I' => 'Nhà sản xuất',
    'J' => 'Đơn vị tính',
    'K' => 'Size',
    'L' => 'Màu sắc'
];

foreach ($headers as $col => $text) {
    $sheet->setCellValue($col . '1', $text);
}

// In đậm tiêu đề
$sheet->getStyle('A1:L1')->getFont()->setBold(true);

$rowIndex = 2;
if ($result && $result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $sheet->setCellValue('A' . $rowIndex, $row['prd_name']);
        $sheet->setCellValue('B' . $rowIndex, $row['prd_code']);
        $sheet->setCellValue('C' . $rowIndex, $row['prd_image_url']);
        $sheet->setCellValue('D' . $rowIndex, $row['prd_inventory']);
        $sheet->setCellValue('E' . $rowIndex, $row['prd_origin_price']);
        $sheet->setCellValue('F' . $rowIndex, $row['prd_sell_price']);
        $sheet->setCellValue('G' . $rowIndex, $row['prd_sell_price2']);
        $sheet->setCellValue('H' . $rowIndex, $row['prd_group_name']);
        $sheet->setCellValue('I' . $rowIndex, $row['prd_manuf_name']);
        $sheet->setCellValue('J' . $rowIndex, $row['prd_unit_name']);
        $sheet->setCellValue('K' . $rowIndex, $row['prd_size']);
        $sheet->setCellValue('L' . $rowIndex, $row['prd_color']);

        $rowIndex++;
    }
}

// Tự động giãn cột
foreach (range('A', 'L') as $columnID) {
    $sheet->getColumnDimension($columnID)->setAutoSize(true);
}

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

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