<?php
// Error reporting for debugging (remove or adjust for production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8'); // Set JSON response and UTF-8

$response = ['success' => false, 'message' => 'Unknown error occurred.']; // Default error

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method. Only POST is accepted.');
    }

    // Get JSON data from the request body
    $jsonInput = file_get_contents('php://input');
    $data = json_decode($jsonInput, true);

    // Check for JSON decoding errors
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid JSON input received: ' + json_last_error_msg());
    }

    // Check if data is empty
    if (empty($data)) {
        throw new Exception('No data received to generate Excel file.');
    }

    // Include the PHPExcel library (ensure the path is correct)
    require '../PHPExcel_1.8.0/Classes/PHPExcel.php'; // Adjust path as needed

    // Create new PHPExcel object
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->setActiveSheetIndex(0);
    $sheet = $objPHPExcel->getActiveSheet();
    $sheet->setTitle('BOM List'); // Optional: Set sheet title

    // === Define Headers ===
    // Keys MUST match the keys sent by the JavaScript generateExcel function.
    // Values are the desired header text in the Excel file (from your thead).
    $headers = [
        'no'               => '번호',
        'categoryMain'     => '대분류',
        'categorySub'      => '중분류',
        'modelName'        => '모델명',
        'shape'            => '형상',
        'finishType'       => '마감타입',
        'specification'    => '규격',
        'boxWidth'         => '박스폭',
        'boxHeight'        => '박스높이',
        'frontBottom'      => '전면밑',
        'railWidth'        => '레일폭',
        'form'             => '형태',
        'unitPriceM'       => '단가/M',
        'memo'             => '메모',
        'priceBaseDate'    => '단가기준일',
        'registrationDate' => '등록일',
        'modificationDate' => '수정일'
    ];

    // === Write Headers to Excel ===
    $col = 'A'; // Start column
    foreach ($headers as $headerText) {
        $sheet->setCellValue($col . '1', $headerText);
        // Style header cells (Bold, Gray Background)
        $headerStyle = $sheet->getStyle($col . '1');
        $headerStyle->getFont()->setBold(true);
        $headerStyle->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
                      ->getStartColor()->setRGB('D9D9D9'); // Light gray
        $headerStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); // Center align headers
        $col++;
    }
    // Determine the last column letter (17 columns: A to Q)
    $lastCol = $sheet->getHighestColumn(); // Should be 'Q' after writing headers

    // === Fill Data ===
    $rowNumber = 2; // Start data from row 2
    foreach ($data as $row) {
        $col = 'A'; // Reset column for each row
        foreach ($headers as $key => $headerText) { // Use the key from $headers
            // Get value from $row using the $key, default to empty string if not set
            $value = isset($row[$key]) ? $row[$key] : '';
            $sheet->setCellValue($col . $rowNumber, $value);
            $col++;
        }
        $rowNumber++;
    }
    $lastRow = $rowNumber - 1; // The last row containing data

    // === Apply Styling ===

    // Set Column Widths (Adjust as needed)
    $sheet->getColumnDimension('A')->setWidth(8);  // 번호
    $sheet->getColumnDimension('B')->setWidth(15); // 대분류
    $sheet->getColumnDimension('C')->setWidth(30); // 중분류
    $sheet->getColumnDimension('D')->setWidth(25); // 모델명
    $sheet->getColumnDimension('E')->setWidth(12); // 형상
    $sheet->getColumnDimension('F')->setWidth(15); // 마감타입
    $sheet->getColumnDimension('G')->setWidth(25); // 규격
    $sheet->getColumnDimension('H')->setWidth(10); // 박스폭
    $sheet->getColumnDimension('I')->setWidth(10); // 박스높이
    $sheet->getColumnDimension('J')->setWidth(10); // 전면밑
    $sheet->getColumnDimension('K')->setWidth(10); // 레일폭
    $sheet->getColumnDimension('L')->setWidth(12); // 형태
    $sheet->getColumnDimension('M')->setWidth(15); // 단가/M
    $sheet->getColumnDimension('N')->setWidth(40); // 메모
    $sheet->getColumnDimension('O')->setWidth(15); // 단가기준일
    $sheet->getColumnDimension('P')->setWidth(18); // 등록일
    $sheet->getColumnDimension('Q')->setWidth(18); // 수정일

    // Apply Borders to all cells (Header + Data)
    $styleArray = [
        'borders' => [
            'allborders' => [
                'style' => PHPExcel_Style_Border::BORDER_THIN,
                'color' => ['rgb' => '000000'] // Black border
            ],
        ],
        'alignment' => [ // Default alignment for data cells
             'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
             'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
        ]
    ];
    if ($lastRow >= 1) { // Apply style only if there is data
         $sheet->getStyle('A1:' . $lastCol . $lastRow)->applyFromArray($styleArray);
    }


    // Set Specific Alignments for Data Rows (Row 2 downwards)
    if ($lastRow >= 2) {
        $dataRange = 'A2:' . $lastCol . $lastRow;
        // Center align '번호' column
        $sheet->getStyle('A2:A' . $lastRow)->getAlignment()
              ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        // Right align numeric columns
        $numericCols = ['H', 'I', 'J', 'K', 'M']; // 박스폭, 박스높이, 전면밑, 레일폭, 단가/M
        foreach ($numericCols as $numCol) {
            $sheet->getStyle($numCol . '2:' . $numCol . $lastRow)->getAlignment()
                  ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
            // Optional: Apply number format if needed (e.g., for currency or decimals)
            // $sheet->getStyle($numCol.'2:'.$numCol.$lastRow)->getNumberFormat()
            //       ->setFormatCode('#,##0'); // Example: Comma separated integer
        }
         // Center align date columns if desired
         $dateCols = ['O', 'P', 'Q']; // 단가기준일, 등록일, 수정일
         foreach ($dateCols as $dateCol) {
             $sheet->getStyle($dateCol . '2:' . $dateCol . $lastRow)->getAlignment()
                   ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
         }
    }


    // === Save File ===
    $filename = 'KD_BOMlist_' . date('Ymd_His') . '.xlsx'; // Use underscore for better compatibility
    // IMPORTANT: Ensure this directory exists and is writable by the web server!
    $filePath = '../excelsave/' . $filename; // Adjust path as needed

    // Check if directory exists, create if not (optional, requires permissions)
    $dirPath = dirname($filePath);
    if (!is_dir($dirPath)) {
        if (!mkdir($dirPath, 0775, true)) { // Adjust permissions as needed (0775 is common)
             throw new Exception("Failed to create directory: {$dirPath}. Check permissions.");
        }
    }

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); // XLSX format
    $objWriter->save($filePath);

    // Verify file was saved
    if (file_exists($filePath)) {
        $response = ['success' => true, 'filename' => $filePath]; // Send back the full path or just filename
    } else {
        throw new Exception('Failed to save the Excel file to the server.');
    }

} catch (Exception $e) {
    error_log("Excel Generation Error: " . $e->getMessage()); // Log the actual error
    $response = ['success' => false, 'message' => $e->getMessage()];
}

// Return JSON response
echo json_encode($response);
?>