<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Inventory.php';

require_once __DIR__ . '/../../vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;


$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);


if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}
if ($_SESSION['role'] != 'admin' && $_SESSION['role'] != 'warehouse') {
    header('Location: /IMS/unauthorized.php');
    exit();
}


$branchId = isset($_GET['branch_id']) ? filter_input(INPUT_GET, 'branch_id', FILTER_SANITIZE_NUMBER_INT) : null;
$itemType = isset($_GET['item_type']) ? $_GET['item_type'] : null;
$searchTerm = isset($_GET['search_term']) ? trim($_GET['search_term']) : '';
$searchField = isset($_GET['search_field']) ? $_GET['search_field'] : '';


if ($branchId === null || !in_array($itemType, ['simple', 'detailed'])) {
    die('Invalid parameters.');
}


$stmtBranch = $conn->prepare("SELECT branch_name FROM branches WHERE branch_id = ?");
$stmtBranch->execute([$branchId]);
$branchName = $stmtBranch->fetchColumn();
if ($branchId == 0) {
    $branchName = 'All Branches';
}
if (!$branchName) {
    die('Invalid branch.');
}


$inventory = new Inventory($conn);
$items = [];
if ($itemType === 'simple') {
    if (!empty($searchTerm) && !empty($searchField)) {
        $items = $inventory->searchSimpleItems($branchId == 0 ? null : $branchId, $searchField, $searchTerm);
    } else {
        $items = $inventory->getSimpleItems($branchId == 0 ? null : $branchId);
    }
} elseif ($itemType === 'detailed') {
    if (!empty($searchTerm) && !empty($searchField)) {
        $items = $inventory->searchDetailedItems($branchId == 0 ? null : $branchId, $searchField, $searchTerm);
    } else {
        $items = $inventory->getDetailedItems($branchId == 0 ? null : $branchId);
    }
}


$totalItems = count($items);
$totalValue = 0;
foreach ($items as $item) {
    if (isset($item['unit_price']) && is_numeric($item['unit_price'])) {
        $totalValue += $item['unit_price'];
    }
}


$header = $itemType === 'detailed' ?
    ['Unique ID', 'Item Name', 'Item Details', 'Category', 'Unit Price', 'Date Entered', 'Serial Number', 'Technical Specs', 'Condition'] :
    ['Unique ID', 'Item Name', 'Item Details', 'Category', 'Unit Price', 'Date Entered'];


$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Inventory');


$sheet->setCellValue('A1', 'Inventory Report - ' . $branchName);
$sheet->mergeCells('A1:' . chr(64 + count($header)) . '1');
$sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
$sheet->getStyle('A1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

$sheet->setCellValue('A2', 'Item Type: ' . ucfirst($itemType) . '   |   Total Items: ' . $totalItems . '   |   Total Value: MWK ' . number_format($totalValue, 2) . '   |   Generated: ' . date('M d, Y'));
$sheet->mergeCells('A2:' . chr(64 + count($header)) . '2');
$sheet->getStyle('A2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

if (!empty($searchTerm)) {
    $sheet->setCellValue('A3', 'Search: "' . $searchTerm . '" (by ' . $searchField . ')');
    $sheet->mergeCells('A3:' . chr(64 + count($header)) . '3');
    $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
    $headerRow = 5;
} else {
    $headerRow = 4;
}


foreach ($header as $colIndex => $colName) {
    $col = chr(65 + $colIndex);
    $sheet->setCellValue($col . $headerRow, $colName);
}
$headerRange = 'A' . $headerRow . ':' . chr(64 + count($header)) . $headerRow;
$sheet->getStyle($headerRange)->getFont()->setBold(true)->getColor()->setRGB('FFFFFF');
$sheet->getStyle($headerRange)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('243447');


$row = $headerRow + 1;
foreach ($items as $item) {
    $sheet->setCellValue('A' . $row, $item['unique_id']);
    $sheet->setCellValue('B' . $row, $item['item_name']);
    $sheet->setCellValue('C' . $row, $item['item_details'] ?? 'N/A');
    $sheet->setCellValue('D' . $row, $item['category'] ?? 'N/A');
    $sheet->setCellValue('E' . $row, (float)$item['unit_price']);
    $sheet->setCellValueExplicit('F' . $row, date('M d, Y', strtotime($item['date_entered'])), \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
    if ($itemType === 'detailed') {
        $sheet->setCellValue('G' . $row, $item['serial_number'] ?? 'N/A');
        $sheet->setCellValue('H' . $row, $item['technical_specs'] ?? 'N/A');
        $sheet->setCellValue('I' . $row, $item['condition_status'] ?? 'N/A');
    }
    $row++;
}


if (empty($items)) {
    $sheet->setCellValue('A' . $row, 'No items found.');
    $sheet->mergeCells('A' . $row . ':' . chr(64 + count($header)) . $row);
}


$sheet->getStyle('E' . ($headerRow + 1) . ':E' . max($row - 1, $headerRow + 1))
    ->getNumberFormat()->setFormatCode('#,##0.00');


foreach (range('A', chr(64 + count($header))) as $col) {
    $sheet->getColumnDimension($col)->setAutoSize(true);
}


$filename = 'Branch_' . str_replace(' ', '_', $branchName) . '_Inventory_' . date('Ymd') . '.xlsx';

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();
