<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();
$companyLogo = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();
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';



$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.');
}
$stmtBranchContact = $conn->prepare("SELECT * FROM branches WHERE branch_id = ?");
$stmtBranchContact->execute([$branchId]);
$branchContact = $stmtBranchContact->fetch(PDO::FETCH_ASSOC) ?: [];
$branchContact = array_merge(['branch_address' => '', 'branch_phone' => '', 'branch_email' => '', 'branch_website' => '', 'branch_logo' => ''], $branchContact);
$branchBranding = Branding::documentDetailsForBranch($branchContact);
$companyName = $branchBranding['name'];
$companyLogo = $branchBranding['logo'];
$companyLogoFile = $branchBranding['logo_file'];


$inventory = new Inventory($conn);
$items = [];
$items = $inventory->getDetailedMissingItems($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'];
    }
}




$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);


$pdf->SetCreator($companyName);
$pdf->SetAuthor($_SESSION['username']);
$pdf->SetTitle($branchName . ' Inventory Report');
$pdf->SetSubject('Missing Inventory Report for ' . $branchName);
$pdf->SetKeywords('inventory, branch, report, ' . $companyName);


$pdf->SetHeaderData(is_file($companyLogoFile) ? $companyLogoFile : '', 18, $companyName, "Inventory Missing Report\n" . $branchName . "\nGenerated on: " . date('M d, Y'));


$pdf->setHeaderFont([PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN]);
$pdf->setFooterFont([PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA]);


$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);


$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);


$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);


$pdf->SetFont('helvetica', '', 10);


$pdf->AddPage();


$companyDetails = <<<EOD
$companyName
{$branchContact['branch_address']}
{$branchContact['branch_phone']}
Email: {$branchContact['branch_email']} / Web: {$branchContact['branch_website']}
EOD;
$pdf->MultiCell(0, 10, $companyDetails, 0, 'C', 0, 1, '', '', true);
$pdf->Ln(5);


$reportDetails = <<<EOD
<b>Inventory Report - Missing items </b>
<b>Branch:</b> $branchName
<b>Item Type:</b> $itemType
EOD;
if (!empty($searchTerm)) {
    $reportDetails .= "\n<b>Search:</b> \"$searchTerm\" (by $searchField)";
}
$pdf->writeHTML($reportDetails, true, false, true, false, '');
$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->writeHTML($summaryHtml, true, false, true, false, '');
$pdf->Ln(10);




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


$html = '<table border="1" cellpadding="4">';
$html .= '<tr style="background-color:#f8f9fa;color:#2c3e50;font-weight:bold;">';
foreach ($header as $col) {
    $html .= "<th>$col</th>";
}
$html .= '</tr>';


if (empty($items)) {
    $colspan = count($header);
    $html .= '<tr><td colspan="' . $colspan . '" style="text-align:center;">No items found.</td></tr>';
} else {
    foreach ($items as $item) {
        $html .= '<tr>';
        $html .= '<td>' . htmlspecialchars($item['unique_id']) . '</td>';
        $html .= '<td>' . htmlspecialchars($item['item_name']) . '</td>';
        $html .= '<td>' . htmlspecialchars($item['item_details'] ?? 'N/A') . '</td>';
        $html .= '<td>MWK ' . number_format($item['unit_price'], 2) . '</td>';
        $html .= '<td>' . date('M d, Y', strtotime($item['date_entered'])) . '</td>';
        if ($itemType === 'detailed') {
            $html .= '<td>' . htmlspecialchars($item['serial_number'] ?? 'N/A') . '</td>';
            $html .= '<td>' . htmlspecialchars($item['technical_specs'] ?? 'N/A') . '</td>';
            $html .= '<td>' . htmlspecialchars($item['condition_status'] ?? 'N/A') . '</td>';
        }
        $html .= '</tr>';
    }
}
$html .= '</table>';


$pdf->writeHTML($html, true, false, true, false, '');


$filename = 'Branch_' . str_replace(' ', '_', $branchName) . '_Inventory_' . date('Ymd') . '.pdf';
$pdf->Output($filename, 'D');
exit();
?>
