<?php
include '../../includes/header.php';
require_once __DIR__ . '/../../classes/CreditSales.php';
require_once __DIR__ . '/../../classes/Branding.php';
require_once __DIR__ . '/../../includes/payment_options.php';

$creditSales = new CreditSales($conn);
$credit = $creditSales->getCreditById((int)($_GET['credit_id'] ?? 0));
if (!$credit) { die('Credit sale not found.'); }
$userId = (int)$_SESSION['user_id'];
$role = strtolower((string)($_SESSION['role'] ?? ''));
if (!in_array($role, ['admin','super_admin','controller'], true) && (int)$credit['branch_id'] !== (int)$auth->getUserBranch($userId)) { die('Access denied.'); }

$items    = $creditSales->getCreditItems((int)$credit['credit_id']);
$payments = $creditSales->getPayments((int)$credit['credit_id']);
$paymentId = (int)($_GET['payment_id'] ?? 0);
$currentPayment = null;
foreach ($payments as $p) {
    if ((int)$p['payment_id'] === $paymentId) { $currentPayment = $p; break; }
}
if (!$currentPayment && $paymentId > 0) { die('Credit payment not found.'); }

// ── EIS outbox ────────────────────────────────────────────────
$isFinal          = (float)$credit['balance'] <= 0 || $credit['status'] === 'completed';
$eisOutbox        = $creditSales->getEisOutbox((string)$credit['transaction_id']);
$eisStatus        = $eisOutbox ? (string)($eisOutbox['status'] ?? '') : '';
$eisValidationUrl = trim((string)($eisOutbox['validation_url'] ?? ''));
$eisRef           = trim((string)($eisOutbox['mra_reference'] ?? ''));
$eisSubmittedAt   = $eisOutbox ? (string)($eisOutbox['submitted_at'] ?? '') : '';
$isEisReceipt     = $isFinal && $eisOutbox && $eisStatus === 'submitted' && $eisRef !== '';

// ── Receipt meta ──────────────────────────────────────────────
$receiptTitle  = $currentPayment ? 'Credit Sale Payment Receipt' : ($isFinal ? 'Final Credit Sale Receipt' : 'Credit Sale Statement');
$issuedAt      = $currentPayment ? (string)$currentPayment['payment_date'] : date('Y-m-d H:i:s');
$receiptNo     = $currentPayment ? ('CP-' . (int)$currentPayment['payment_id']) : ('CR-' . (int)$credit['credit_id']);
$totalAmount   = (float)$credit['total_amount'];
$totalPaid     = (float)$credit['amount_paid'];
$balance       = (float)$credit['balance'];
$paymentAmount = $currentPayment ? (float)$currentPayment['amount'] : 0.0;
$paymentMethod = $currentPayment ? paymentMethodLabel($currentPayment['payment_method']) : '-';
$recordedBy    = $currentPayment ? ($currentPayment['recorded_by_name'] ?? '-') : '-';
$companyLabel  = isset($companyName) && trim((string)$companyName) !== '' ? $companyName : Branding::companyName();

// ── Branding / contact details ────────────────────────────────
$companyLogo = Branding::logoUrl();
$settings    = Branding::settings();
$serviceBody = trim((string)($settings['service_body'] ?? ''));

$branchStmt = $conn->prepare("SELECT * FROM branches WHERE branch_id = ?");
$branchStmt->execute([(int)$credit['branch_id']]);
$branchRow     = $branchStmt->fetch(PDO::FETCH_ASSOC) ?: [];
$branchBranding = Branding::documentDetailsForBranch($branchRow);
$companyLabel = $branchBranding['name'];
$companyLogo  = $branchBranding['logo'];
$branchLabel   = $branchRow['branch_name']    ?? ($credit['branch_name'] ?? (string)$credit['branch_id']);
$branchAddress = trim((string)($branchRow['branch_address'] ?? ''));
$branchPhone   = trim((string)($branchRow['branch_phone']   ?? ''));
$branchEmail   = trim((string)($branchRow['branch_email']   ?? ''));
$branchWebsite = trim((string)($branchRow['branch_website'] ?? ''));
?>
<style id="crPrintPageSize">@page { size: 80mm auto; margin: 0; }</style>
<style>
/* ── Shell ── */
.cr-page { background:#F3F4F6; min-height:100vh; padding-bottom:24px; }
.cr-wrap  { max-width:980px; margin:0 auto; }
.cr-toolbar { display:flex; justify-content:space-between; gap:10px; align-items:center; flex-wrap:wrap; }
.cr-stage { display:flex; justify-content:center; }

/* ── Format visibility ── */
.cr-doc { display:none; background:#fff; color:#111827; box-shadow:0 8px 28px rgba(15,23,42,.12); }
body.cr-fmt-a5 .cr-formal, body.cr-fmt-a4 .cr-formal { display:block; }
body.cr-fmt-th80 .cr-thermal, body.cr-fmt-th58 .cr-thermal { display:block; }

/* ── Formal receipt ── */
.cr-formal { width:148mm; min-height:210mm; padding:12mm; font-size:11px; }
body.cr-fmt-a4 .cr-formal { width:210mm; min-height:297mm; }

/* Header */
.f-head { display:flex; justify-content:space-between; gap:10px; border-bottom:2px solid #111827; padding-bottom:10px; margin-bottom:6px; }
.f-head-left { display:flex; gap:10px; align-items:flex-start; flex:1; }
.f-logo { height:52px; width:auto; max-width:80px; object-fit:contain; }
.f-logo-placeholder { height:52px; width:52px; background:#1E40AF; border-radius:4px; display:flex; align-items:center; justify-content:center; }
.f-logo-placeholder span { color:#fff; font-weight:900; font-size:16px; }
.f-company { flex:1; }
.f-company-name { font-size:15px; font-weight:900; text-transform:uppercase; letter-spacing:.03em; color:#111827; line-height:1.1; }
.f-company-branch { font-size:10px; font-weight:700; color:#4B5563; margin-top:2px; }
.f-company-addr { font-size:9px; color:#6B7280; margin-top:3px; line-height:1.4; }
.f-company-contact { font-size:9px; color:#374151; margin-top:3px; }
.f-head-right { text-align:right; flex-shrink:0; }
.f-head-right h2 { font-size:16px; font-weight:800; margin:0 0 4px; color:#1E40AF; }
.f-receipt-meta { font-size:10px; line-height:1.6; }

/* Services bar */
.f-services { background:#F9FAFB; border:1px dashed #D1D5DB; border-radius:3px; padding:5px 8px; font-size:9px; color:#374151; margin-bottom:10px; line-height:1.4; }
.f-services strong { color:#111827; }

/* Info grid */
.f-grid { display:grid; grid-template-columns:1fr 1fr; gap:8px 16px; margin-bottom:12px; }
.f-box { border:1px solid #D1D5DB; padding:7px; min-height:50px; border-radius:2px; }
.f-lbl { font-size:9px; color:#6B7280; text-transform:uppercase; font-weight:700; letter-spacing:.04em; margin-bottom:2px; }
.f-val { font-size:12px; font-weight:700; }
.f-sub { font-size:10px; color:#6B7280; margin-top:1px; }

/* Tables */
.f-tbl { width:100%; border-collapse:collapse; font-size:10px; margin-bottom:10px; }
.f-tbl th, .f-tbl td { border:1px solid #D1D5DB; padding:5px 6px; vertical-align:top; }
.f-tbl th { background:#F3F4F6; text-transform:uppercase; font-size:9px; font-weight:700; }
.f-tbl .text-end { text-align:right; }
.f-section-hd { font-size:10px; font-weight:700; text-transform:uppercase; color:#374151; border-bottom:1px solid #E5E7EB; padding-bottom:3px; margin:10px 0 6px; letter-spacing:.04em; }

/* Totals */
.f-totals { margin-left:auto; width:74mm; font-size:11px; margin-bottom:12px; }
.f-tot-row { display:flex; justify-content:space-between; border-bottom:1px solid #E5E7EB; padding:4px 0; }
.f-tot-row.strong { font-size:14px; font-weight:800; border-top:2px solid #111827; border-bottom:2px solid #111827; margin-top:4px; padding:5px 0; }

/* EIS receipt block */
.f-eis-submitted { border:2px solid #059669; border-radius:4px; padding:10px; margin-top:12px; background:#F0FDF4; }
.f-eis-submitted .eis-badge { display:flex; align-items:center; gap:6px; margin-bottom:8px; }
.f-eis-submitted .eis-badge .eis-icon { width:22px; height:22px; background:#059669; border-radius:50%; display:flex; align-items:center; justify-content:center; flex-shrink:0; }
.f-eis-submitted .eis-badge .eis-icon svg { fill:#fff; width:13px; height:13px; }
.f-eis-submitted .eis-badge strong { font-size:11px; font-weight:800; color:#059669; text-transform:uppercase; }
.f-eis-submitted .eis-row { font-size:10px; display:flex; gap:6px; margin-bottom:3px; }
.f-eis-submitted .eis-row span:first-child { color:#6B7280; width:95px; flex-shrink:0; font-weight:700; }
.f-eis-submitted .eis-url { font-size:9px; overflow-wrap:anywhere; color:#1D4ED8; margin-top:5px; border-top:1px dashed #A7F3D0; padding-top:5px; }

/* Non-EIS notice */
.f-eis-notice { border:2px dashed #D97706; border-radius:4px; padding:8px 10px; margin-top:12px; background:#FFFBEB; }
.f-eis-notice .notice-hd { font-size:10px; font-weight:800; color:#92400E; text-transform:uppercase; margin-bottom:4px; display:flex; align-items:center; gap:6px; }
.f-eis-notice .notice-body { font-size:9px; color:#78350F; line-height:1.5; }

/* Footer */
.f-footer { margin-top:16px; display:flex; justify-content:space-between; gap:16mm; font-size:10px; }
.sig-line { border-top:1px solid #111827; padding-top:4px; flex:1; text-align:center; }

/* ── Thermal receipt ── */
.cr-thermal { padding:4mm 3mm; font-family:Consolas,'Courier New',monospace; line-height:1.3; font-weight:700; }
body.cr-fmt-th80 .cr-thermal { width:80mm; font-size:11px; }
body.cr-fmt-th58 .cr-thermal { width:58mm; font-size:10px; }
.th-center { text-align:center; }
.th-logo { max-height:28mm; max-width:90%; display:block; margin:0 auto 3px; }
.th-brand { font-size:14px; font-weight:900; text-transform:uppercase; }
body.cr-fmt-th58 .th-brand { font-size:12px; }
.th-contact { font-size:8px; margin-top:2px; }
.th-services { font-size:8px; font-style:italic; margin-top:2px; overflow-wrap:anywhere; }
.th-title { border-top:1px dashed #000; border-bottom:1px dashed #000; margin:6px 0; padding:5px 0; font-size:12px; font-weight:900; }
body.cr-fmt-th58 .th-title { font-size:10px; }
.th-row { display:flex; justify-content:space-between; gap:6px; margin:2px 0; }
.th-row span:last-child { text-align:right; overflow-wrap:anywhere; }
.th-div { border-top:1px dashed #000; margin:6px 0; }
.th-items { width:100%; border-collapse:collapse; font-size:10px; }
.th-items td { padding:3px 0; border-bottom:1px dotted #000; vertical-align:top; }
body.cr-fmt-th58 .th-items { font-size:9px; }
.th-total { font-size:12px; font-weight:900; border-top:2px solid #000; border-bottom:2px solid #000; padding:4px 0; margin-top:5px; }
body.cr-fmt-th58 .th-total { font-size:10px; }
.th-sm { font-size:9px; overflow-wrap:anywhere; }
body.cr-fmt-th58 .th-sm { font-size:8px; }
.th-eis-ok { border:1px solid #000; padding:4px 5px; margin-top:5px; font-size:9px; }
.th-eis-ok .th-eis-hd { text-align:center; font-size:10px; font-weight:900; border-bottom:1px dashed #000; padding-bottom:3px; margin-bottom:3px; }
.th-no-eis { border:2px dashed #000; padding:4px 5px; margin-top:5px; font-size:9px; text-align:center; }
.th-no-eis strong { font-size:9px; display:block; margin-bottom:2px; }

/* ── Print ── */
@media print {
    .no-print, .main-sidebar, .main-header, .main-footer, footer { display:none!important; }
    html, body, .content-wrapper, .cr-page { margin:0!important; padding:0!important; background:#fff!important; }
    .content-wrapper { margin-left:0!important; }
    .cr-stage { display:block; }
    .cr-doc { box-shadow:none!important; }
    body.cr-fmt-a5 .cr-formal,
    body.cr-fmt-a4 .cr-formal { width:auto; min-height:auto; padding:0; }
    body.cr-fmt-th80 .cr-thermal { width:80mm; padding:3mm; }
    body.cr-fmt-th58 .cr-thermal { width:58mm; padding:2mm; }
    body.cr-fmt-a5 .cr-thermal, body.cr-fmt-a4 .cr-thermal { display:none!important; }
    body.cr-fmt-th80 .cr-formal, body.cr-fmt-th58 .cr-formal { display:none!important; }
    .f-logo-placeholder { -webkit-print-color-adjust:exact; print-color-adjust:exact; }
    .f-eis-submitted { -webkit-print-color-adjust:exact; print-color-adjust:exact; }
    .f-eis-notice { -webkit-print-color-adjust:exact; print-color-adjust:exact; }
}
</style>

<div class="cr-page px-4 pt-4">
<div class="cr-wrap">

    <!-- Toolbar -->
    <div class="cr-toolbar mb-3 no-print">
        <a href="credit_sales.php" class="btn btn-outline-secondary btn-sm"><i class="fas fa-arrow-left me-1"></i> Back</a>
        <div class="d-flex align-items-center gap-2 flex-wrap">
            <div class="btn-group" role="group" aria-label="Paper size">
                <button type="button" class="btn btn-sm btn-outline-primary" id="crBtnTh58"><i class="fas fa-receipt me-1"></i>58mm</button>
                <button type="button" class="btn btn-sm btn-outline-primary" id="crBtnTh80"><i class="fas fa-receipt me-1"></i>80mm</button>
                <button type="button" class="btn btn-sm btn-outline-primary" id="crBtnA5"><i class="fas fa-file-alt me-1"></i>A5</button>
                <button type="button" class="btn btn-sm btn-outline-primary" id="crBtnA4"><i class="fas fa-file-alt me-1"></i>A4</button>
            </div>
            <button type="button" onclick="crPrint()" class="btn btn-primary btn-sm"><i class="fas fa-print me-1"></i> Print</button>
        </div>
    </div>

    <div class="cr-stage">

    <!-- ═══════════════════════ FORMAL RECEIPT (A5 / A4) ═══════════════════════ -->
    <section class="cr-doc cr-formal">

        <!-- Header: Logo + Company info | Receipt meta -->
        <div class="f-head">
            <div class="f-head-left">
                <?php if (!empty($companyLogo)): ?>
                    <img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="Logo" class="f-logo"
                         onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">
                    <div class="f-logo-placeholder" style="display:none"><span><?php echo htmlspecialchars(mb_substr($companyLabel,0,1)); ?></span></div>
                <?php else: ?>
                    <div class="f-logo-placeholder"><span><?php echo htmlspecialchars(mb_substr($companyLabel,0,1)); ?></span></div>
                <?php endif; ?>
                <div class="f-company">
                    <div class="f-company-name"><?php echo htmlspecialchars($companyLabel); ?></div>
                    <div class="f-company-branch"><?php echo htmlspecialchars($branchLabel); ?></div>
                    <?php if ($branchAddress): ?><div class="f-company-addr"><?php echo nl2br(htmlspecialchars($branchAddress)); ?></div><?php endif; ?>
                    <div class="f-company-contact">
                        <?php
                        $contactParts = [];
                        if ($branchPhone)   $contactParts[] = 'Tel: ' . htmlspecialchars($branchPhone);
                        if ($branchEmail)   $contactParts[] = 'Email: ' . htmlspecialchars($branchEmail);
                        if ($branchWebsite) $contactParts[] = 'Web: '  . htmlspecialchars($branchWebsite);
                        echo implode(' &nbsp;|&nbsp; ', $contactParts);
                        ?>
                    </div>
                </div>
            </div>
            <div class="f-head-right">
                <h2><?php echo htmlspecialchars($receiptTitle); ?></h2>
                <div class="f-receipt-meta">
                    <div><strong>Receipt No:</strong> <?php echo htmlspecialchars($receiptNo); ?></div>
                    <div><strong>Date:</strong> <?php echo htmlspecialchars(date('d M Y H:i', strtotime($issuedAt))); ?></div>
                    <div><strong>Status:</strong> <?php echo htmlspecialchars(ucwords(str_replace('_', ' ', (string)$credit['status']))); ?></div>
                </div>
            </div>
        </div>

        <!-- Services -->
        <?php if ($serviceBody): ?>
        <div class="f-services">
            <strong>Services &amp; Products:</strong> <?php echo htmlspecialchars($serviceBody); ?>
        </div>
        <?php endif; ?>

        <!-- Info boxes -->
        <div class="f-grid">
            <div class="f-box">
                <div class="f-lbl">Customer</div>
                <div class="f-val"><?php echo htmlspecialchars($credit['customer_name']); ?></div>
                <div class="f-sub"><?php echo htmlspecialchars($credit['customer_phone'] ?? '-'); ?></div>
            </div>
            <div class="f-box">
                <div class="f-lbl">Credit Sale Ref</div>
                <div class="f-val"><?php echo htmlspecialchars($credit['credit_number']); ?></div>
                <div class="f-sub">Txn: <?php echo htmlspecialchars($credit['transaction_id']); ?></div>
            </div>
            <?php if ($currentPayment): ?>
            <div class="f-box">
                <div class="f-lbl">This Payment</div>
                <div class="f-val">MWK <?php echo number_format($paymentAmount, 2); ?></div>
                <div class="f-sub"><?php echo htmlspecialchars($paymentMethod); ?></div>
            </div>
            <div class="f-box">
                <div class="f-lbl">Recorded By</div>
                <div class="f-val"><?php echo htmlspecialchars($recordedBy); ?></div>
                <div class="f-sub"><?php echo htmlspecialchars(date('d M Y H:i', strtotime($currentPayment['payment_date']))); ?></div>
            </div>
            <?php else: ?>
            <div class="f-box">
                <div class="f-lbl">Total Credit</div>
                <div class="f-val">MWK <?php echo number_format($totalAmount, 2); ?></div>
            </div>
            <div class="f-box">
                <div class="f-lbl">Balance</div>
                <div class="f-val" style="color:<?php echo $balance > 0 ? '#DC2626' : '#059669'; ?>">MWK <?php echo number_format($balance, 2); ?></div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Items -->
        <div class="f-section-hd">Items Purchased</div>
        <table class="f-tbl">
            <thead><tr><th>#</th><th>Item</th><th>Code</th><th class="text-end">Unit Price</th></tr></thead>
            <tbody>
            <?php foreach ($items as $idx => $item): ?>
            <tr>
                <td><?php echo $idx + 1; ?></td>
                <td><?php echo htmlspecialchars($item['item_name'] ?? '-'); ?></td>
                <td><?php echo htmlspecialchars($item['unique_code']); ?></td>
                <td class="text-end">MWK <?php echo number_format((float)$item['unit_price'], 2); ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>

        <!-- Payment history -->
        <div class="f-section-hd">Payment History</div>
        <table class="f-tbl">
            <thead><tr><th>Date</th><th>Method</th><th>Notes</th><th class="text-end">Amount</th></tr></thead>
            <tbody>
            <?php foreach ($payments as $payment): ?>
            <tr<?php echo $currentPayment && (int)$currentPayment['payment_id'] === (int)$payment['payment_id'] ? ' style="background:#F0FDF4"' : ''; ?>>
                <td><?php echo htmlspecialchars(date('d M Y H:i', strtotime($payment['payment_date']))); ?></td>
                <td><?php echo htmlspecialchars(paymentMethodLabel($payment['payment_method'])); ?></td>
                <td><?php echo htmlspecialchars($payment['notes'] ?? ''); ?></td>
                <td class="text-end">MWK <?php echo number_format((float)$payment['amount'], 2); ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if (!$payments): ?>
            <tr><td colspan="4" style="text-align:center;color:#6B7280">No payments recorded.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>

        <!-- Totals -->
        <div class="f-totals">
            <div class="f-tot-row"><span>Total Credit Amount</span><span>MWK <?php echo number_format($totalAmount, 2); ?></span></div>
            <div class="f-tot-row"><span>Total Paid</span><span>MWK <?php echo number_format($totalPaid, 2); ?></span></div>
            <div class="f-tot-row strong"><span>Balance Due</span><span>MWK <?php echo number_format($balance, 2); ?></span></div>
        </div>

        <!-- ── EIS Receipt Section ── -->
        <?php if ($isEisReceipt): ?>
        <div class="f-eis-submitted">
            <div class="eis-badge">
                <div class="eis-icon">
                    <svg viewBox="0 0 24 24"><path d="M20.285 6.709l-11.4 11.4-5.57-5.572 1.414-1.414 4.156 4.157 9.986-9.986z"/></svg>
                </div>
                <strong>MRA EIS Fiscal Receipt &mdash; Submitted</strong>
            </div>
            <div class="eis-row"><span>MRA Reference:</span><span><?php echo htmlspecialchars($eisRef); ?></span></div>
            <?php if ($eisSubmittedAt): ?>
            <div class="eis-row"><span>Submitted At:</span><span><?php echo htmlspecialchars(date('d M Y H:i', strtotime($eisSubmittedAt))); ?></span></div>
            <?php endif; ?>
            <div class="eis-row"><span>EIS Status:</span><span><?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $eisStatus))); ?></span></div>
            <?php if ($eisValidationUrl): ?>
            <div class="eis-url"><strong>Validation URL:</strong> <?php echo htmlspecialchars($eisValidationUrl); ?></div>
            <?php endif; ?>
        </div>
        <?php elseif ($isFinal): ?>
        <div class="f-eis-notice">
            <div class="notice-hd">&#9888; Not an MRA EIS Fiscal Receipt</div>
            <div class="notice-body">
                This document has not been submitted to the Malawi Revenue Authority Electronic Invoice System (MRA EIS)
                <?php if ($eisOutbox && in_array($eisStatus, ['pending','ready','failed','blocked'])): ?>
                    &mdash; EIS submission status: <strong><?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $eisStatus))); ?></strong>.
                <?php else: ?>
                    and is not a valid fiscal receipt under MRA EIS regulations.
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Signature footer -->
        <div class="f-footer">
            <div class="sig-line">Customer Signature</div>
            <div class="sig-line">Authorized Signature</div>
        </div>

    </section><!-- .cr-formal -->


    <!-- ═══════════════════════ THERMAL RECEIPT (80mm / 58mm) ═══════════════════════ -->
    <section class="cr-doc cr-thermal">

        <!-- Header -->
        <div class="th-center">
            <?php if (!empty($companyLogo)): ?>
            <img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="Logo" class="th-logo"
                 onerror="this.style.display='none'">
            <?php endif; ?>
            <div class="th-brand"><?php echo htmlspecialchars($companyLabel); ?></div>
            <div class="th-contact">
                <?php
                $thParts = [];
                if ($branchPhone)   $thParts[] = htmlspecialchars($branchPhone);
                if ($branchEmail)   $thParts[] = htmlspecialchars($branchEmail);
                if ($branchWebsite) $thParts[] = htmlspecialchars($branchWebsite);
                echo implode(' | ', $thParts);
                ?>
            </div>
            <?php if ($branchAddress): ?><div class="th-contact"><?php echo htmlspecialchars($branchAddress); ?></div><?php endif; ?>
            <?php if ($serviceBody): ?><div class="th-services"><?php echo htmlspecialchars(mb_substr($serviceBody, 0, 120)); ?></div><?php endif; ?>
            <div class="th-title"><?php echo htmlspecialchars(strtoupper($receiptTitle)); ?></div>
        </div>

        <div class="th-row"><span>Receipt:</span><span><?php echo htmlspecialchars($receiptNo); ?></span></div>
        <div class="th-row"><span>Date:</span><span><?php echo htmlspecialchars(date('d/m/y H:i', strtotime($issuedAt))); ?></span></div>
        <div class="th-row"><span>Credit Ref:</span><span><?php echo htmlspecialchars($credit['credit_number']); ?></span></div>
        <div class="th-row"><span>Customer:</span><span><?php echo htmlspecialchars($credit['customer_name']); ?></span></div>
        <div class="th-row"><span>Phone:</span><span><?php echo htmlspecialchars($credit['customer_phone'] ?? '-'); ?></span></div>

        <div class="th-div"></div>
        <table class="th-items">
        <?php foreach ($items as $item): ?>
            <tr>
                <td><?php echo htmlspecialchars($item['item_name'] ?? '-'); ?><br><span class="th-sm"><?php echo htmlspecialchars($item['unique_code']); ?></span></td>
                <td style="text-align:right;white-space:nowrap;">MWK <?php echo number_format((float)$item['unit_price'], 2); ?></td>
            </tr>
        <?php endforeach; ?>
        </table>

        <div class="th-div"></div>

        <?php if ($currentPayment): ?>
        <div class="th-row th-total"><span>PAID NOW</span><span>MWK <?php echo number_format($paymentAmount, 2); ?></span></div>
        <div class="th-row"><span>Method:</span><span><?php echo htmlspecialchars($paymentMethod); ?></span></div>
        <?php endif; ?>

        <div class="th-row"><span>Total Credit:</span><span>MWK <?php echo number_format($totalAmount, 2); ?></span></div>
        <div class="th-row"><span>Total Paid:</span><span>MWK <?php echo number_format($totalPaid, 2); ?></span></div>
        <div class="th-row th-total"><span>BALANCE</span><span>MWK <?php echo number_format($balance, 2); ?></span></div>

        <!-- ── Thermal EIS section ── -->
        <?php if ($isEisReceipt): ?>
        <div class="th-eis-ok">
            <div class="th-eis-hd">*** MRA EIS RECEIPT ***</div>
            <div class="th-sm">Ref: <?php echo htmlspecialchars($eisRef); ?></div>
            <?php if ($eisSubmittedAt): ?><div class="th-sm">Date: <?php echo htmlspecialchars(date('d/m/y H:i', strtotime($eisSubmittedAt))); ?></div><?php endif; ?>
            <?php if ($eisValidationUrl): ?><div class="th-sm"><?php echo htmlspecialchars($eisValidationUrl); ?></div><?php endif; ?>
        </div>
        <?php elseif ($isFinal): ?>
        <div class="th-no-eis">
            <strong>* NOT AN MRA EIS RECEIPT *</strong>
            <span class="th-sm">
            <?php if ($eisOutbox && in_array($eisStatus, ['pending','ready','failed','blocked'])): ?>
                EIS Status: <?php echo htmlspecialchars(strtoupper($eisStatus)); ?>
            <?php else: ?>
                Not submitted to MRA EIS.
            <?php endif; ?>
            </span>
        </div>
        <?php endif; ?>

        <div class="th-div"></div>
        <div class="th-center th-sm">Thank you for your business</div>

    </section><!-- .cr-thermal -->

    </div><!-- .cr-stage -->
</div><!-- .cr-wrap -->
</div><!-- .cr-page -->

<script>
(function () {
    var pageStyle = document.getElementById('crPrintPageSize');
    var formats = {
        th58: { cls: 'cr-fmt-th58', page: '@page { size: 58mm auto; margin: 0; }' },
        th80: { cls: 'cr-fmt-th80', page: '@page { size: 80mm auto; margin: 0; }' },
        a5:   { cls: 'cr-fmt-a5',   page: '@page { size: A5 portrait; margin: 10mm; }' },
        a4:   { cls: 'cr-fmt-a4',   page: '@page { size: A4 portrait; margin: 12mm; }' }
    };
    var btnMap = { th58: 'crBtnTh58', th80: 'crBtnTh80', a5: 'crBtnA5', a4: 'crBtnA4' };

    function setFormat(fmt) {
        if (!formats[fmt]) fmt = 'th80';
        Object.values(formats).forEach(function (f) { document.body.classList.remove(f.cls); });
        document.body.classList.add(formats[fmt].cls);
        if (pageStyle) pageStyle.textContent = formats[fmt].page;
        Object.keys(btnMap).forEach(function (k) {
            var btn = document.getElementById(btnMap[k]);
            if (!btn) return;
            btn.classList.toggle('btn-primary', k === fmt);
            btn.classList.toggle('btn-outline-primary', k !== fmt);
        });
        localStorage.setItem('crReceiptFormat', fmt);
    }

    window.crPrint = function () { window.print(); };

    document.addEventListener('DOMContentLoaded', function () {
        var saved = localStorage.getItem('crReceiptFormat') || 'th80';
        setFormat(saved);
        Object.keys(btnMap).forEach(function (k) {
            var btn = document.getElementById(btnMap[k]);
            if (btn) btn.addEventListener('click', function () { setFormat(k); });
        });
    });
})();
</script>
<?php include '../../includes/footer.php'; ?>
