<?php
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/Mailer.php';
requireLogin();

$id = (int)($_GET['id'] ?? 0);

// ── Load delivery note ──────────────────────────────────────────
$stmt = $pdo->prepare("SELECT d.*, c.customer_name, c.email, c.phone,
                        c.shipping_address, c.billing_address, c.city, c.state, c.pincode,
                        q.quotation_no, q.grand_total, q.id as q_id
                        FROM delivery_notes d
                        JOIN sale_vendors c ON c.id=d.customer_id
                        JOIN quotations q ON q.id=d.quotation_id
                        WHERE d.id=?");
$stmt->execute([$id]);
$d = $stmt->fetch();

if (!$d) {
    setFlash('danger', 'Delivery note not found.');
    header('Location: delivery_notes.php'); exit;
}

// ── Send email action ───────────────────────────────────────────
if (($_GET['action'] ?? '') === 'send_email') {
    if (empty($d['email'])) {
        setFlash('danger', 'Customer has no email address. Use Download button to share via WhatsApp.');
    } else {
        $result = Mailer::sendDeliveryNote($id);
        setFlash($result['success'] ? 'success' : 'danger',
            $result['success'] ? 'Delivery note emailed to ' . $d['email'] : 'Email failed: ' . $result['error']);
    }
    header("Location: delivery_view.php?id=$id"); exit;
}

// ── Mark "Sent to Customer" checkbox ───────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'mark_sent_to_customer') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger', 'Invalid request.'); header("Location: delivery_view.php?id=$id"); exit;
    }
    $pdo->prepare("UPDATE delivery_notes SET sent_to_customer=1, sent_to_customer_at=NOW() WHERE id=?")->execute([$id]);
    setFlash('success', 'Marked as sent to customer.');
    header("Location: delivery_view.php?id=$id"); exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'unmark_sent_to_customer') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger', 'Invalid request.'); header("Location: delivery_view.php?id=$id"); exit;
    }
    $pdo->prepare("UPDATE delivery_notes SET sent_to_customer=0, sent_to_customer_at=NULL WHERE id=?")->execute([$id]);
    header("Location: delivery_view.php?id=$id"); exit;
}

// ── "Delivery Done" submit: record delivery details + auto-generate tax invoice ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delivery_done') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger', 'Invalid request.'); header("Location: delivery_view.php?id=$id"); exit;
    }

    $deliveredDatetime = trim($_POST['delivered_datetime'] ?? '');
    $deliveryLocation  = trim($_POST['delivery_location'] ?? '');
    $deliveryNotes     = trim($_POST['delivery_notes'] ?? '');

    if (empty($deliveredDatetime)) {
        setFlash('danger', 'Please enter the delivery date and time.');
        header("Location: delivery_view.php?id=$id"); exit;
    }

    try {
        $pdo->beginTransaction();

        // 1. Mark delivery note as delivered
        $pdo->prepare("UPDATE delivery_notes SET
                        status='delivered',
                        delivered_at=NOW(),
                        delivered_datetime=?,
                        delivery_location=?,
                        notes=COALESCE(NULLIF(?, ''), notes)
                        WHERE id=?")
            ->execute([$deliveredDatetime, $deliveryLocation, $deliveryNotes, $id]);

        // 2. Auto-generate Tax Invoice from this delivery note
        $existingInv = $pdo->prepare("SELECT id FROM invoices WHERE delivery_note_id=?");
        $existingInv->execute([$id]);
        $existingInvoice = $existingInv->fetch();

        if (!$existingInvoice) {
            // Load quotation items to build invoice lines
            $qItems = $pdo->prepare("SELECT qi.*, i.item_name, i.item_code, i.hsn_code, i.unit
                                     FROM quotation_items qi JOIN items i ON i.id=qi.item_id
                                     WHERE qi.quotation_id=?");
            $qItems->execute([$d['q_id']]);
            $quotationItems = $qItems->fetchAll();

            // Delivery note items (to get qty per item for this delivery)
            $dnItems = $pdo->prepare("SELECT * FROM delivery_note_items WHERE delivery_note_id=?");
            $dnItems->execute([$id]);
            $dnItemMap = [];
            foreach ($dnItems->fetchAll() as $dni) {
                $dnItemMap[$dni['item_id']] = $dni['qty'];
            }

            // Build invoice totals
            $invSubtotal = 0; $invCgst = 0; $invSgst = 0;
            $invoiceLines = [];
            foreach ($quotationItems as $qi) {
                $qty = $dnItemMap[$qi['item_id']] ?? $qi['qty'];
                $ratio = $qi['line_total_before_discount'] > 0
                    ? $qi['line_final_amount'] / $qi['line_total_before_discount'] : 1;
                $lineBase = round($qi['line_subtotal'] * $ratio, 2);
                $lineCgst = round($qi['line_cgst'] * $ratio, 2);
                $lineSgst = round($qi['line_sgst'] * $ratio, 2);
                $lineTotal = $lineBase + $lineCgst + $lineSgst;
                $unitPrice = $qty > 0 ? $lineBase / $qty : 0;

                $invSubtotal += $lineBase;
                $invCgst += $lineCgst;
                $invSgst += $lineSgst;
                $invoiceLines[] = [
                    'item_id'      => $qi['item_id'],
                    'item_name'    => $qi['item_name'],
                    'hsn_code'     => $qi['hsn_code'],
                    'unit'         => $qi['unit'],
                    'qty'          => $qty,
                    'unit_price'   => $unitPrice,
                    'cgst_percent' => $qi['cgst_percent'],
                    'sgst_percent' => $qi['sgst_percent'],
                    'cgst_amount'  => $lineCgst,
                    'sgst_amount'  => $lineSgst,
                    'subtotal'     => $lineBase,
                    'line_total'   => $lineTotal,
                ];
            }
            $grandTotal = $invSubtotal + $invCgst + $invSgst;

            // Generate invoice number
            $prefix = getSetting('invoice_prefix', 'INV');
            $month  = date('Ym');
            $lastNo = $pdo->query("SELECT MAX(CAST(SUBSTRING_INDEX(invoice_no, '-', -1) AS UNSIGNED)) FROM invoices")->fetchColumn() ?: 0;
            $invoiceNo = $prefix . '-' . $month . '-' . str_pad($lastNo + 1, 4, '0', STR_PAD_LEFT);

            // Insert invoice - include quotation_id for proper linking
            $pdo->prepare("INSERT INTO invoices
                (invoice_no, invoice_type, customer_id, quotation_id, delivery_note_id,
                 invoice_date, subtotal, cgst_amount, sgst_amount, grand_total,
                 payment_status, created_by)
                VALUES (?,?,?,?,?,?,?,?,?,?,?,?)")
                ->execute([
                    $invoiceNo, 'sale', $d['customer_id'], $d['quotation_id'], $id,
                    date('Y-m-d'),
                    $invSubtotal, $invCgst, $invSgst, $grandTotal,
                    'pending', currentUserId()
                ]);
            $invoiceId = $pdo->lastInsertId();

            // Insert invoice line items using correct schema columns
            // (invoice_items uses description + item_id, joins items table for name/hsn/unit)
            $insLine = $pdo->prepare("INSERT INTO invoice_items
                (invoice_id, item_id, description, qty, unit_price,
                 cgst_percent, line_cgst, sgst_percent, line_sgst,
                 line_subtotal, line_total)
                VALUES (?,?,?,?,?,?,?,?,?,?,?)");
            foreach ($invoiceLines as $line) {
                $insLine->execute([
                    $invoiceId,
                    $line['item_id'],
                    $line['item_name'],        // stored in description column
                    $line['qty'],
                    $line['unit_price'],
                    $line['cgst_percent'],
                    $line['cgst_amount'],      // line_cgst
                    $line['sgst_percent'],
                    $line['sgst_amount'],      // line_sgst
                    $line['subtotal'],         // line_subtotal
                    $line['line_total'],
                ]);
            }
        }

        $pdo->commit();

        // Auto accounting journal: DR Accounts Receivable  CR Sales Revenue
        if (function_exists('createJournalEntry') && isset($invoiceId)) {
            try {
                $arAccId  = $pdo->query("SELECT id FROM accounts WHERE account_code='1100' LIMIT 1")->fetchColumn();
                $revAccId = $pdo->query("SELECT id FROM accounts WHERE account_code='4001' LIMIT 1")->fetchColumn();
                if ($arAccId && $revAccId) {
                    createJournalEntry(date('Y-m-d'), 'sale',
                        "Sale Invoice $invoiceNo — {$d['customer_name']}",
                        [
                            ['account_id' => $arAccId,  'debit'  => $grandTotal, 'credit' => 0,           'narration' => 'Receivable from customer'],
                            ['account_id' => $revAccId, 'debit'  => 0,           'credit' => $grandTotal, 'narration' => "Invoice $invoiceNo"],
                        ],
                        'invoice', $invoiceId, currentUserId()
                    );
                }
            } catch (Exception $e) {
                error_log('Journal failed for invoice: ' . $e->getMessage());
            }
        }

        $finalInvoiceId = $existingInvoice ? $existingInvoice['id'] : $invoiceId;
        setFlash('success', 'Delivery marked as done! Tax Invoice has been auto-generated.');
        header("Location: delivery_view.php?id=$id&invoice_created=$finalInvoiceId"); exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        setFlash('danger', 'Error: ' . $e->getMessage());
        header("Location: delivery_view.php?id=$id"); exit;
    }
}

// ── Reload after any changes ────────────────────────────────────
$stmt = $pdo->prepare("SELECT d.*, c.customer_name, c.email, c.phone,
                        c.shipping_address, c.billing_address, c.city, c.state, c.pincode,
                        q.quotation_no, q.grand_total, q.id as q_id
                        FROM delivery_notes d
                        JOIN sale_vendors c ON c.id=d.customer_id
                        JOIN quotations q ON q.id=d.quotation_id
                        WHERE d.id=?");
$stmt->execute([$id]);
$d = $stmt->fetch();

// ── Line items with GST breakdown ──────────────────────────────
$stmt = $pdo->prepare("SELECT dni.*, i.item_name, i.item_code, i.unit,
                        qi.unit_price, qi.cgst_percent, qi.sgst_percent,
                        qi.line_subtotal, qi.line_cgst, qi.line_sgst,
                        qi.line_total_before_discount, qi.line_discount_amount, qi.line_final_amount
                        FROM delivery_note_items dni
                        JOIN items i ON i.id=dni.item_id
                        LEFT JOIN quotation_items qi ON qi.quotation_id=:qid AND qi.item_id=dni.item_id
                        WHERE dni.delivery_note_id=:did");
$stmt->execute(['qid' => $d['q_id'], 'did' => $id]);
$lineItems = $stmt->fetchAll();

$dnSubtotal = 0; $dnCgst = 0; $dnSgst = 0; $dnTotal = 0;
foreach ($lineItems as $li) {
    $originalTotal = $li['line_total_before_discount'] ?: 0;
    $ratio = $originalTotal > 0 ? $li['line_final_amount'] / $originalTotal : 1;
    $finalBase = round(($li['line_subtotal'] ?? 0) * $ratio, 2);
    $finalCgst = round(($li['line_cgst'] ?? 0) * $ratio, 2);
    $finalSgst = round(($li['line_sgst'] ?? 0) * $ratio, 2);
    $dnSubtotal += $finalBase;
    $dnCgst += $finalCgst;
    $dnSgst += $finalSgst;
    $dnTotal += $finalBase + $finalCgst + $finalSgst;
}

// Check if invoice already exists
$stmt = $pdo->prepare("SELECT * FROM invoices WHERE delivery_note_id=?");
$stmt->execute([$id]);
$invoice = $stmt->fetch();

$companyName    = getSetting('company_name', 'Your Company');
$companyAddress = getSetting('company_address', '');
$companyGst     = getSetting('company_gst', '');
$companyPhone   = getSetting('company_phone', '');

$csrf = generateCSRFToken();
$pageTitle = 'Delivery Note';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header no-print">
    <div>
        <div class="eyebrow">Sales Flow</div>
        <h2 class="mb-0"><?= sanitize($d['delivery_no']) ?></h2>
    </div>
    <div class="flex gap-8" style="flex-wrap:wrap;">
        <a href="delivery_notes.php" class="btn"><?= icon('arrow-left') ?> Back</a>
        <a href="delivery_pdf.php?id=<?= $id ?>" class="btn" target="_blank"><?= icon('download') ?> Download PDF</a>
        <?php if ($d['email']): ?>
        <a href="?id=<?= $id ?>&action=send_email" class="btn btn-primary" onclick="return confirm('Send delivery note to <?= sanitize($d['email']) ?>?')">
            <?= icon('mail-forward') ?> <?= $d['email_sent'] ? 'Re-send Email' : 'Send Email' ?>
        </a>
        <?php endif; ?>
        <?php if ($invoice): ?>
        <a href="../invoice/invoice_view.php?id=<?= $invoice['id'] ?>" class="btn btn-accent"><?= icon('receipt') ?> View Tax Invoice</a>
        <?php endif; ?>
    </div>
</div>

<?php if (isset($_GET['invoice_created'])): ?>
<div class="alert alert-success no-print">
    <?= icon('circle-check') ?> Tax Invoice auto-generated!
    <a href="../invoice/invoice_view.php?id=<?= (int)$_GET['invoice_created'] ?>" class="btn btn-sm btn-success" style="margin-left:12px;"><?= icon('receipt') ?> View & Download Invoice</a>
</div>
<?php endif; ?>

<?php if (!$d['email']): ?>
<div class="alert alert-warning no-print"><?= icon('alert-triangle') ?> No email on file. Use the Download button to share via WhatsApp, then check the box below.</div>
<?php endif; ?>

<?php if ($d['email_sent']): ?>
<div class="alert alert-info no-print"><?= icon('mail') ?> Emailed to <?= sanitize($d['email']) ?> on <?= formatDateTime($d['email_sent_at']) ?></div>
<?php endif; ?>

<!-- ── STEP 1: Sent to Customer ─────────────────────────────── -->
<div class="card no-print" style="max-width:850px; margin:0 auto 12px; border-color:<?= $d['sent_to_customer'] ? 'var(--color-success)' : 'var(--color-border)' ?>;">
    <div class="flex-between" style="flex-wrap:wrap; gap:12px;">
        <form method="POST" id="sentForm">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="action" value="<?= $d['sent_to_customer'] ? 'unmark_sent_to_customer' : 'mark_sent_to_customer' ?>">
            <label class="flex gap-8" style="align-items:center; cursor:pointer; margin:0;">
                <input type="checkbox" <?= $d['sent_to_customer'] ? 'checked' : '' ?>
                    onchange="document.getElementById('sentForm').submit()"
                    <?= $d['status'] === 'delivered' ? 'disabled' : '' ?>
                    style="width:20px;height:20px;">
                <span style="font-weight:600; font-size:15px;">
                    <?= icon('truck-delivery') ?> Delivery Note Sent to Customer
                </span>
            </label>
        </form>
        <?php if ($d['sent_to_customer']): ?>
        <span class="badge badge-success">Confirmed <?= formatDateTime($d['sent_to_customer_at']) ?></span>
        <?php endif; ?>
    </div>
    <?php if (!$d['sent_to_customer']): ?>
    <div class="text-sm text-faint mt-8">Check this once the customer has received the delivery note (via email or WhatsApp download).</div>
    <?php endif; ?>
</div>

<!-- ── STEP 2: Delivery Done Form ───────────────────────────── -->
<?php if ($d['status'] !== 'delivered'): ?>
<div class="card no-print" style="max-width:850px; margin:0 auto 12px; <?= !$d['sent_to_customer'] ? 'opacity:0.5;pointer-events:none;' : 'border-color:var(--color-accent);' ?>">
    <div class="card-title"><?= icon('check') ?> Mark Delivery Done → Auto-Generate Tax Invoice</div>
    <?php if (!$d['sent_to_customer']): ?>
    <div class="text-sm text-faint">Check "Delivery Note Sent to Customer" above first to unlock this step.</div>
    <?php else: ?>
    <form method="POST">
        <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
        <input type="hidden" name="action" value="delivery_done">
        <div class="form-grid">
            <div class="form-group">
                <label>Delivery Date &amp; Time <span class="req">*</span></label>
                <input type="datetime-local" name="delivered_datetime" value="<?= date('Y-m-d\TH:i') ?>" required>
                <div class="text-sm text-faint">Enter the actual date and time goods were delivered.</div>
            </div>
            <div class="form-group">
                <label>Delivery Location</label>
                <input type="text" name="delivery_location" placeholder="e.g. Customer warehouse, Site address, etc.">
            </div>
            <div class="form-group full">
                <label>Additional Delivery Notes</label>
                <input type="text" name="delivery_notes" placeholder="e.g. Received by: John, Condition: Good">
            </div>
        </div>
        <div class="alert alert-info" style="margin-bottom:12px;">
            <?= icon('info-circle') ?> Clicking "Delivery Done" will: mark this delivery as completed, auto-generate the Tax Invoice, and let you download or email the invoice.
        </div>
        <div class="flex-end">
            <button type="submit" class="btn btn-success" onclick="return confirm('Mark delivery as done and generate Tax Invoice?')" style="font-size:15px; padding:10px 24px;">
                <?= icon('circle-check') ?> Delivery Done → Generate Tax Invoice
            </button>
        </div>
    </form>
    <?php endif; ?>
</div>
<?php else: ?>
<!-- ── Delivery already done: show summary + invoice link ─── -->
<div class="card no-print" style="max-width:850px; margin:0 auto 12px; border-color:var(--color-success);">
    <div class="flex-between" style="flex-wrap:wrap; gap:12px;">
        <div>
            <div class="badge badge-success" style="margin-bottom:6px;"><?= icon('circle-check') ?> Delivery Completed</div>
            <div class="text-sm">Delivered on: <strong><?= formatDateTime($d['delivered_datetime'] ?: $d['delivered_at']) ?></strong></div>
            <?php if ($d['delivery_location']): ?>
            <div class="text-sm">Location: <strong><?= sanitize($d['delivery_location']) ?></strong></div>
            <?php endif; ?>
        </div>
        <?php if ($invoice): ?>
        <div>
            <div class="text-sm text-muted" style="margin-bottom:6px;">Tax Invoice generated:</div>
            <a href="../invoice/invoice_view.php?id=<?= $invoice['id'] ?>" class="btn btn-accent"><?= icon('receipt') ?> <?= sanitize($invoice['invoice_no']) ?></a>
        </div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<!-- ── PRINTABLE DELIVERY NOTE DOCUMENT ─────────────────────── -->
<div class="card" style="max-width:850px; margin:0 auto;">
    <div class="flex-between" style="align-items:flex-start; margin-bottom:24px;">
        <div>
            <h1 style="margin-bottom:4px;"><?= sanitize($companyName) ?></h1>
            <div class="text-sm text-muted"><?= nl2br(sanitize($companyAddress)) ?></div>
            <?php if ($companyGst): ?><div class="text-sm text-muted">GSTIN: <?= sanitize($companyGst) ?></div><?php endif; ?>
            <?php if ($companyPhone): ?><div class="text-sm text-muted">Phone: <?= sanitize($companyPhone) ?></div><?php endif; ?>
        </div>
        <div class="text-right">
            <h2 style="margin-bottom:4px;">DELIVERY NOTE</h2>
            <div class="mono"><?= sanitize($d['delivery_no']) ?></div>
            <div class="text-sm text-muted">Date: <?= formatDate($d['delivery_date']) ?></div>
            <div class="text-sm text-muted">Ref: <?= sanitize($d['quotation_no']) ?></div>
            <?php if ($d['status'] === 'delivered' && $d['delivered_datetime']): ?>
            <div class="text-sm text-muted">Delivered: <?= formatDateTime($d['delivered_datetime']) ?></div>
            <?php endif; ?>
        </div>
    </div>

    <div class="divider"></div>

    <div style="margin-bottom:16px;">
        <div class="text-sm text-muted" style="font-weight:700; text-transform:uppercase; letter-spacing:0.5px; margin-bottom:4px;">Deliver To</div>
        <div style="font-weight:600;"><?= sanitize($d['customer_name']) ?></div>
        <div class="text-sm"><?= nl2br(sanitize($d['shipping_address'] ?: $d['billing_address'])) ?></div>
        <div class="text-sm"><?= sanitize($d['city']) ?><?= $d['city']&&$d['state']?', ':'' ?><?= sanitize($d['state']) ?> <?= sanitize($d['pincode']) ?></div>
        <div class="text-sm">Phone: <?= sanitize($d['phone']) ?></div>
        <?php if ($d['delivery_location']): ?>
        <div class="text-sm">Delivery Location: <strong><?= sanitize($d['delivery_location']) ?></strong></div>
        <?php endif; ?>
    </div>

    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th style="width:36px">#</th>
                    <th>Item Description</th>
                    <th class="text-right">Qty</th>
                    <th class="text-right">Rate</th>
                    <th class="text-right">CGST</th>
                    <th class="text-right">SGST</th>
                    <th class="text-right">Amount</th>
                </tr>
            </thead>
            <tbody>
            <?php $sno=1; foreach ($lineItems as $li):
                $originalTotal = $li['line_total_before_discount'] ?: 0;
                $ratio = $originalTotal > 0 ? $li['line_final_amount'] / $originalTotal : 1;
                $finalBase = round(($li['line_subtotal'] ?? 0) * $ratio, 2);
                $finalCgst = round(($li['line_cgst'] ?? 0) * $ratio, 2);
                $finalSgst = round(($li['line_sgst'] ?? 0) * $ratio, 2);
                $lineTotal = $finalBase + $finalCgst + $finalSgst;
                $unitRate  = $li['qty'] > 0 ? $finalBase / $li['qty'] : 0;
            ?>
            <tr>
                <td><?= $sno++ ?></td>
                <td><?= sanitize($li['item_name']) ?> <span class="text-faint mono">(<?= sanitize($li['item_code']) ?>)</span></td>
                <td class="num"><?= $li['qty'] ?></td>
                <td class="num mono"><?= formatMoney($unitRate) ?></td>
                <td class="num mono"><?= formatMoney($finalCgst) ?> <span class="text-faint">(<?= number_format($li['cgst_percent'] ?? 0,1) ?>%)</span></td>
                <td class="num mono"><?= formatMoney($finalSgst) ?> <span class="text-faint">(<?= number_format($li['sgst_percent'] ?? 0,1) ?>%)</span></td>
                <td class="num mono"><strong><?= formatMoney($lineTotal) ?></strong></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <div class="flex-end mt-16">
        <div style="width:280px;">
            <div class="flex-between" style="padding:4px 0;">
                <span class="text-sm text-muted">Subtotal</span>
                <strong class="mono"><?= formatMoney($dnSubtotal) ?></strong>
            </div>
            <div class="flex-between" style="padding:4px 0;">
                <span class="text-sm text-muted">CGST</span>
                <strong class="mono"><?= formatMoney($dnCgst) ?></strong>
            </div>
            <div class="flex-between" style="padding:4px 0;">
                <span class="text-sm text-muted">SGST</span>
                <strong class="mono"><?= formatMoney($dnSgst) ?></strong>
            </div>
            <div class="divider" style="margin:8px 0;"></div>
            <div class="flex-between" style="padding:4px 0;">
                <span style="font-weight:700; font-size:15px;">Total Amount</span>
                <strong class="mono" style="font-size:18px; color:var(--color-primary);"><?= formatMoney($dnTotal) ?></strong>
            </div>
        </div>
    </div>

    <?php if ($d['notes']): ?>
    <div class="divider"></div>
    <div>
        <strong class="text-sm">Delivery Notes:</strong>
        <div class="text-sm text-muted"><?= nl2br(sanitize($d['notes'])) ?></div>
    </div>
    <?php endif; ?>

    <div class="divider"></div>
    <div class="text-sm text-faint">Please verify quantities upon receipt. Tax Invoice will follow separately.</div>
    <div style="margin-top:40px;" class="flex-between">
        <div class="text-sm text-muted">Received by: _________________________</div>
        <div class="text-sm text-muted">Signature: _________________________</div>
    </div>
</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
