<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Inventory.php';
require_once __DIR__ . '/../../classes/Branding.php';
$conn = (new 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(); }
$branchIdRaw = filter_input(INPUT_GET, 'branch_id', FILTER_SANITIZE_NUMBER_INT);
$itemType = $_GET['item_type'] ?? '';
$searchTerm = trim($_GET['search_term'] ?? '');
if ($branchIdRaw === null || $branchIdRaw === false || !in_array($itemType, ['simple', 'detailed'], true)) {
    http_response_code(400); exit('Invalid report parameters.');
}
$branchId = (int)$branchIdRaw;
if ($branchId === 0) {
    $branchName = 'All Branches'; $branch = [];
} else {
    $stmt = $conn->prepare('SELECT * FROM branches WHERE branch_id = ?');
    $stmt->execute([$branchId]);
    $branch = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$branch) { http_response_code(404); exit('Branch not found.'); }
    $branchName = $branch['branch_name'];
}
$inventory = new Inventory($conn);
$filterBranchId = $branchId === 0 ? null : $branchId;
$search = $searchTerm !== '' ? $searchTerm : null;
$items = $itemType === 'simple' ? $inventory->getSimpleItems($filterBranchId, $search) : $inventory->getDetailedItems($filterBranchId, $search);
$branchLocations = [];
$locationStmt = $conn->query('SELECT branch_id, branch_name FROM branches');
foreach ($locationStmt->fetchAll(PDO::FETCH_ASSOC) as $location) {
    $branchLocations[(int)$location['branch_id']] = (string)$location['branch_name'];
}
$itemsByBranch = [];
foreach ($items as $item) {
    $locationId = (int)($item['current_location_id'] ?? 0);
    $groupKey = $locationId > 0 ? (string)$locationId : 'unassigned';
    if (!isset($itemsByBranch[$groupKey])) {
        $itemsByBranch[$groupKey] = [
            'name' => $locationId > 0 ? ($branchLocations[$locationId] ?? 'Unknown Branch') : 'Unassigned / In Transit',
            'items' => [],
            'value' => 0.0,
            'unassigned' => $locationId <= 0,
        ];
    }
    $itemsByBranch[$groupKey]['items'][] = $item;
    $itemsByBranch[$groupKey]['value'] += (float)($item['unit_price'] ?? 0);
}
uasort($itemsByBranch, static function (array $left, array $right): int {
    if ($left['unassigned'] !== $right['unassigned']) {
        return $left['unassigned'] ? 1 : -1;
    }
    return strnatcasecmp($left['name'], $right['name']);
});
$totalValue = array_sum(array_map(static fn($item) => (float)($item['unit_price'] ?? 0), $items));
$company = Branding::documentDetailsForBranch($branch);
$contactLine = Branding::contactLine($company);
function re($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
function rd($value): string { return (!$value || strtotime($value) === false) ? 'N/A' : date('M d, Y', strtotime($value)); }
function itemBranchLocation(array $item, array $branchLocations): string {
    $locationId = (int)($item['current_location_id'] ?? 0);
    if ($locationId <= 0) {
        return 'Unassigned / In Transit';
    }
    return $branchLocations[$locationId] ?? 'Unknown Branch';
}
?>
<!doctype html><html lang=en><head><meta charset=utf-8><meta name=viewport content=width=device-width,initial-scale=1>
<title><?php echo re($branchName); ?> Inventory Report</title><style>
@page{size:landscape;margin:12mm}*{box-sizing:border-box}body{margin:0;color:#1f2937;background:#fff;font:12px/1.4 Arial,sans-serif}.toolbar{display:flex;justify-content:flex-end;margin:0 auto 16px;max-width:1400px;padding:12px;background:#f3f4f6}.toolbar button{border:0;border-radius:5px;padding:9px 16px;color:#fff;background:#198754;font-weight:700}.report{max-width:1400px;margin:auto}.head{display:grid;grid-template-columns:90px 1fr 260px;align-items:center;gap:18px;padding-bottom:14px;border-bottom:3px solid #243447}.logo{max-width:85px;max-height:65px}h1,h2,p{margin:0}h1{font-size:22px}h2{color:#4b5563;font-size:16px}.meta{text-align:right}.summary{display:flex;gap:24px;margin:14px 0;padding:10px;background:#f3f6f9;border:1px solid #d1d5db}table{width:100%;border-collapse:collapse;table-layout:fixed}thead{display:table-header-group}tr{break-inside:avoid}th,td{padding:6px;border:1px solid #aeb6bf;text-align:left;vertical-align:top;overflow-wrap:anywhere}th{color:#fff;background:#243447}tbody tr:nth-child(even){background:#f7f8fa}.branch-group{break-after:avoid}.branch-group td{padding:8px;color:#fff;background:#4b6478!important;font-size:13px}.branch-total{float:right;font-weight:400}.num{text-align:right;white-space:nowrap}.foot{margin-top:10px;color:#6b7280;text-align:right}@media print{.no-print{display:none!important}body{print-color-adjust:exact;-webkit-print-color-adjust:exact}.report{max-width:none}}
</style></head><body>
<div class='toolbar no-print'><button type='button' onclick='window.print()'>Print Report</button></div>
<main class='report'>
<header class='head'><div><?php if (!empty($company['logo'])): ?><img class='logo' src='<?php echo re($company['logo']); ?>' alt=''><?php endif; ?></div>
<div><h1><?php echo re($company['name']); ?></h1><h2>Branch Inventory Report</h2><?php if ($contactLine !== ''): ?><p><?php echo re($contactLine); ?></p><?php endif; ?></div>
<div class='meta'><p><strong>Branch:</strong> <?php echo re($branchName); ?></p><p><strong>Item type:</strong> <?php echo re(ucfirst($itemType)); ?></p><p><strong>Generated:</strong> <?php echo date('M d, Y H:i'); ?></p><?php if ($searchTerm !== ''): ?><p><strong>Filter:</strong> <?php echo re($searchTerm); ?></p><?php endif; ?></div></header>
<section class='summary'><div><strong>Total items:</strong> <?php echo number_format(count($items)); ?></div><div><strong>Total value:</strong> MWK <?php echo number_format($totalValue, 2); ?></div></section>
<table><thead><tr><th>Unique ID</th><th>Item Name</th><th>Item Details</th><th>Branch Location</th><th>Category</th><th>Unit Price</th><th>Date Entered</th><?php if ($itemType === 'detailed'): ?><th>Serial Number</th><th>Technical Specs</th><th>Condition</th><?php endif; ?></tr></thead><tbody>
<?php $columnCount = $itemType === 'detailed' ? 10 : 7; ?>
<?php if (!$items): ?><tr><td colspan='<?php echo $columnCount; ?>'>No inventory items found.</td></tr><?php else: foreach ($itemsByBranch as $branchGroup): ?>
<tr class='branch-group'><td colspan='<?php echo $columnCount; ?>'><strong><?php echo re($branchGroup['name']); ?></strong><span class='branch-total'><?php echo number_format(count($branchGroup['items'])); ?> item(s) &middot; MWK <?php echo number_format($branchGroup['value'], 2); ?></span></td></tr>
<?php foreach ($branchGroup['items'] as $item): ?>
<tr><td><?php echo re($item['unique_id'] ?? 'N/A'); ?></td><td><?php echo re($item['item_name'] ?? 'N/A'); ?></td><td><?php echo re($item['item_details'] ?? 'N/A'); ?></td><td><?php echo re(itemBranchLocation($item, $branchLocations)); ?></td><td><?php echo re($item['category'] ?? 'N/A'); ?></td><td class='num'>MWK <?php echo number_format((float)($item['unit_price'] ?? 0), 2); ?></td><td><?php echo rd($item['date_entered'] ?? null); ?></td><?php if ($itemType === 'detailed'): ?><td><?php echo re($item['serial_number'] ?? 'N/A'); ?></td><td><?php echo re($item['technical_specs'] ?? 'N/A'); ?></td><td><?php echo re($item['condition_status'] ?? 'N/A'); ?></td><?php endif; ?></tr>
<?php endforeach; endforeach; endif; ?></tbody></table>
<footer class='foot'>Printed by <?php echo re($_SESSION['username']); ?></footer></main>
<script>addEventListener('load',()=>setTimeout(()=>print(),250));</script></body></html>
