<?php
require_once __DIR__ . '/../../classes/Branding.php';
require_once __DIR__ . '/../../vendor/autoload.php';
$companyName = Branding::companyName();
$companyLogo = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();
$settings = Branding::settings();
$vatPercentage = (float)($settings['vat_percentage'] ?? 17.5);
$vatRate = $vatPercentage / 100;
$profitPercentage = (float)($settings['profit_percentage'] ?? 30.0);
$profitRate = $profitPercentage / 100;

session_start();


require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/payment_options.php';


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



$conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


$auth = new Auth($conn);


if (!$auth->isSalesAssistant($_SESSION['user_id']) && !$auth->isBranchManager($_SESSION['user_id'])) {
    die("Access denied. You must be a sales assistant or branch manager to access this page.");
}


if (!isset($_SESSION['sale_data'])) {
    header('Location: create_sale.php');
    exit();
}


$saleData = $_SESSION['sale_data'];
$eisTransactionType = strtoupper(trim((string)($saleData['eis_transaction_type'] ?? 'B2C')));
if (!in_array($eisTransactionType, ['B2B', 'B2C'], true)) {
    $eisTransactionType = 'B2C';
}
$branchId = $auth->getUserBranch($_SESSION['user_id']);

// Refresh the EIS acknowledgement from the outbox. This covers B2B responses
// and delayed submissions where the session did not retain the validation URL.
try {
    $outboxStmt = $conn->prepare("
        SELECT status, validation_url, response_body, payload_json, local_audit_json
        FROM mra_eis_outbox
        WHERE entity_type = 'sale'
          AND source_key = :transaction_id
          AND branch_id = :branch_id
        ORDER BY id DESC
        LIMIT 1
    ");
    $outboxStmt->execute([
        ':transaction_id' => (string)($saleData['transaction_id'] ?? ''),
        ':branch_id' => (int)$branchId,
    ]);
    $outbox = $outboxStmt->fetch(PDO::FETCH_ASSOC);
    if ($outbox) {
        $outboxPayload = json_decode((string)($outbox['payload_json'] ?? ''), true);
        $outboxAudit = json_decode((string)($outbox['local_audit_json'] ?? ''), true);
        if (is_array($outboxAudit) && array_key_exists('is_vat_registered', $outboxAudit)) {
            $saleData['is_vat_registered'] = $outboxAudit['is_vat_registered'];
        }
        $offlineSignature = trim((string)($outboxPayload['invoiceSummary']['offlineSignature'] ?? ''));
        if ($offlineSignature !== '' && ($outbox['status'] ?? '') !== 'submitted') {
            $saleData['eis_status'] = 'offline';
            $saleData['eis_offline_signature'] = $offlineSignature;
            $saleData['eis_offline_qr_data'] = $outboxAudit['offline_receipt_data'] ?? null;
            $saleData['eis_message'] = 'Signed offline B2C invoice queued for MRA EIS submission.';
        } else {
            $saleData['eis_status'] = $outbox['status'] ?: ($saleData['eis_status'] ?? null);
        }
        if (!empty($outbox['validation_url'])) {
            $saleData['eis_validation_url'] = trim((string)$outbox['validation_url']);
        }
        if (!empty($outboxPayload['invoiceSummary']['taxBreakDown'])) {
            $saleData['eis_tax_breakdown'] = array_values((array)$outboxPayload['invoiceSummary']['taxBreakDown']);
        }
        if (!empty($outboxPayload['invoiceSummary']['levyBreakDown'])) {
            $saleData['eis_levy_breakdown'] = array_values((array)$outboxPayload['invoiceSummary']['levyBreakDown']);
        }
    }
} catch (Throwable $e) {
    error_log('Unable to refresh EIS receipt acknowledgement: ' . $e->getMessage());
}

$sellerTin = trim((string)(isset($outboxPayload) ? ($outboxPayload['invoiceHeader']['sellerTIN'] ?? '') : ''));
$paymentMethodLabel = paymentMethodLabel($saleData['payment_method'] ?? 'cash');

$isCreditReceipt = (($saleData['sale_mode'] ?? '') === 'credit');
$creditData = null;
$creditPayments = [];
if ($isCreditReceipt && !empty($_GET['credit_id'])) {
    try {
        require_once __DIR__ . '/../../classes/CreditSales.php';
        $creditSalesObj = new CreditSales($conn);
        $creditData = $creditSalesObj->getCreditById((int)$_GET['credit_id']);
        $creditPayments = $creditSalesObj->getPayments((int)$_GET['credit_id']);
    } catch (Throwable $e) {
        error_log('Unable to fetch credit data for receipt: ' . $e->getMessage());
    }
}
$receiptAmountPaid = round((float)($saleData['amount_paid'] ?? 0), 2);
$receiptCreditBalance = $isCreditReceipt
    ? round((float)($saleData['credit_balance'] ?? max(0, ($saleData['total'] ?? 0) - $receiptAmountPaid)), 2)
    : 0.0;
$creditNumber = $creditData ? ($creditData['credit_number'] ?? null) : null;

$itemNames = array_values((array)($saleData['item_names'] ?? []));
$uniqueCodes = array_values((array)($saleData['unique_codes'] ?? []));
$itemDetails = array_values((array)($saleData['item_details'] ?? []));
$receiptPrices = array_map(static function ($price) {
    return round((float)$price, 2);
}, array_values((array)($saleData['prices'] ?? [])));
$receiptItemCount = min(count($itemNames), count($uniqueCodes), count($receiptPrices));
$detailsByCode = [];
if ($receiptItemCount > 0) {
    try {
        $lookupCodes = array_values(array_unique(array_filter(array_map('trim', array_slice($uniqueCodes, 0, $receiptItemCount)))));
        if ($lookupCodes) {
            $placeholders = implode(',', array_fill(0, count($lookupCodes), '?'));
            $detailsStmt = $conn->prepare("SELECT unique_code, item_details FROM items WHERE unique_code IN ($placeholders)");
            $detailsStmt->execute($lookupCodes);
            foreach ($detailsStmt->fetchAll(PDO::FETCH_ASSOC) as $detailRow) {
                $detailsByCode[(string)$detailRow['unique_code']] = trim((string)($detailRow['item_details'] ?? ''));
            }
        }
    } catch (Throwable $e) {
        error_log('Unable to load item details for receipt: ' . $e->getMessage());
    }
}
for ($i = 0; $i < $receiptItemCount; $i++) {
    $code = trim((string)$uniqueCodes[$i]);
    $itemDetails[$i] = $detailsByCode[$code] ?? trim((string)($itemDetails[$i] ?? ''));
}
$receiptTotal = round(array_sum(array_slice($receiptPrices, 0, $receiptItemCount)), 2);

// Build per-rate (A/B/E) tax breakdown — prefer the EIS-submitted breakdown
// (device/terminal computed, authoritative) and otherwise compute one locally
// from each line's own MRA tax rate group, so a mixed-tax-group sale is never
// taxed by a single blended rate just because the EIS payload isn't in yet.
$noVat = !empty($saleData['vat_relief']) || ($saleData['is_vat_registered'] ?? null) === false;

$eisTaxBreakdown = [];
if (!$noVat && !empty($saleData['eis_tax_breakdown'])) {
    foreach ((array)$saleData['eis_tax_breakdown'] as $bucket) {
        $rateId = strtoupper((string)($bucket['rateId'] ?? ''));
        if ($rateId === '') {
            continue;
        }
        $eisTaxBreakdown[] = [
            'rateId'        => $rateId,
            'taxableAmount' => round((float)($bucket['taxableAmount'] ?? 0), 2),
            'taxAmount'     => round((float)($bucket['taxAmount'] ?? 0), 2),
        ];
    }
}

if (!$noVat && empty($eisTaxBreakdown)) {
    require_once __DIR__ . '/../../classes/SystemSettings.php';
    require_once __DIR__ . '/../../classes/Inventory.php';
    require_once __DIR__ . '/../../classes/MraEisCompliance.php';
    $zeroRatedTaxIds = (new SystemSettings())->eisZeroRatedTaxIds();
    $inventory = new Inventory($conn);
    $eisCompliance = new MraEisCompliance($conn);

    $groupTaxableCents = [];
    $groupTaxCents = [];
    for ($i = 0; $i < $receiptItemCount; $i++) {
        $lineCents = (int)round($receiptPrices[$i] * 100);
        if ($lineCents <= 0) {
            continue;
        }
        $taxRateId = 'A';
        try {
            $lineItem = $inventory->getItemByUniqueCode(trim((string)$uniqueCodes[$i]));
            if ($lineItem) {
                $taxRateId = $eisCompliance->resolveTaxRateId($lineItem['item_id']);
            }
        } catch (Throwable $e) {
            $taxRateId = 'A';
        }
        $isZeroRated = in_array($taxRateId, $zeroRatedTaxIds, true);
        $lineVatCents = $isZeroRated ? 0 : (int)round(($lineCents * $vatRate) / (1 + $vatRate));
        $lineTaxableCents = $lineCents - $lineVatCents;

        $groupTaxableCents[$taxRateId] = ($groupTaxableCents[$taxRateId] ?? 0) + $lineTaxableCents;
        $groupTaxCents[$taxRateId] = ($groupTaxCents[$taxRateId] ?? 0) + $lineVatCents;
    }
    foreach ($groupTaxableCents as $rateId => $taxableCents) {
        $eisTaxBreakdown[] = [
            'rateId'        => $rateId,
            'taxableAmount' => round($taxableCents / 100, 2),
            'taxAmount'     => round(($groupTaxCents[$rateId] ?? 0) / 100, 2),
        ];
    }
}

$eisLevyBreakdown = [];
foreach ((array)($saleData['eis_levy_breakdown'] ?? []) as $bucket) {
    $levyTypeId = strtoupper(trim((string)($bucket['levyTypeId'] ?? $bucket['rateId'] ?? '')));
    if ($levyTypeId !== '') {
        $eisLevyBreakdown[] = [
            'levyTypeId' => $levyTypeId,
            'levyRate'   => round((float)($bucket['levyRate'] ?? 0), 2),
            'levyAmount' => round((float)($bucket['levyAmount'] ?? $bucket['taxAmount'] ?? 0), 2),
        ];
    }
}

if ($noVat) {
    $receiptSubtotal = $receiptTotal;
    $receiptVat = 0.0;
} else {
    $receiptSubtotal = round(array_sum(array_column($eisTaxBreakdown, 'taxableAmount')), 2);
    $receiptVat = round(array_sum(array_column($eisTaxBreakdown, 'taxAmount')), 2);
}

// Recalculate the printed figures from the actual receipt lines so the lines,
// subtotal, VAT and total always reconcile to the cent.
$saleData['quantity'] = $receiptItemCount;
$saleData['subtotal'] = $receiptSubtotal;
$saleData['vat_amount'] = $receiptVat;
$saleData['total'] = $receiptTotal;

$receiptDiscount = round((float)($saleData['discount'] ?? 0), 2);
$receiptOriginalTotal = round((float)($saleData['original_total'] ?? $receiptTotal), 2);
$receiptDiscountPct = round((float)($saleData['discount_percentage'] ?? 0), 1);
$isReliefSupply = !empty($saleData['vat_relief']);
$vat5CertNumber = trim((string)($saleData['vat5_certificate_number'] ?? ''));
$vat5ProjectNumber = trim((string)($saleData['vat5_project_number'] ?? ''));

$eisQrDataUri = null;
$eisValidationUrl = trim((string)($saleData['eis_validation_url'] ?? ''));
$eisAcknowledged = strtolower((string)($saleData['eis_status'] ?? '')) === 'submitted'
    && filter_var($eisValidationUrl, FILTER_VALIDATE_URL) !== false;
if ($eisAcknowledged) {
    try {
        $barcode = new \Com\Tecnick\Barcode\Barcode();
        $qrCode = $barcode->getBarcodeObj('QRCODE,H', $eisValidationUrl, -4, -4, 'black', [-2, -2, -2, -2]);
        // SVG output avoids requiring GD/Imagick and stays sharp on thermal prints.
        $eisQrDataUri = 'data:image/svg+xml;base64,' . base64_encode($qrCode->getSvgCode());
    } catch (Throwable $e) {
        error_log('Unable to generate EIS receipt QR code: ' . $e->getMessage());
    }
}

$eisOfflineQrDataUri = null;
$eisOfflineQrData = trim((string)($saleData['eis_offline_qr_data'] ?? ''));
if (strtolower((string)($saleData['eis_status'] ?? '')) === 'offline' && $eisOfflineQrData !== '') {
    try {
        $barcode = new \Com\Tecnick\Barcode\Barcode();
        $qrCode = $barcode->getBarcodeObj('QRCODE,H', $eisOfflineQrData, -4, -4, 'black', [-2, -2, -2, -2]);
        $eisOfflineQrDataUri = 'data:image/svg+xml;base64,' . base64_encode($qrCode->getSvgCode());
    } catch (Throwable $e) {
        error_log('Unable to generate offline EIS receipt QR code: ' . $e->getMessage());
    }
}


$stmt = $conn->prepare("SELECT * FROM branches WHERE branch_id = ?");
$stmt->execute([$branchId]);
$branch = $stmt->fetch(PDO::FETCH_ASSOC);
$branchBranding = Branding::documentDetailsForBranch($branch ?: []);
$companyName = $branchBranding['name'];
$companyLogo = $branchBranding['logo'];
$companyLogoFile = $branchBranding['logo_file'];


$stmt = $conn->prepare("SELECT username FROM users WHERE user_id = ?");
$stmt->execute([$_SESSION['user_id']]);
$salesRep = $stmt->fetch(PDO::FETCH_ASSOC);
$salesRepName = $salesRep['username'] ?? $_SESSION['username'];


$receiptTimezone = new DateTimeZone('Africa/Blantyre');
$serverTime = false;
$eisInvoiceDateTime = isset($outboxPayload) ? ($outboxPayload['invoiceHeader']['invoiceDateTime'] ?? null) : null;
if (is_string($eisInvoiceDateTime) && trim($eisInvoiceDateTime) !== '') {
    try {
        $parsed = new DateTimeImmutable($eisInvoiceDateTime);
        $serverTime = $parsed->setTimezone($receiptTimezone);
        $formattedDate = $serverTime->format('n/j/y');
    } catch (Throwable $e) {
        $serverTime = false;
    }
}
if ($serverTime === false) {
    $dateTime = new DateTime($saleData['sale_date'], $receiptTimezone);
    $formattedDate = $dateTime->format('n/j/y');
    $saleTime = trim((string)($saleData['sale_time'] ?? ''));
    $serverTime = DateTimeImmutable::createFromFormat('!H:i:s', $saleTime, $receiptTimezone);
}
if ($serverTime === false) {
    $serverTime = new DateTimeImmutable('now', $receiptTimezone);
}
$formattedTime = $serverTime->format('g:i A');
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sale Receipt</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap');

        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background: #F1F5F9;
            min-height: 100vh;
            margin: 0; padding: 0;
            color: #1E293B;
            -webkit-font-smoothing: antialiased;
        }


        .receipt-container {
            display: flex;
            justify-content: center;
            padding: 20px 0;
        }

        .receipt {
            width: var(--receipt-paper-width, 80mm);
            background: white;
            padding: var(--receipt-padding, 3mm);
            box-sizing: border-box;
            font-family: Consolas, 'Lucida Console', 'Courier New', monospace;
            font-size: 13px;
            line-height: 1.28;
            color: #000;
            font-weight: 900;
            text-rendering: geometricPrecision;
            -webkit-font-smoothing: none;
            print-color-adjust: exact;
            -webkit-print-color-adjust: exact;
            border: 1px solid #000;
            position: relative;
        }


        .receipt-header {
            text-align: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px dashed #000;
        }

        .company-logo {
            margin-bottom: 0;
            text-align: center;
        }

        .company-logo img {
            width: 100%;
            max-width: 100%;
            height: auto;
            display: block;
        }

        .company-logo .logo-placeholder {
            font-size: 28px;
            color: #667eea;
            margin-bottom: 0;
        }

        .company-info {
            margin-top: 0;
        }

        .company-info h2 {
            font-size: 18px;
            font-weight: 900;
            margin: 0 0 2px 0;
            text-transform: uppercase;
            color: #000;
        }

        .company-info p {
            margin: 0 0 1px 0;
            font-size: 15px;
            line-height: 1.12;
            color: #000;
            font-weight: 900;
        }

        .company-contact {
            margin: 2px 0;
            font-size: 12px;
        }

        .company-contact .contact-item {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 4px;
            margin: 0;
            color: #000;
            line-height: 1.1;
        }

        .company-contact .contact-item i {
            font-size: 8px;
            width: 12px;
            text-align: center;
        }

        .company-contact .website {
            color: #667eea;
            font-weight: 900;
        }

        .transaction-info {
            margin-top: 4px;
            font-size: 12px;
            border-top: 2px solid #000;
            padding-top: 4px;
        }

        .transaction-info p {
            margin: 0;
            display: flex;
            justify-content: space-between;
            line-height: 1.15;
            color: #000;
            font-weight: 900;
        }

        .transaction-info .label {
            font-weight: 900;
        }


        .receipt-divider {
            border-top: 1px dashed #000;
            margin: 12px 0;
        }


        .items-section {
            margin-bottom: 15px;
        }

        .items-header {
            display: grid;
            grid-template-columns: 2fr 1fr 1fr;
            gap: 8px;
            font-weight: 900;
            font-size: 12px;
            text-transform: uppercase;
            border-bottom: 1px solid #000;
            padding-bottom: 4px;
            margin-bottom: 8px;
        }

        .item-row {
            display: grid;
            grid-template-columns: 2fr 1fr 1fr;
            gap: 8px;
            margin-bottom: 10px;
            font-size: 12px;
            border-bottom: 1px dotted #000;
            padding-bottom: 6px;
            align-items: start;
        }

        .item-row:last-child {
            border-bottom: none;
        }

        .item-details {
            margin-bottom: 4px;
        }

        .item-name {
            font-weight: 800;
            font-size: 13px;
            color: #000;
        }

        .item-description {
            margin-top: 2px;
            font-size: 10px;
            line-height: 1.25;
            color: #000;
            overflow-wrap: anywhere;
        }

        .item-code {
            font-size: 11px;
            color: #000;
            font-family: Consolas, 'Lucida Console', 'Courier New', monospace;
            font-weight: 900;
            text-align: center;
        }

        .item-price {
            font-size: 12px;
            text-align: right;
            font-weight: 800;
            color: #000;
        }


        .totals-section {
            margin-top: 15px;
            border-top: 1px dashed #000;
            padding-top: 10px;
        }

        .total-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 4px;
            font-size: 11px;
        }

        .total-row.subtotal {
            color: #000;
        }

        .total-row.vat {
            color: #000;
            font-size: 10px;
        }

        .total-row.discount {
            color: #000;
            font-size: 10px;
        }

        .total-row.grand-total {
            font-weight: 900;
            font-size: 13px;
            border-top: 2px solid #000;
            border-bottom: 1px solid #000;
            padding: 6px 0 4px 0;
            margin: 8px 0;
        }

        .total-row .label {
            font-weight: 900;
        }

        .total-row .amount {
            font-weight: 900;
        }


        .receipt-footer {
            text-align: center;
            font-size: 10px;
            margin-top: 15px;
            border-top: 1px dashed #000;
            padding-top: 10px;
        }

        .receipt-footer p {
            margin: 4px 0;
        }

        .thank-you {
            font-weight: 900;
            font-size: 11px;
            margin-bottom: 8px;
        }

        .warranty-info {
            font-size: 8px;
            color: #000;
            margin-top: 8px;
            line-height: 1.2;
        }

        /* Paper-specific preview layouts. Narrow rolls use stacked item rows so
           product codes and prices remain readable instead of being squeezed. */
        .receipt[data-printer-width='30'],
        .receipt[data-printer-width='40'] {
            line-height: 1.15;
        }

        .receipt[data-printer-width='30'] {
            font-size: 6px;
        }

        .receipt[data-printer-width='40'] {
            font-size: 7px;
        }

        .receipt[data-printer-width='30'] .company-logo img { width: 100%; max-width: 100%; }
        .receipt[data-printer-width='40'] .company-logo img { width: 100%; max-width: 100%; }
        .receipt[data-printer-width='50'] .company-logo img { width: 100%; max-width: 100%; }

        .receipt[data-printer-width='30'] .company-info p,
        .receipt[data-printer-width='30'] .company-contact,
        .receipt[data-printer-width='30'] .transaction-info,
        .receipt[data-printer-width='30'] .item-description,
        .receipt[data-printer-width='30'] .item-name,
        .receipt[data-printer-width='30'] .item-code,
        .receipt[data-printer-width='30'] .item-price,
        .receipt[data-printer-width='30'] .total-row,
        .receipt[data-printer-width='30'] .receipt-footer { font-size: 6px; }

        .receipt[data-printer-width='40'] .company-info p,
        .receipt[data-printer-width='40'] .company-contact,
        .receipt[data-printer-width='40'] .transaction-info,
        .receipt[data-printer-width='40'] .item-description,
        .receipt[data-printer-width='40'] .item-name,
        .receipt[data-printer-width='40'] .item-code,
        .receipt[data-printer-width='40'] .item-price,
        .receipt[data-printer-width='40'] .total-row,
        .receipt[data-printer-width='40'] .receipt-footer { font-size: 7px; }

        .receipt[data-printer-width='30'] .items-header,
        .receipt[data-printer-width='40'] .items-header { display: none; }

        .receipt[data-printer-width='30'] .item-row,
        .receipt[data-printer-width='40'] .item-row {
            display: grid;
            grid-template-columns: minmax(0, 1fr) auto;
            grid-template-areas: 'name name' 'code price';
            gap: 2px 4px;
            margin-bottom: 5px;
            padding-bottom: 4px;
            overflow-wrap: anywhere;
        }

        .receipt[data-printer-width='30'] .item-details,
        .receipt[data-printer-width='40'] .item-details { grid-area: name; margin: 0; }
        .receipt[data-printer-width='30'] .item-code,
        .receipt[data-printer-width='40'] .item-code { grid-area: code; text-align: left; }
        .receipt[data-printer-width='30'] .item-price,
        .receipt[data-printer-width='40'] .item-price { grid-area: price; text-align: right; }
        .receipt[data-printer-width='30'] .item-code::before,
        .receipt[data-printer-width='40'] .item-code::before { content: 'Code: '; font-weight: 700; }
        .receipt[data-printer-width='30'] .item-price::before,
        .receipt[data-printer-width='40'] .item-price::before { content: 'MWK '; font-weight: 700; }

        .receipt[data-printer-width='30'] .transaction-info p,
        .receipt[data-printer-width='40'] .transaction-info p,
        .receipt[data-printer-width='30'] .total-row,
        .receipt[data-printer-width='40'] .total-row { gap: 3px; overflow-wrap: anywhere; }

        .receipt[data-printer-width='50'] { font-size: 8px; }
        .receipt[data-printer-width='50'] .company-info p,
        .receipt[data-printer-width='50'] .company-contact,
        .receipt[data-printer-width='50'] .transaction-info,
        .receipt[data-printer-width='50'] .item-description,
        .receipt[data-printer-width='50'] .item-name,
        .receipt[data-printer-width='50'] .item-code,
        .receipt[data-printer-width='50'] .item-price,
        .receipt[data-printer-width='50'] .total-row,
        .receipt[data-printer-width='50'] .receipt-footer { font-size: 8px; }
        .receipt[data-printer-width='50'] .items-header,
        .receipt[data-printer-width='50'] .item-row {
            grid-template-columns: 1.5fr 1fr 1.1fr;
            gap: 3px;
            font-size: 8px;
        }

        .receipt[data-printer-width='30'] .eis-qr img { width: 18mm !important; height: 18mm !important; }
        .receipt[data-printer-width='40'] .eis-qr img { width: 24mm !important; height: 24mm !important; }
        .receipt[data-printer-width='50'] .eis-qr img { width: 29mm !important; height: 29mm !important; }


        .btn {
            padding: 10px 20px; border: none; border-radius: 8px;
            font-family: 'Inter', system-ui, sans-serif;
            font-size: .88rem; font-weight: 600; cursor: pointer;
            transition: all .15s; text-decoration: none;
            display: inline-flex; align-items: center; gap: 7px;
            letter-spacing: -.01em;
        }
        .btn-primary { background: #4F46E5; color: #fff; box-shadow: 0 2px 8px rgba(79,70,229,.2); }
        .btn-primary:hover { background: #3730A3; color: #fff; text-decoration: none; transform: translateY(-1px); }
        .btn-success { background: #059669; color: #fff; box-shadow: 0 2px 8px rgba(5,150,105,.2); }
        .btn-success:hover { background: #047857; color: #fff; text-decoration: none; transform: translateY(-1px); }
        .btn-secondary { background: #F1F5F9; color: #475569; border: 1px solid #CBD5E1; }
        .btn-secondary:hover { background: #E2E8F0; color: #1E293B; text-decoration: none; }
        @media print {
            html,
            body {
                margin: 0 !important;
                padding: 0 !important;
                background: white !important;
                min-height: 0 !important;
            }

            body * {
                visibility: hidden !important;
            }

            #receipt-content,
            #receipt-content * {
                visibility: visible !important;
            }

            .no-print,
            .page-topbar,
            .success-card,
            .eis-status-bar,
            .action-panel,
            .success-message,
            .eis-status,
            .action-buttons,
            .printer-size-toolbar {
                display: none !important;
            }

            .receipt-container {
                display: block !important;
                justify-content: flex-start !important;
                padding: 0 !important;
                margin: 0 !important;
            }

            #receipt-content {
                position: absolute !important;
                left: 0 !important;
                top: 0 !important;
            }

            .receipt {
                width: var(--receipt-paper-width, 80mm) !important;
                max-width: var(--receipt-paper-width, 80mm) !important;
                margin: 0 !important;
                padding: var(--receipt-padding, 3mm) !important;
                box-shadow: none !important;
                border: none !important;
                border-radius: 0 !important;
                font-family: Consolas, 'Lucida Console', 'Courier New', monospace !important;
                font-size: 12px;
                color: #000 !important;
                font-weight: 900;
                text-rendering: geometricPrecision;
                -webkit-font-smoothing: none;
                print-color-adjust: exact;
                -webkit-print-color-adjust: exact;
                page-break-inside: avoid;
            }

            .receipt,
            .receipt * {
                color: #000 !important;
            }

            .company-info h2 {
                font-size: 16px;
                font-weight: 900;
            }

            .company-logo img {
                width: 100%;
                max-width: 100%;
                height: auto;
                display: block;
            }

            .company-info {
                margin-top: 0;
            }

            .item-name,
            .item-code,
            .item-price {
                font-size: 12px;
                font-weight: 900;
            }

            .total-row.grand-total {
                font-size: 14px;
                font-weight: 900;
            }

            @page {
                margin: 0;
                size: var(--receipt-paper-width, 80mm) auto;
            }
        }
        @media (max-width: 768px) {
            .receipt { width: var(--receipt-paper-width, 80mm); max-width: 100%; }
            .action-btns { flex-direction: column; }
            .btn { width: 100%; justify-content: center; }
            .page-shell { padding: 14px 10px; }
        }


        .receipt {
            animation: slideUp 0.6s ease-out;
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        /* ── Page chrome ─────────────────────────────── */
        .page-topbar {
            background: #0F172A; color: #fff;
            border-bottom: 3px solid #4F46E5;
            height: 58px; display: flex; align-items: center;
            justify-content: space-between; padding: 0 20px;
            position: sticky; top: 0; z-index: 100;
        }
        .page-topbar-back {
            display: flex; align-items: center; gap: 7px;
            color: #94A3B8; text-decoration: none;
            font-size: .8rem; font-weight: 500;
            padding: 6px 12px; border-radius: 6px;
            border: 1px solid rgba(255,255,255,.1); transition: all .15s;
        }
        .page-topbar-back:hover { color: #fff; background: rgba(255,255,255,.08); text-decoration: none; }
        .page-topbar-title { font-size: .92rem; font-weight: 700; display: flex; align-items: center; gap: 8px; }
        .page-topbar-right { display: flex; align-items: center; gap: 10px; }
        .eis-pill {
            font-size: .67rem; font-weight: 700; letter-spacing: .04em;
            padding: 3px 10px; border-radius: 20px;
            display: inline-flex; align-items: center; gap: 5px;
        }
        .eis-pill.success { background: #DCFCE7; color: #166534; }
        .eis-pill.warning { background: #FEF9C3; color: #854D0E; }
        .eis-pill.danger  { background: #FEE2E2; color: #991B1B; }

        .page-shell {
            max-width: 760px; margin: 0 auto;
            padding: 24px 16px;
            display: flex; flex-direction: column;
            align-items: center; gap: 14px;
        }

        .success-card {
            width: 100%; background: #fff;
            border: 1px solid #E2E8F0; border-left: 4px solid #059669;
            border-radius: 10px; padding: 16px 20px;
            display: flex; align-items: center; gap: 14px;
            box-shadow: 0 1px 3px rgba(0,0,0,.06);
        }
        .success-card-icon {
            width: 42px; height: 42px; border-radius: 50%;
            background: #ECFDF5; color: #059669;
            display: flex; align-items: center; justify-content: center;
            font-size: 1.1rem; flex-shrink: 0;
        }
        .success-card-body { flex: 1; min-width: 0; }
        .success-card-title { font-size: .95rem; font-weight: 700; color: #059669; }
        .success-card-sub { font-size: .8rem; color: #64748B; margin-top: 2px; }
        .success-card-txn {
            font-family: Consolas, 'Lucida Console', monospace;
            font-size: .75rem; font-weight: 700; letter-spacing: .04em;
            background: #F1F5F9; border: 1px solid #E2E8F0;
            padding: 4px 12px; border-radius: 20px;
            color: #334155; white-space: nowrap; flex-shrink: 0;
        }

        .eis-status-bar {
            width: 100%; padding: 10px 16px; border-radius: 8px;
            font-size: .82rem; font-weight: 500;
            border: 1px solid transparent;
            display: flex; align-items: flex-start; gap: 8px;
        }
        .eis-status-bar.success { background: #F0FDF4; border-color: #A7F3D0; color: #166534; }
        .eis-status-bar.warning { background: #FFFBEB; border-color: #FDE68A; color: #854D0E; }
        .eis-status-bar.danger  { background: #FEF2F2; border-color: #FECACA; color: #991B1B; }
        .eis-status-bar i { margin-top: 1px; flex-shrink: 0; }

        .receipt-container { padding: 0; }
        .receipt { box-shadow: 0 4px 24px rgba(0,0,0,.13); }

        .action-panel {
            width: 100%; background: #fff;
            border: 1px solid #E2E8F0; border-radius: 10px;
            padding: 16px 20px; box-shadow: 0 1px 3px rgba(0,0,0,.06);
            display: flex; flex-direction: column; gap: 14px;
        }
        .action-panel-label {
            font-size: .68rem; font-weight: 700;
            text-transform: uppercase; letter-spacing: .08em; color: #94A3B8;
            display: flex; align-items: center; gap: 6px;
        }
        .action-btns { display: flex; gap: 10px; flex-wrap: wrap; justify-content: center; }
        .action-printer { display: flex; align-items: center; gap: 10px; padding-top: 2px; border-top: 1px solid #F1F5F9; }
        .action-printer span { font-size: .8rem; font-weight: 500; color: #64748B; }
        .action-printer select {
            padding: 7px 10px; border: 1px solid #CBD5E1; border-radius: 6px;
            font-family: 'Inter', system-ui, sans-serif; font-size: .82rem;
            background: #F8FAFC; cursor: pointer; color: #1E293B;
        }
    </style>
    <link href="/IMS/assets/css/responsive.css" rel="stylesheet">
</head>
<body>

    <!-- ── Page Top Bar ────────────────────────────────── -->
    <div class="page-topbar no-print">
        <a href="create_sale.php" class="page-topbar-back">
            <i class="fas fa-arrow-left"></i> Back to POS
        </a>
        <div class="page-topbar-title">
            <i class="fas fa-receipt"></i> Sale Receipt
        </div>
        <div class="page-topbar-right">
            <?php if (!empty($saleData['eis_status'])): ?>
                <?php
                    $eisStatus = strtolower((string)$saleData['eis_status']);
                    $eisAlertClass = in_array($eisStatus, ['ready', 'submitted'], true) ? 'success' : (in_array($eisStatus, ['blocked', 'queued', 'offline'], true) ? 'warning' : 'danger');
                    $eisIcon = $eisAlertClass === 'success' ? 'check-circle' : ($eisAlertClass === 'warning' ? 'clock' : 'exclamation-circle');
                ?>
                <span class="eis-pill <?php echo htmlspecialchars($eisAlertClass); ?>">
                    <i class="fas fa-<?php echo $eisIcon; ?>"></i>
                    EIS <?php echo htmlspecialchars(strtoupper($eisStatus)); ?>
                </span>
            <?php endif; ?>
        </div>
    </div>

    <div class="page-shell">

    <!-- ── Success Card ────────────────────────────────── -->
    <?php
        $isViewMode = !empty($_GET['view']);
    ?>
    <div class="success-card no-print">
        <div class="success-card-icon"><i class="fas fa-<?php echo $isViewMode ? 'receipt' : ($isCreditReceipt ? 'credit-card' : 'check'); ?>"></i></div>
        <div class="success-card-body">
            <?php if ($isViewMode): ?>
            <div class="success-card-title">Sale Receipt</div>
            <div class="success-card-sub">Viewing receipt for this transaction</div>
            <?php elseif ($isCreditReceipt): ?>
            <div class="success-card-title">Credit Sale Recorded</div>
            <div class="success-card-sub">Sent for controller approval — balance due on account</div>
            <?php else: ?>
            <div class="success-card-title">Sale Recorded Successfully</div>
            <div class="success-card-sub">Transaction saved and receipt is ready to print</div>
            <?php endif; ?>
        </div>
        <div class="success-card-txn"><?php echo htmlspecialchars($saleData['transaction_id']); ?></div>
    </div>

    <!-- ── EIS Status Bar ──────────────────────────────── -->
    <?php if (!empty($saleData['eis_status'])): ?>
        <?php $eisBarIcon = $eisAlertClass === 'success' ? 'check-circle' : ($eisAlertClass === 'warning' ? 'exclamation-triangle' : 'times-circle'); ?>
        <div class="eis-status-bar <?php echo htmlspecialchars($eisAlertClass); ?> no-print">
            <i class="fas fa-<?php echo $eisBarIcon; ?>"></i>
            <span><strong>MRA EIS:</strong> <?php echo htmlspecialchars(strtoupper($eisStatus)); ?><?php if (!empty($saleData['eis_message'])): ?> &mdash; <?php echo htmlspecialchars($saleData['eis_message']); ?><?php endif; ?></span>
        </div>
    <?php endif; ?>

    <div class="receipt-container">
        <div class="receipt" id="receipt-content">
			
            <div class="receipt-header">
			<?php
				if ($branchId == "10"){
			?>
                <div class="company-logo">

                    <img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="<?php echo htmlspecialchars($companyName); ?> Logo">
                </div>
                <div class="company-info">
                    <p><?php echo nl2br(htmlspecialchars($branch['branch_address'] ?? '')); ?></p>
                    <p>Central Africa</p>
                    <p>Cell: +265 (0) 212 273 707</p>
                    <p>Cell: +265 (0) 888 737 654</p>
                    <p>TPIN: 307987774</p>
                </div>		

 <div class="company-contact">
                    <div class="contact-item website">
                        <i class="fas fa-globe"></i>
                        <span><?php echo htmlspecialchars(Branding::companyDetails()['website']); ?></span>
                    </div>
                    <div class="contact-item">
                        <i class="fas fa-envelope"></i>
                        <span><?php echo htmlspecialchars($branch['branch_email'] ?? ''); ?></span>
                    </div>
                </div>				
				<?php
				}else{
					?>
					
					<div class="company-logo">

                    <img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="<?php echo htmlspecialchars($companyName); ?> Logo">
                </div>
                <div class="company-info">
                    <p><?php echo nl2br(htmlspecialchars($branch['branch_address'] ?? '')); ?></p>
                    <p><?php echo htmlspecialchars($branch['branch_phone'] ?? ''); ?></p>
                </div>	
				
				 <div class="company-contact">
                    <div class="contact-item website">
                        <i class="fas fa-globe"></i>
                        <span><?php echo htmlspecialchars($branch['branch_website'] ?? ''); ?></span>
                    </div>
                 
                </div>
				
				<?php
				}
				?>


               

                <div class="transaction-info">
                    <p><span class="label">Transaction ID:</span> <span><?php echo htmlspecialchars($saleData['transaction_id']); ?></span></p>
                    <p><span class="label">Date:</span> <span><?php echo $formattedDate; ?></span></p>
                    <p><span class="label">Time:</span> <span><?php echo $formattedTime; ?></span></p>
                    <p><span class="label">Branch:</span> <span><?php echo htmlspecialchars($branch['branch_name'] ?? 'Main Branch'); ?></span></p>
                    <p><span class="label">Sales Rep:</span> <span><?php echo htmlspecialchars($salesRepName); ?></span></p>
                    <p><span class="label">Payment:</span> <span><?php echo htmlspecialchars($paymentMethodLabel, ENT_QUOTES, 'UTF-8'); ?></span></p>
                    <p><span class="label">Buyer Name:</span> <span><?php echo htmlspecialchars(($saleData['customer_name'] ?? '') ?: 'Walk-in customer', ENT_QUOTES, 'UTF-8'); ?></span></p>
                    <p><span class="label">Phone:</span> <span><?php echo htmlspecialchars(($saleData['customer_phone'] ?? '') ?: 'Not provided', ENT_QUOTES, 'UTF-8'); ?></span></p>
                    <p><span class='label'>Transaction Type:</span> <span><?php echo htmlspecialchars($eisTransactionType, ENT_QUOTES, 'UTF-8'); ?></span></p>
                    <p><span class='label'>Document:</span> <span><?php echo (($saleData['is_vat_registered'] ?? null) === true) ? 'TAX INVOICE' : 'SALE RECEIPT'; ?><?php if ($isReliefSupply): ?> — RELIEF SUPPLY<?php endif; ?></span></p>
                    <?php if ($isCreditReceipt): ?>
                    <p><span class='label'>Sale Type:</span> <span style="font-weight:900; letter-spacing:.04em;">*** CREDIT SALE ***</span></p>
                    <?php if ($creditNumber !== null): ?>
                    <p><span class='label'>Credit No:</span> <span><?php echo htmlspecialchars($creditNumber, ENT_QUOTES, 'UTF-8'); ?></span></p>
                    <?php endif; ?>
                    <?php endif; ?>
                    <?php if (($saleData['is_vat_registered'] ?? null) === false): ?>
                    <p><span class='label'>VAT Status:</span> <span>Not VAT Registered</span></p>
                    <?php elseif ($sellerTin !== ''): ?>
                    <p><span class='label'>Seller TPIN:</span> <span><?php echo htmlspecialchars($sellerTin, ENT_QUOTES, 'UTF-8'); ?></span></p>
                    <?php endif; ?>
                    <?php if ($isReliefSupply && $vat5CertNumber !== ''): ?>
                    <p><span class='label'>VAT-5 Cert:</span> <span><?php echo htmlspecialchars($vat5CertNumber, ENT_QUOTES, 'UTF-8'); ?></span></p>
                    <?php endif; ?>
                    <?php if ($isReliefSupply && $vat5ProjectNumber !== ''): ?>
                    <p><span class='label'>Project No:</span> <span><?php echo htmlspecialchars($vat5ProjectNumber, ENT_QUOTES, 'UTF-8'); ?></span></p>
                    <?php endif; ?>
                    <?php if (!empty($saleData['buyer_tin'])): ?>
                    <p><span class="label">Buyer TIN:</span> <span><?php echo htmlspecialchars($saleData['buyer_tin'], ENT_QUOTES, 'UTF-8'); ?></span></p>
                    <?php endif; ?>
                </div>
            </div>

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


            <div class="items-section">
                <div class="items-header">
                    <span>Item</span>
                    <span>Code</span>
                    <span>Price (MWK)</span>
                </div>

                <?php for ($i = 0; $i < $receiptItemCount; $i++): ?>
                <div class="item-row">
                    <div class="item-details">
                        <div class="item-name"><?php echo htmlspecialchars($itemNames[$i], ENT_QUOTES, 'UTF-8'); ?></div>
                        <?php if ($itemDetails[$i] !== ''): ?>
                            <div class="item-description"><?php echo htmlspecialchars($itemDetails[$i], ENT_QUOTES, 'UTF-8'); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="item-code"><?php echo htmlspecialchars($uniqueCodes[$i], ENT_QUOTES, 'UTF-8'); ?></div>
                    <div class="item-price"><?php echo number_format($receiptPrices[$i], 2); ?></div>
                </div>
                <?php endfor; ?>
            </div>

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


            <div class="totals-section">

                <?php if ($receiptDiscount > 0): ?>
                <div class="total-row subtotal">
                    <span class="label">Original Total:</span>
                    <span class="amount">MWK <?php echo number_format($receiptOriginalTotal, 2); ?></span>
                </div>
                <div class="total-row discount">
                    <span class="label">Discount (<?php echo $receiptDiscountPct; ?>%):</span>
                    <span class="amount">-MWK <?php echo number_format($receiptDiscount, 2); ?></span>
                </div>
                <?php endif; ?>

                <div class="total-row subtotal">
                    <span class="label">Subtotal:</span>
                    <span class="amount">MWK <?php echo number_format($saleData['subtotal'], 2); ?></span>
                </div>

                <?php if (($saleData['is_vat_registered'] ?? null) === false): ?>
                <div class="total-row vat">
                    <span class="label">Not VAT Registered</span>
                    <span class="amount"></span>
                </div>
                <?php elseif ($isReliefSupply): ?>
                <div class="total-row vat">
                    <span class="label">VAT (Relief — Exempt):</span>
                    <span class="amount">MWK <?php echo number_format($saleData['vat_amount'], 2); ?></span>
                </div>
                <?php else: ?>
                    <?php foreach ($eisTaxBreakdown as $bucket): ?>
                <div class="total-row vat">
                    <span class="label">VAT <?php echo htmlspecialchars($bucket['rateId']); ?>:</span>
                    <span class="amount">MWK <?php echo number_format($bucket['taxAmount'], 2); ?></span>
                </div>
                    <?php endforeach; ?>
                <?php endif; ?>

                <?php foreach ($eisLevyBreakdown as $levy): ?>
                <div class="total-row vat">
                    <span class="label">Levy <?php echo htmlspecialchars($levy['levyTypeId']); ?><?php if ($levy['levyRate'] > 0): ?> (<?php echo number_format($levy['levyRate'], 2); ?>%)<?php endif; ?>:</span>
                    <span class="amount">MWK <?php echo number_format($levy['levyAmount'], 2); ?></span>
                </div>
                <?php endforeach; ?>

                <div class="total-row grand-total">
                    <span class="label">TOTAL AMOUNT:</span>
                    <span class="amount">MWK <?php echo number_format($saleData['total'], 2); ?></span>
                </div>

                <?php if ($isCreditReceipt): ?>
                <div class="total-row" style="font-size:11px; margin-top:4px;">
                    <span class="label">Amount Paid:</span>
                    <span class="amount">MWK <?php echo number_format($receiptAmountPaid, 2); ?></span>
                </div>
                <div class="total-row grand-total" style="border-top:2px solid #000; border-bottom:2px solid #000; background:#fffde7;">
                    <span class="label">BALANCE DUE:</span>
                    <span class="amount">MWK <?php echo number_format($receiptCreditBalance, 2); ?></span>
                </div>
                <?php if (!empty($creditPayments)): ?>
                <div style="margin-top:8px;">
                    <div style="font-weight:900; font-size:11px; border-bottom:1px solid #000; padding-bottom:3px; margin-bottom:5px; text-transform:uppercase; letter-spacing:.04em;">Payment Record</div>
                    <?php foreach ($creditPayments as $pmt): ?>
                    <div class="total-row" style="font-size:10px;">
                        <span><?php echo htmlspecialchars(date('d/m/y', strtotime($pmt['payment_date'])), ENT_QUOTES, 'UTF-8'); ?> &mdash; <?php echo htmlspecialchars(paymentMethodLabel($pmt['payment_method']), ENT_QUOTES, 'UTF-8'); ?></span>
                        <span>MWK <?php echo number_format((float)$pmt['amount'], 2); ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
                <?php endif; ?>

             <!--   <div class="total-row">
                    <span class="label">Payment Method:</span>
                    <span class="amount"><?php echo htmlspecialchars($paymentMethodLabel, ENT_QUOTES, 'UTF-8'); ?></span>
                </div>

                <div class="total-row">
                    <span class="label">Amount Paid:</span>
                    <span class="amount">MWK <?php echo number_format($saleData['amount_paid'], 2); ?></span>
                </div>

                <div class="total-row">
                    <span class="label">Change:</span>
                    <span class="amount">MWK <?php echo number_format($saleData['change_due'], 2); ?></span>
                </div> -->
            </div>

         <!--   <div class="receipt-divider"></div> -->


            <?php if ($eisQrDataUri !== null): ?>
            <div class='eis-qr' style='text-align: center; margin: 12px 0;'>
                <img src='<?php echo htmlspecialchars($eisQrDataUri, ENT_QUOTES, 'UTF-8'); ?>' alt='MRA EIS invoice validation QR code' style='width: 34mm; height: 34mm;'>
                <p style='font-size: 9px; margin-top: 4px;'>Scan to validate this MRA EIS invoice</p>
                <?php if ($serverTime): ?>
                <p style='font-size: 8px; margin-top: 2px; color: #000;'>MRA Invoice Time: <?php echo htmlspecialchars($serverTime->format('d M Y H:i:s'), ENT_QUOTES, 'UTF-8'); ?></p>
                <?php endif; ?>
            </div>
            <?php endif; ?>
            <?php if ($eisOfflineQrDataUri !== null): ?>
            <div class='eis-qr' style='text-align: center; margin: 12px 0;'>
                <img src='<?php echo htmlspecialchars($eisOfflineQrDataUri, ENT_QUOTES, 'UTF-8'); ?>' alt='Signed offline MRA EIS receipt QR code' style='width: 34mm; height: 34mm;'>
            </div>
            <?php endif; ?>

            <div class="receipt-footer">
                <p class="thank-you">Thank you for your purchase!</p>
            </div>
        </div>
    </div>


    <!-- ── Action Panel ───────────────────────────────── -->
    <div class="action-panel no-print">
        <div class="action-panel-label"><i class="fas fa-bolt"></i> Actions</div>
        <div class="action-btns">
            <button class="btn btn-primary" onclick="printReceipt()">
                <i class="fas fa-print"></i> Print Receipt
            </button>
            <?php if (!empty($_GET['credit_id'])): ?>
            <a href="credit_sales.php?credit_id=<?php echo (int)$_GET['credit_id']; ?>" class="btn btn-success">
                <i class="fas fa-credit-card"></i> View Credit Account
            </a>
            <?php endif; ?>
            <a href="create_sale.php" class="btn <?php echo empty($_GET['credit_id']) ? 'btn-success' : 'btn-secondary'; ?>">
                <i class="fas fa-plus"></i> New Sale
            </a>
            <a href="../../dashboard/branch.php" class="btn btn-secondary">
                <i class="fas fa-home"></i> Dashboard
            </a>
        </div>
        <div class="action-printer">
            <span><i class="fas fa-print" style="color:#94A3B8;font-size:.75rem;margin-right:4px;"></i> Paper Width:</span>
            <select id='printer-size' aria-label='Receipt printer paper width'>
                <option value='30'>30 mm</option>
                <option value='40'>40 mm</option>
                <option value='50'>50 mm</option>
                <option value='80' selected>80 mm</option>
            </select>
        </div>
    </div>

    </div><!-- /.page-shell -->

    <script>

        const receiptPrinterSizes = {
            '30': { width: 30, padding: 1, font: 7, detailFont: 7, logo: 26, qr: 20, gap: 1 },
            '40': { width: 40, padding: 1.5, font: 8, detailFont: 8, logo: 34, qr: 25, gap: 2 },
            '50': { width: 50, padding: 2, font: 9, detailFont: 9, logo: 42, qr: 30, gap: 3 },
            '80': { width: 80, padding: 3, font: 12, detailFont: 11, logo: 60, qr: 34, gap: 6 }
        };

        function selectedPrinterSize() {
            const selector = document.getElementById('printer-size');
            return receiptPrinterSizes[selector ? selector.value : '80'] || receiptPrinterSizes['80'];
        }

        function applyPrinterSize() {
            const size = selectedPrinterSize();
            const receipt = document.getElementById('receipt-content');
            if (!receipt) return;
            receipt.style.setProperty('--receipt-paper-width', size.width + 'mm');
            receipt.style.setProperty('--receipt-padding', size.padding + 'mm');
            receipt.dataset.printerWidth = String(size.width);
        }

        function isHandheldPrintContext() {
            return window.matchMedia('(max-width: 768px)').matches
                || (navigator.maxTouchPoints > 0 && window.innerWidth <= 1024);
        }

        function printCurrentReceipt() {
            applyPrinterSize();
            window.print();
        }

        function waitForPrintAssets(printWindow) {
            const images = Array.from(printWindow.document.images || []);
            const imagePromises = images.map((img) => {
                if (img.complete) {
                    return Promise.resolve();
                }

                return new Promise((resolve) => {
                    img.addEventListener('load', resolve, { once: true });
                    img.addEventListener('error', resolve, { once: true });
                });
            });

            const fontPromise = printWindow.document.fonts && printWindow.document.fonts.ready
                ? printWindow.document.fonts.ready
                : Promise.resolve();

            return Promise.all([fontPromise, ...imagePromises]);
        }

        function printReceipt() {
            if (isHandheldPrintContext()) {
                printCurrentReceipt();
                return;
            }

            const printWindow = window.open('', '_blank');
            if (!printWindow) {
                printCurrentReceipt();
                return;
            }
            const size = selectedPrinterSize();
            const receiptContent = document.getElementById('receipt-content').outerHTML;

            printWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Sale Receipt</title>
                    <style>
                        body {
                            margin: 0;
                            padding: 0;
                            font-family: Consolas, 'Lucida Console', 'Courier New', monospace;
                            background: white;
                        }
                        .receipt {
                            width: ${size.width}mm;
                            max-width: ${size.width}mm;
                            padding: ${size.padding}mm;
                            box-sizing: border-box;
                            overflow: hidden;
                            font-size: ${size.font}px;
                            line-height: 1.15;
                            text-align: center;
                                                    color: #000;
                            font-weight: 700;
                            text-rendering: geometricPrecision;
                            -webkit-font-smoothing: none;
                            print-color-adjust: exact;
                            -webkit-print-color-adjust: exact;
                        }
                        .receipt, .receipt * { color: #000; }
                        .company-info h2 { font-size: ${size.font + 2}px; margin: 0 0 2px 0; text-transform: uppercase; }
                        .company-info p { margin: 0; font-size: ${size.detailFont}px; overflow-wrap: anywhere; color: #000; font-weight: 700; }
                        .company-logo { text-align: center; }
                        .company-logo img { width: 100%; max-width: 100%; height: auto; display: block; object-fit: contain; }
                        .company-logo .logo-placeholder { font-size: 30px; margin-bottom: 0; }
                        .company-info { margin-top: 0; }
                        .company-contact { margin: 1mm 0; font-size: ${size.detailFont}px; overflow-wrap: anywhere; }
                        .company-contact .contact-item { display: flex; align-items: center; justify-content: center; gap: 4px; margin: 0; line-height: 1.1; }
                        .company-contact .contact-item i { font-size: 8px; width: 12px; text-align: center; }
                        .company-contact .website { }
                        .receipt-divider { border-top: 1px dashed #000; margin: 2mm 0; }
                        .transaction-info p { display: flex; justify-content: space-between; gap: 2px; margin: 0; font-size: ${size.detailFont}px; line-height: 1.15; overflow-wrap: anywhere; color: #000; font-weight: 700; }
                        .items-header { display: grid; grid-template-columns: 1.5fr 1fr 1.1fr; gap: ${size.gap}px; font-size: ${size.detailFont}px; font-weight: 900; border-bottom: 1px solid #000; padding-bottom: 3px; margin-bottom: 4px; }
                        .item-row { display: grid; grid-template-columns: 1.5fr 1fr 1.1fr; gap: ${size.gap}px; align-items: start; margin-bottom: 4px; overflow-wrap: anywhere; }
                        .item-details { margin-bottom: 4px; }
                        .item-name { font-weight: 800; font-size: ${size.detailFont}px; color: #000; }
                        .item-description { margin-top: 1px; font-size: ${Math.max(6, size.detailFont - 1)}px; line-height: 1.2; color: #000; overflow-wrap: anywhere; }
                        .item-code { font-weight: 800; font-size: ${size.detailFont}px; text-align: center; color: #000; }
                        .item-price { font-size: ${size.detailFont}px; text-align: right; font-weight: 800; overflow-wrap: anywhere; color: #000; }
                        .total-row { display: flex; justify-content: space-between; gap: 3px; margin-bottom: 3px; font-size: ${size.detailFont}px; }
                        .total-row .amount { text-align: right; overflow-wrap: anywhere; }
                        .total-row.discount { color: #000; font-size: ${size.detailFont}px; font-weight: 800; }
                        .total-row.grand-total { font-weight: 900; font-size: ${size.font + 1}px; border-top: 2px solid #000; border-bottom: 1px solid #000; padding: 4px 0; margin: 5px 0; }
                        .eis-qr img { width: ${size.qr}mm !important; height: ${size.qr}mm !important; max-width: 100%; }
                        .eis-qr p { font-size: ${Math.max(6, size.detailFont)}px !important; }
                        .receipt-footer { text-align: center; font-size: ${size.detailFont}px; margin-top: 8px; border-top: 1px dashed #000; padding-top: 6px; }
                        .thank-you { font-weight: 900; font-size: ${size.detailFont}px; margin-bottom: 5px; }
                        .warranty-info { font-size: ${Math.max(7, size.detailFont)}px; color: #000; margin-top: 8px; line-height: 1.2; font-weight: 900; }

                        .paper-30 .receipt, .paper-40 .receipt { line-height: 1.15; }
                        .paper-30 .receipt-header, .paper-40 .receipt-header { margin-bottom: 2mm; padding-bottom: 1.5mm; }
                        .paper-30 .company-contact .contact-item, .paper-40 .company-contact .contact-item { display: block; overflow-wrap: anywhere; }
                        .paper-30 .transaction-info, .paper-40 .transaction-info { margin-top: 1mm; padding-top: 1mm; }
                        .paper-30 .transaction-info p, .paper-40 .transaction-info p { align-items: start; }
                        .paper-30 .transaction-info .label, .paper-40 .transaction-info .label { flex: 0 0 auto; }

                        .paper-30 .items-header, .paper-40 .items-header { display: none; }
                        .paper-30 .item-row, .paper-40 .item-row {
                            display: grid;
                            grid-template-columns: minmax(0, 1fr) auto;
                            grid-template-areas: 'name name' 'code price';
                            gap: 2px 4px;
                            margin-bottom: 1.5mm;
                            padding-bottom: 1mm;
                            border-bottom: 1px dotted #000;
                        }
                        .paper-30 .item-details, .paper-40 .item-details { grid-area: name; margin: 0; text-align: left; }
                        .paper-30 .item-code, .paper-40 .item-code { grid-area: code; text-align: left; }
                        .paper-30 .item-price, .paper-40 .item-price { grid-area: price; text-align: right; }
                        .paper-30 .item-code::before, .paper-40 .item-code::before { content: 'Code: '; font-weight: 700; }
                        .paper-30 .item-price::before, .paper-40 .item-price::before { content: 'MWK '; font-weight: 700; }
                        .paper-30 .totals-section, .paper-40 .totals-section { margin-top: 2mm; padding-top: 1.5mm; }
                        .paper-30 .total-row, .paper-40 .total-row { align-items: start; }
                        .paper-30 .total-row .label, .paper-40 .total-row .label { text-align: left; }
                        .paper-30 .total-row .amount, .paper-40 .total-row .amount { max-width: 55%; }

                        .paper-50 .items-header, .paper-50 .item-row {
                            grid-template-columns: 1.5fr 1fr 1.1fr;
                            gap: 3px;
                        }
                        .paper-50 .receipt-header { margin-bottom: 2.5mm; padding-bottom: 2mm; }
                        .paper-80 .receipt { line-height: 1.25; }
                        .paper-80 .items-header, .paper-80 .item-row { grid-template-columns: 2fr 1fr 1fr; }
                        @page { margin: 0; size: ${size.width}mm auto; }
                    </style>
</head>
                <body class=paper-${size.width}>
                    ${receiptContent}
                </body>
                </html>
            `);

            printWindow.document.close();

            waitForPrintAssets(printWindow).finally(() => {
                printWindow.focus();
                setTimeout(() => {
                    printWindow.print();
                    setTimeout(() => printWindow.close(), 500);
                }, 100);
            });
        }
        document.addEventListener('DOMContentLoaded', function() {

            const printerSize = document.getElementById('printer-size');
            const savedSize = localStorage.getItem('receiptPrinterWidth');
            if (printerSize && receiptPrinterSizes[savedSize]) {
                printerSize.value = savedSize;
            }
            applyPrinterSize();

            if (printerSize) {
                printerSize.addEventListener('change', function() {
                    localStorage.setItem('receiptPrinterWidth', this.value);
                    applyPrinterSize();
                });
            }

            document.addEventListener('keydown', function(e) {
                if (e.ctrlKey && e.key === 'p') {
                    e.preventDefault();
                    printReceipt();
                }
            });

            // Auto-print: skip when viewing a past receipt (?view=1)
            <?php if (empty($_GET['view'])): ?>
            var fontReady = (document.fonts && document.fonts.ready) ? document.fonts.ready : Promise.resolve();
            var imgReady = Array.from(document.images).map(function(img) {
                if (img.complete) return Promise.resolve();
                return new Promise(function(r) {
                    img.addEventListener('load', r, { once: true });
                    img.addEventListener('error', r, { once: true });
                });
            });
            Promise.all([fontReady].concat(imgReady)).then(function() {
                printCurrentReceipt();
            });
            <?php endif; ?>
        });
    </script>
</body>
</html>

<?php

?>
