<?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';
require_once __DIR__ . '/../../vendor/autoload.php';

function pdfText($value): string {
    return htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function pdfDate($value): string {
    $timestamp = $value ? strtotime((string)$value) : false;
    return $timestamp === false ? 'N/A' : date('d M Y', $timestamp);
}

final class BranchInventoryPdf extends TCPDF {
    private string $companyName = '';
    private string $generatedBy = '';

    public function setReportFooter(string $companyName, string $generatedBy): void {
        $this->companyName = $companyName;
        $this->generatedBy = $generatedBy;
    }

    public function Footer(): void {
        $this->SetY(-12);
        $margins = $this->getMargins();
        $usableWidth = $this->getPageWidth() - $margins['left'] - $margins['right'];
        $this->SetDrawColor(204, 214, 224);
        $this->Line($margins['left'], $this->GetY(), $this->getPageWidth() - $margins['right'], $this->GetY());
        $this->Ln(2);
        $this->SetTextColor(93, 108, 123);
        $this->SetFont('helvetica', '', 7.5);
        $this->Cell($usableWidth * 0.72, 5, $this->companyName . ' | Inventory Control | Prepared by ' . $this->generatedBy, 0, 0, 'L');
        $this->Cell($usableWidth * 0.28, 5, 'Page ' . $this->getAliasNumPage() . ' of ' . $this->getAliasNbPages(), 0, 0, 'R');
    }
}

$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;
if ($branchId === null && isset($_GET['branch_id'])) {
    $branchId = filter_var($_GET['branch_id'], FILTER_SANITIZE_NUMBER_INT);
}
$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.');
}


$branchId = (int)$branchId;
$branch = [];
if ($branchId === 0) {
    $branchName = 'All Branches';
} else {
    $stmtBranch = $conn->prepare('SELECT * FROM branches WHERE branch_id = ?');
    $stmtBranch->execute([$branchId]);
    $branch = $stmtBranch->fetch(PDO::FETCH_ASSOC) ?: [];
    if (!$branch) {
        http_response_code(404);
        exit('Branch not found.');
    }
    $branchName = (string)$branch['branch_name'];
}

$branchLocations = [];
$locationStmt = $conn->query('SELECT branch_id, branch_name FROM branches ORDER BY branch_name');
foreach ($locationStmt->fetchAll(PDO::FETCH_ASSOC) as $location) {
    $branchLocations[(int)$location['branch_id']] = (string)$location['branch_name'];
}

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


$itemsByBranch = [];
$totalValue = 0.0;
foreach ($items as $item) {
    $locationId = (int)($item['current_location_id'] ?? ($branchId > 0 ? $branchId : 0));
    $locationName = $locationId > 0 ? ($branchLocations[$locationId] ?? 'Unknown Branch') : 'Unassigned / In Transit';
    $groupKey = $locationId > 0 ? (string)$locationId : 'unassigned';
    if (!isset($itemsByBranch[$groupKey])) {
        $itemsByBranch[$groupKey] = [
            'name' => $locationName,
            'items' => [],
            'value' => 0.0,
            'unassigned' => $locationId <= 0,
        ];
    }
    $itemValue = (float)($item['unit_price'] ?? 0);
    $itemsByBranch[$groupKey]['items'][] = $item;
    $itemsByBranch[$groupKey]['value'] += $itemValue;
    $totalValue += $itemValue;
}
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']);
});

$totalItems = count($items);
$company = Branding::documentDetailsForBranch($branch);
$companyName = (string)$company['name'];
$companyLogoFile = (string)($company['logo_file'] ?? '');
$generatedBy = (string)($_SESSION['username'] ?? 'System User');
$generatedAt = date('d M Y, H:i');
$reportId = 'INV-' . date('Ymd-His');
$contactParts = array_filter([
    trim((string)($company['address'] ?? '')),
    trim((string)($company['phone'] ?? '')) !== '' ? 'Tel: ' . trim((string)$company['phone']) : '',
    trim((string)($company['email'] ?? '')),
    trim((string)($company['website'] ?? '')),
]);
$contactLine = implode(' | ', $contactParts);




$pdf = new BranchInventoryPdf('L', PDF_UNIT, 'A4', true, 'UTF-8', false);
$pdf->SetCreator($companyName);
$pdf->SetAuthor($generatedBy);
$pdf->SetTitle($branchName . ' Inventory Report');
$pdf->SetSubject('Branch inventory status and valuation');
$pdf->SetKeywords('inventory, branch, stock, valuation, ' . $companyName);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(true);
$pdf->setReportFooter($companyName, $generatedBy);
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins(12, 12, 12);
$pdf->SetFooterMargin(8);
$pdf->SetAutoPageBreak(true, 17);
$pdf->AddPage();


$reportDetails = <<<EOD
<b>Inventory Report</b>
<b>Branch:</b> $branchName
<b>Item Type:</b> $itemType
EOD;
if (!empty($searchTerm)) {
    $reportDetails .= "\n<b>Search:</b> \"$searchTerm\" (by $searchField)";
}
$pdf->Ln(5);



$summaryHtml = '
<table border="1" cellpadding="6" style="background-color:#f0f8ff;">
    <tr>
        <td width="50%" style="font-weight:bold;">Total Number of Items:</td>
        <td width="50%">' . $totalItems . '</td>
    </tr>
    <tr>
        <td width="50%" style="font-weight:bold;">Total Monetary Value:</td>
        <td width="50%">MWK ' . number_format($totalValue, 2) . '</td>
    </tr>
</table>';
$pdf->Ln(10);




$pageWidth = $pdf->getPageWidth();
$pdf->SetFillColor(25, 50, 74);
$pdf->Rect(0, 0, $pageWidth, 34, 'F');

$titleX = 14;
if ($companyLogoFile !== '' && is_file($companyLogoFile)) {
    $pdf->SetFillColor(255, 255, 255);
    $pdf->RoundedRect(12, 7, 24, 20, 2, '1111', 'F');
    $pdf->Image($companyLogoFile, 14, 9, 20, 16, '', '', '', true, 300, '', false, false, 0, 'CM');
    $titleX = 41;
}
$pdf->SetXY($titleX, 8);
$pdf->SetTextColor(255, 255, 255);
$pdf->SetFont('helvetica', 'B', 17);
$pdf->Cell(150, 7, $companyName, 0, 1, 'L');
$pdf->SetX($titleX);
$pdf->SetFont('helvetica', '', 8.5);
$pdf->SetTextColor(213, 225, 236);
$pdf->Cell(190, 5, $contactLine !== '' ? $contactLine : 'Inventory Management System', 0, 0, 'L');
$pdf->SetXY($pageWidth - 78, 8);
$pdf->SetTextColor(255, 255, 255);
$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(64, 6, 'INVENTORY REPORT', 0, 1, 'R');
$pdf->SetX($pageWidth - 78);
$pdf->SetFont('helvetica', '', 8);
$pdf->SetTextColor(213, 225, 236);
$pdf->Cell(64, 5, 'Report ID: ' . $reportId, 0, 1, 'R');
$pdf->SetX($pageWidth - 78);
$pdf->Cell(64, 5, 'Generated: ' . $generatedAt, 0, 1, 'R');

$pdf->SetY(41);
$pdf->SetTextColor(25, 50, 74);
$pdf->SetFont('helvetica', 'B', 15);
$pdf->Cell(170, 7, $branchName . ' Stock Register', 0, 0, 'L');
$pdf->SetFont('helvetica', '', 8.5);
$pdf->SetTextColor(93, 108, 123);
$pdf->Cell(103, 7, 'Classification: ' . ucfirst($itemType) . ' items', 0, 1, 'R');
$pdf->SetDrawColor(35, 139, 125);
$pdf->SetLineWidth(0.7);
$pdf->Line(12, 50, $pageWidth - 12, 50);

if ($searchTerm !== '') {
    $filterLabel = 'Applied filter: ' . ($searchField !== '' ? ucwords(str_replace('_', ' ', $searchField)) . ' contains ' : '') . $searchTerm;
    $pdf->SetY(53);
    $pdf->SetFillColor(239, 246, 250);
    $pdf->SetTextColor(46, 91, 119);
    $pdf->SetFont('helvetica', '', 8.5);
    $pdf->Cell(0, 7, $filterLabel, 0, 1, 'L', true);
    $summaryY = 63;
} else {
    $summaryY = 55;
}

$contentWidth = $pageWidth - 24;
$cardGap = 4;
$cardWidth = ($contentWidth - ($cardGap * 2)) / 3;
$summaryCards = [
    ['TOTAL ITEMS', number_format($totalItems), 'Units currently listed'],
    ['STOCK VALUE', 'MWK ' . number_format($totalValue, 2), 'Combined unit value'],
    ['BRANCH SECTIONS', number_format(count($itemsByBranch)), $branchId === 0 ? 'Locations represented' : 'Selected location'],
];
foreach ($summaryCards as $index => $card) {
    $x = 12 + (($cardWidth + $cardGap) * $index);
    $pdf->SetFillColor(245, 248, 251);
    $pdf->SetDrawColor(216, 225, 233);
    $pdf->RoundedRect($x, $summaryY, $cardWidth, 19, 1.5, '1111', 'DF');
    $pdf->SetXY($x + 4, $summaryY + 3);
    $pdf->SetTextColor(93, 108, 123);
    $pdf->SetFont('helvetica', 'B', 7);
    $pdf->Cell($cardWidth - 8, 4, $card[0], 0, 1, 'L');
    $pdf->SetX($x + 4);
    $pdf->SetTextColor(25, 50, 74);
    $pdf->SetFont('helvetica', 'B', 12);
    $pdf->Cell($cardWidth - 8, 6, $card[1], 0, 1, 'L');
    $pdf->SetX($x + 4);
    $pdf->SetTextColor(112, 126, 140);
    $pdf->SetFont('helvetica', '', 7);
    $pdf->Cell($cardWidth - 8, 4, $card[2], 0, 1, 'L');
}
$pdf->SetY($summaryY + 25);

if (!$items) {
    $pdf->SetFillColor(248, 250, 252);
    $pdf->SetDrawColor(216, 225, 233);
    $pdf->SetTextColor(93, 108, 123);
    $pdf->SetFont('helvetica', '', 10);
    $pdf->Cell(0, 18, 'No inventory items matched the selected report criteria.', 1, 1, 'C', true);
} else {
    $columns = $itemType === 'detailed'
        ? [
            ['Unique ID', 10], ['Item Name', 14], ['Item Details', 16], ['Category', 9], ['Unit Price', 10],
            ['Date Entered', 9], ['Serial Number', 10], ['Technical Specs', 14], ['Condition', 8],
        ]
        : [
            ['Unique ID', 16], ['Item Name', 22], ['Item Details', 27], ['Category', 15], ['Unit Price', 11], ['Date Entered', 9],
        ];

    foreach ($itemsByBranch as $branchGroup) {
        if ($pdf->GetY() > 172) {
            $pdf->AddPage();
            $pdf->SetY(15);
        }
        $pdf->SetFillColor(35, 139, 125);
        $pdf->SetTextColor(255, 255, 255);
        $pdf->SetFont('helvetica', 'B', 10);
        $pdf->Cell($contentWidth * 0.60, 9, $branchGroup['name'], 0, 0, 'L', true);
        $pdf->SetFont('helvetica', '', 8.5);
        $pdf->Cell(
            $contentWidth * 0.40,
            9,
            number_format(count($branchGroup['items'])) . ' item(s) | MWK ' . number_format($branchGroup['value'], 2),
            0,
            1,
            'R',
            true
        );

        $groupHtml = '<table border="1" cellpadding="4" cellspacing="0">';
        $groupHtml .= '<thead><tr style="background-color:#19324a;color:#ffffff;font-weight:bold;">';
        foreach ($columns as [$label, $width]) {
            $alignment = $label === 'Unit Price' ? 'right' : 'left';
            $groupHtml .= '<th width="' . $width . '%" align="' . $alignment . '">' . pdfText($label) . '</th>';
        }
        $groupHtml .= '</tr></thead><tbody>';

        foreach ($branchGroup['items'] as $index => $item) {
            $background = $index % 2 === 0 ? '#ffffff' : '#f4f7fa';
            $groupHtml .= '<tr style="background-color:' . $background . ';color:#263746;">';
            $groupHtml .= '<td width="' . $columns[0][1] . '%">' . pdfText($item['unique_id'] ?? 'N/A') . '</td>';
            $groupHtml .= '<td width="' . $columns[1][1] . '%"><b>' . pdfText($item['item_name'] ?? 'N/A') . '</b></td>';
            $groupHtml .= '<td width="' . $columns[2][1] . '%">' . pdfText($item['item_details'] ?? 'N/A') . '</td>';
            $groupHtml .= '<td width="' . $columns[3][1] . '%">' . pdfText($item['category'] ?? 'N/A') . '</td>';
            $groupHtml .= '<td width="' . $columns[4][1] . '%" align="right">MWK ' . number_format((float)($item['unit_price'] ?? 0), 2) . '</td>';
            $groupHtml .= '<td width="' . $columns[5][1] . '%">' . pdfText(pdfDate($item['date_entered'] ?? null)) . '</td>';
            if ($itemType === 'detailed') {
                $groupHtml .= '<td width="' . $columns[6][1] . '%">' . pdfText($item['serial_number'] ?? 'N/A') . '</td>';
                $groupHtml .= '<td width="' . $columns[7][1] . '%">' . pdfText($item['technical_specs'] ?? 'N/A') . '</td>';
                $groupHtml .= '<td width="' . $columns[8][1] . '%">' . pdfText($item['condition_status'] ?? 'N/A') . '</td>';
            }
            $groupHtml .= '</tr>';
        }
        $groupHtml .= '</tbody></table>';

        $pdf->SetDrawColor(216, 225, 233);
        $pdf->SetFont('helvetica', '', 7.5);
        $pdf->writeHTML($groupHtml, true, false, true, false, '');
        $pdf->Ln(4);
    }
}


$safeBranchName = preg_replace('/[^A-Za-z0-9_-]+/', '_', $branchName);
$filename = 'Inventory_' . trim((string)$safeBranchName, '_') . '_' . date('Ymd') . '.pdf';
$previewFile = PHP_SAPI === 'cli' ? getenv('INVENTORY_PDF_PREVIEW_FILE') : false;
if (is_string($previewFile) && $previewFile !== '') {
    $pdf->Output($previewFile, 'F');
} else {
    $pdf->Output($filename, 'D');
}
exit();
