<?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__ . '/../../config/database.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../classes/Request.php';

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

$branch = new Branch($conn);
$auth = new Auth($conn);
$Request = new Request($conn);

if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}


$RequestId = isset($_GET['request_id']) ? (int)$_GET['request_id'] : ($_SESSION['request_data']['request_id'] ?? null);
if (!$RequestId) {
    header('Location: create_request.php?error=' . urlencode('No Request data found.'));
    exit();
}

$RequestData = $Request->getRequestById($RequestId);
if (!$RequestData) {
    header('Location: create_request.php?error=' . urlencode('Request not found.'));
    exit();
}


$creatorId = $RequestData['created_by'] ?? null;
$creatorName = 'Unknown';
if ($creatorId) {
    $creatorName = $auth->getUserName($creatorId);
    if (!$creatorName) {
        error_log("Failed to retrieve username for user_id: $creatorId in Request ID: $RequestId");
        $creatorName = 'Unknown';
    }
} else {
    error_log("No created_by field found for Request ID: $RequestId");
}

$dateTime = new DateTime($RequestData['created_at']);
$formattedDate = $dateTime->format('d M Y');
$formattedTime = $dateTime->format('H:i');

$documentBranch = $branch->getBranchById((int)($RequestData['branch_id'] ?? 0));
$companyDetails = Branding::documentDetailsForBranch($documentBranch);
$companyLogo = $companyDetails['logo'];
$items = is_array($RequestData['items'] ?? null) ? $RequestData['items'] : [];
$totalQuantity = array_sum(array_map(static fn($item) => (int)($item['quantity'] ?? 0), $items));
$requestStatus = ucfirst(str_replace('_', ' ', (string)($RequestData['status'] ?? 'pending')));
$contactLine = Branding::contactLine($companyDetails);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars(Branding::pageTitle('Request Receipt')); ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        :root { --ink:#172033; --muted:#667085; --line:#dfe3ea; --soft:#f5f7fa; --brand:#1f4b7a; --accent:#e9f2fb; }
        * { box-sizing:border-box; }
        body { margin:0; background:#edf1f5; color:var(--ink); font-family:Inter,Segoe UI,Arial,sans-serif; -webkit-font-smoothing:antialiased; }
        .page-shell { max-width:1040px; margin:0 auto; padding:32px 20px 48px; }
        .action-bar { display:flex; align-items:center; justify-content:space-between; gap:16px; margin-bottom:18px; }
        .action-title { font-size:.84rem; color:var(--muted); }
        .action-title strong { display:block; color:var(--ink); font-size:1rem; }
        .action-buttons { display:flex; flex-wrap:wrap; gap:9px; }
        .action-buttons .btn { border-radius:8px; padding:9px 15px; font-size:.84rem; font-weight:600; }
        .document { position:relative; overflow:hidden; background:#fff; border:1px solid #d7dde5; border-radius:14px; box-shadow:0 18px 50px rgba(23,32,51,.10); }
        .document::before { content:''; display:block; height:7px; background:linear-gradient(90deg,var(--brand),#3d7eb8); }
        .document-inner { padding:42px 46px 36px; }
        .doc-header { display:grid; grid-template-columns:minmax(0,1fr) auto; gap:32px; align-items:start; padding-bottom:28px; border-bottom:1px solid var(--line); }
        .brand-block { display:flex; align-items:flex-start; gap:18px; }
        .company-logo { width:82px; height:70px; object-fit:contain; object-position:left top; }
        .company-name { margin:0 0 5px; font-size:1.35rem; line-height:1.2; font-weight:800; letter-spacing:-.02em; color:var(--ink); }
        .company-contact { max-width:520px; color:var(--muted); font-size:.78rem; line-height:1.65; }
        .doc-identity { min-width:250px; text-align:right; }
        .doc-type { color:var(--brand); font-size:.72rem; font-weight:800; letter-spacing:.16em; text-transform:uppercase; }
        .doc-number { margin:5px 0 9px; font-size:1.75rem; line-height:1; font-weight:800; letter-spacing:-.04em; }
        .status-pill { display:inline-flex; align-items:center; gap:6px; padding:6px 10px; border:1px solid #b9d3ec; border-radius:999px; background:var(--accent); color:var(--brand); font-size:.7rem; font-weight:800; text-transform:uppercase; letter-spacing:.05em; }
        .status-pill::before { content:''; width:6px; height:6px; border-radius:50%; background:#2f75b5; }
        .meta-grid { display:grid; grid-template-columns:repeat(4,1fr); gap:0; margin:28px 0; border:1px solid var(--line); border-radius:10px; overflow:hidden; }
        .meta-item { min-height:76px; padding:15px 17px; background:#fff; border-right:1px solid var(--line); }
        .meta-item:last-child { border-right:0; }
        .meta-label { margin-bottom:5px; color:var(--muted); font-size:.66rem; font-weight:800; letter-spacing:.08em; text-transform:uppercase; }
        .meta-value { font-size:.88rem; font-weight:700; overflow-wrap:anywhere; }
        .section-heading { display:flex; align-items:end; justify-content:space-between; gap:12px; margin:0 0 10px; }
        .section-heading h2 { margin:0; font-size:.86rem; font-weight:800; letter-spacing:.04em; text-transform:uppercase; }
        .section-count { color:var(--muted); font-size:.74rem; }
        .items-table { width:100%; margin:0; border-collapse:collapse; }
        .items-table thead th { padding:11px 14px; border:0; background:var(--ink); color:#fff; font-size:.68rem; font-weight:800; letter-spacing:.07em; text-transform:uppercase; }
        .items-table thead th:first-child { border-radius:8px 0 0 0; }
        .items-table thead th:last-child { border-radius:0 8px 0 0; }
        .items-table tbody td { padding:13px 14px; border:0; border-bottom:1px solid var(--line); color:#344054; font-size:.84rem; }
        .items-table tbody tr:nth-child(even) td { background:#fafbfc; }
        .items-table .col-index { width:58px; text-align:center; color:var(--muted); }
        .items-table .col-qty { width:130px; text-align:right; font-weight:800; }
        .items-table tfoot td { padding:13px 14px; border-top:2px solid var(--ink); font-size:.82rem; font-weight:800; }
        .items-table tfoot td:last-child { text-align:right; }
        .notes-grid { display:grid; grid-template-columns:minmax(0,1fr) 270px; gap:20px; margin-top:28px; }
        .notes-card,.approval-card { min-height:120px; padding:18px; border:1px solid var(--line); border-radius:10px; }
        .notes-card { background:var(--soft); }
        .card-label { margin-bottom:9px; color:var(--muted); font-size:.66rem; font-weight:800; letter-spacing:.08em; text-transform:uppercase; }
        .notes-card p { margin:0; color:#475467; font-size:.82rem; line-height:1.65; white-space:pre-line; }
        .signature-line { margin-top:45px; padding-top:7px; border-top:1px solid #98a2b3; color:var(--muted); font-size:.7rem; text-align:center; }
        .doc-footer { display:flex; justify-content:space-between; gap:20px; margin-top:30px; padding-top:16px; border-top:1px solid var(--line); color:var(--muted); font-size:.68rem; }
        @media (max-width:760px) { .document-inner{padding:28px 22px}.doc-header{grid-template-columns:1fr}.doc-identity{text-align:left}.meta-grid{grid-template-columns:1fr 1fr}.meta-item:nth-child(2){border-right:0}.meta-item:nth-child(-n+2){border-bottom:1px solid var(--line)}.notes-grid{grid-template-columns:1fr}.action-bar{align-items:flex-start;flex-direction:column} }
        @page { size:A4 portrait; margin:12mm; }
        @media print { body{background:#fff;print-color-adjust:exact;-webkit-print-color-adjust:exact}.no-print{display:none!important}.page-shell{max-width:none;padding:0}.document{border:0;border-radius:0;box-shadow:none}.document-inner{padding:18px 12px 0}.doc-header{padding-bottom:20px}.meta-grid{margin:20px 0}.items-table thead{display:table-header-group}.items-table tr{break-inside:avoid}.doc-footer{margin-top:22px} }
    </style>
    <link href="/IMS/assets/css/responsive.css" rel="stylesheet">
</head>
<body>
    <div class="page-shell">
        <div class="action-bar no-print">
            <div class="action-title"><strong>Inventory Request</strong>Review, print, or create another request.</div>
            <div class="action-buttons">
                <a href="list_request.php?branch_id=<?php echo (int)$RequestData['branch_id']; ?>" class="btn btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Back to Requests</a>
                <button type="button" class="btn btn-primary" onclick="window.print()"><i class="fas fa-print me-1"></i> Print Request</button>
                <?php if ((int)$RequestData['branch_id'] === (int)$auth->getUserBranch($_SESSION['user_id'])): ?>
                    <a href="request.php" class="btn btn-dark"><i class="fas fa-plus me-1"></i> New Request</a>
                <?php endif; ?>
            </div>
        </div>

        <article class="document">
            <div class="document-inner">
                <header class="doc-header">
                    <div class="brand-block">
                        <?php if (!empty($companyLogo)): ?><img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="<?php echo htmlspecialchars($companyName); ?>" class="company-logo"><?php endif; ?>
                        <div>
                            <h1 class="company-name"><?php echo htmlspecialchars($companyDetails['name']); ?></h1>
                            <?php if ($contactLine !== ''): ?><div class="company-contact"><?php echo htmlspecialchars($contactLine); ?></div><?php endif; ?>
                        </div>
                    </div>
                    <div class="doc-identity">
                        <div class="doc-type">Inventory Request</div>
                        <div class="doc-number"><?php echo htmlspecialchars($RequestData['request_number'] ?? 'N/A'); ?></div>
                        <span class="status-pill"><?php echo htmlspecialchars($requestStatus); ?></span>
                    </div>
                </header>

                <section class="meta-grid" aria-label="Request details">
                    <div class="meta-item"><div class="meta-label">Request Date</div><div class="meta-value"><?php echo htmlspecialchars($formattedDate); ?></div></div>
                    <div class="meta-item"><div class="meta-label">Time Created</div><div class="meta-value"><?php echo htmlspecialchars($formattedTime); ?></div></div>
                    <div class="meta-item"><div class="meta-label">Prepared By</div><div class="meta-value"><?php echo htmlspecialchars($creatorName); ?></div></div>
                    <div class="meta-item"><div class="meta-label">Requesting Branch</div><div class="meta-value"><?php echo htmlspecialchars($documentBranch['branch_name'] ?? 'N/A'); ?></div></div>
                </section>

                <section>
                    <div class="section-heading">
                        <h2>Requested Items</h2>
                        <div class="section-count"><?php echo count($items); ?> line item<?php echo count($items) === 1 ? '' : 's'; ?></div>
                    </div>
                    <table class="items-table">
                        <thead><tr><th class="col-index">#</th><th>Item Description</th><th class="col-qty">Quantity</th></tr></thead>
                        <tbody>
                            <?php if (!$items): ?>
                                <tr><td class="col-index">—</td><td>No requested items were recorded.</td><td class="col-qty">0</td></tr>
                            <?php else: foreach ($items as $index => $item): ?>
                                <tr><td class="col-index"><?php echo $index + 1; ?></td><td><?php echo htmlspecialchars($item['item_name'] ?? 'Unnamed item'); ?></td><td class="col-qty"><?php echo number_format((int)($item['quantity'] ?? 0)); ?></td></tr>
                            <?php endforeach; endif; ?>
                        </tbody>
                        <tfoot><tr><td colspan="2">Total Units Requested</td><td><?php echo number_format($totalQuantity); ?></td></tr></tfoot>
                    </table>
                </section>

                <section class="notes-grid">
                    <div class="notes-card"><div class="card-label">Request Notes</div><p><?php echo htmlspecialchars(trim((string)($RequestData['notes'] ?? '')) ?: 'No additional notes were provided.'); ?></p></div>
                    <div class="approval-card"><div class="card-label">Authorisation</div><div class="signature-line">Authorised signature and date</div></div>
                </section>

                <footer class="doc-footer"><span>Internal inventory request &bull; <?php echo htmlspecialchars($companyDetails['name']); ?></span><span>Document ID: REQ-<?php echo (int)$RequestId; ?></span></footer>
            </div>
        </article>
    </div>
</body>
</html>
