<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();
$companyLogo = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../classes/LoanLaybuy.php';
require_once __DIR__ . '/../../classes/Laybuy.php';

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

$branchObj = new Branch($conn);
$auth = new Auth($conn);
$loanLaybuy = new LoanLaybuy($conn);
$laybuyPayment = new Laybuy($conn);

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


$recordId = isset($_GET['record_id']) ? (int)$_GET['record_id'] : null;
if (!$recordId) {
    header('Location: laybuy_and_loans.php?error=' . urlencode('No lay-buy data found.'));
    exit();
}

$recordData = $loanLaybuy->getLoanLaybuyById($recordId);
if (!$recordData) {
    header('Location: laybuy_and_loans.php?error=' . urlencode('Lay-buy not found.'));
    exit();
}


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

$branch = $branchObj->getBranchById($recordData['branch_id'] ?? 0) ?: [];
$branchBranding = Branding::documentDetailsForBranch($branch);
$companyName = $branchBranding['name'];
$companyLogo = $branchBranding['logo'];
$companyLogoFile = $branchBranding['logo_file'];

$dateTime = new DateTime($recordData['created_at']);
$formattedDate = $dateTime->format('d M Y');
$formattedTime = $dateTime->format('g:i A');
$validUntil = new DateTime($recordData['valid_until']);
$formattedValidUntil = $validUntil->format('d M Y');


$now = new DateTime();
$status = $now > $validUntil ? 'expired' : ($recordData['status'] ?? 'pending');
$statusColors = [
    'expired'   => ['bg' => '#FEE2E2', 'fg' => '#991B1B'],
    'approved'  => ['bg' => '#DCFCE7', 'fg' => '#166534'],
    'completed' => ['bg' => '#DBEAFE', 'fg' => '#1E40AF'],
    'pending'   => ['bg' => '#FEF9C3', 'fg' => '#854D0E'],
];
$statusColor = $statusColors[$status] ?? $statusColors['pending'];

$totalAmount = round((float)($recordData['amount'] ?? 0), 2);
$totalPaid = round((float)($recordData['total_paid'] ?? 0), 2);
$balance = max(0, round($totalAmount - $totalPaid, 2));

$payments = $laybuyPayment->getPaymentDetails($recordId) ?: [];

$companyDetails = $branchBranding;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars(Branding::pageTitle('Laybuy 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;
            color: #1E293B;
            -webkit-font-smoothing: antialiased;
        }

        /* ── 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; }
        .method-pill {
            font-size: .67rem; font-weight: 700; letter-spacing: .04em;
            padding: 3px 10px; border-radius: 20px; text-transform: uppercase;
            background: rgba(79,70,229,.18); color: #C7D2FE;
        }

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

        /* ── Receipt (screen preview) ────────────────── */
        .receipt-container { display: flex; justify-content: center; padding: 0; width: 100%; }

        .receipt {
            width: var(--receipt-width, 80mm);
            max-width: 100%;
            background: #fff;
            padding: var(--receipt-padding, 4mm);
            box-shadow: 0 4px 24px rgba(0,0,0,.13);
            box-sizing: border-box;
            color: #000;
            animation: slideUp .5s ease-out;
        }
        @keyframes slideUp { from { opacity: 0; transform: translateY(24px); } to { opacity: 1; transform: translateY(0); } }

        /* Thermal (80mm / 50mm) look */
        .receipt[data-size='80'],
        .receipt[data-size='50'] {
            font-family: Consolas, 'Lucida Console', 'Courier New', monospace;
            font-weight: 700;
            border: 1px solid #000;
        }
        .receipt[data-size='50'] { font-size: 9px; }
        .receipt[data-size='80'] { font-size: 12px; }

        /* A4 (full invoice) look */
        .receipt[data-size='a4'] {
            font-family: 'Inter', system-ui, sans-serif;
            font-size: 14px;
            border: 1px solid #E2E8F0;
        }

        .receipt-header { text-align: center; margin-bottom: 12px; padding-bottom: 10px; border-bottom: 1px dashed #000; }
        .receipt[data-size='a4'] .receipt-header { border-bottom: 2px solid #1E293B; }
        .company-logo img { width: 100%; max-width: 220px; height: auto; display: inline-block; margin-bottom: 6px; }
        .receipt[data-size='80'] .company-logo img, .receipt[data-size='50'] .company-logo img { max-width: 100%; }
        .company-info h2 { font-size: 1.3em; font-weight: 900; text-transform: uppercase; margin-bottom: 2px; }
        .company-info p { font-size: .82em; line-height: 1.3; margin: 0; }
        .receipt-doc-title {
            font-weight: 900; letter-spacing: .06em; text-transform: uppercase;
            font-size: 1.05em; margin-top: 8px;
        }

        .receipt-info {
            display: flex; justify-content: space-between; gap: 10px;
            margin: 12px 0; padding-bottom: 10px; border-bottom: 1px dashed #000;
        }
        .receipt[data-size='a4'] .receipt-info { border-bottom: 1px solid #E2E8F0; }
        .receipt-info-column { flex: 1; min-width: 0; }
        .receipt-info p { display: flex; justify-content: space-between; gap: 6px; font-size: .84em; line-height: 1.5; margin: 0; overflow-wrap: anywhere; }
        .receipt-info .label { font-weight: 700; opacity: .75; flex-shrink: 0; }
        .status-badge {
            display: inline-block; font-size: .78em; font-weight: 700; text-transform: uppercase;
            padding: 2px 8px; border-radius: 20px; letter-spacing: .03em;
            background: <?php echo $statusColor['bg']; ?>; color: <?php echo $statusColor['fg']; ?>;
        }

        .receipt-table { width: 100%; border-collapse: collapse; margin-bottom: 12px; font-size: .86em; }
        .receipt-table th, .receipt-table td { padding: 6px 4px; text-align: left; }
        .receipt-table th { border-bottom: 1px solid #000; font-weight: 800; text-transform: uppercase; font-size: .85em; }
        .receipt[data-size='a4'] .receipt-table th { border-bottom: 2px solid #1E293B; }
        .receipt-table td { border-bottom: 1px dotted #999; }
        .receipt-table .num { text-align: right; }

        .totals-section { margin-top: 6px; padding-top: 8px; border-top: 1px dashed #000; }
        .receipt[data-size='a4'] .totals-section { border-top: 1px solid #E2E8F0; }
        .total-row { display: flex; justify-content: space-between; font-size: .88em; margin-bottom: 4px; }
        .total-row .label { font-weight: 600; }
        .total-row.grand-total {
            font-weight: 900; font-size: 1.05em;
            border-top: 2px solid #000; border-bottom: 1px solid #000;
            padding: 6px 0; margin: 6px 0;
        }
        .total-row.balance-due { background: #FFFDE7; padding: 4px 6px; border-radius: 4px; font-weight: 800; }

        .payments-section { margin-top: 10px; padding-top: 8px; border-top: 1px dashed #000; }
        .receipt[data-size='a4'] .payments-section { border-top: 1px solid #E2E8F0; }
        .payments-section h5 { font-size: .84em; text-transform: uppercase; letter-spacing: .04em; margin-bottom: 4px; }
        .payments-table { width: 100%; border-collapse: collapse; font-size: .82em; }
        .payments-table th, .payments-table td { padding: 4px; text-align: left; }
        .payments-table th { border-bottom: 1px solid #000; font-weight: 800; text-transform: uppercase; font-size: .82em; }
        .receipt[data-size='a4'] .payments-table th { border-bottom: 2px solid #1E293B; }
        .payments-table td { border-bottom: 1px dotted #999; }
        .payments-table .num { text-align: right; }
        .payments-table tfoot td { border-bottom: none; border-top: 1px solid #000; font-weight: 800; }

        .receipt-notes {
            margin-top: 12px; padding: 8px 10px; background: #F8FAFC;
            border-radius: 4px; font-size: .82em; line-height: 1.4;
        }
        .receipt[data-size='80'] .receipt-notes, .receipt[data-size='50'] .receipt-notes { background: transparent; border: 1px dashed #000; }
        .receipt-notes h5 { font-size: .84em; text-transform: uppercase; letter-spacing: .04em; margin-bottom: 3px; }

        .receipt-validity { margin-top: 10px; font-size: .78em; font-style: italic; opacity: .8; }

        .receipt-footer { text-align: center; margin-top: 14px; padding-top: 10px; border-top: 1px dashed #000; font-size: .8em; }
        .receipt[data-size='a4'] .receipt-footer { border-top: 1px solid #E2E8F0; }
        .receipt-footer .thank-you { font-weight: 800; margin-bottom: 4px; }

        /* ── Action panel ─────────────────────────────── */
        .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; }
        .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;
        }
        .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; }
        .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;
        }

        @media (max-width: 768px) {
            .action-btns { flex-direction: column; }
            .btn { width: 100%; justify-content: center; }
            .page-shell { padding: 14px 10px; }
        }

        @media print {
            .no-print { display: none !important; }
            body { background: #fff; margin: 0; padding: 0; }
            .page-shell { padding: 0; }
            .receipt { box-shadow: none; }
        }
    </style>
    <link href="/IMS/assets/css/responsive.css" rel="stylesheet">
</head>
<body>

    <div class="page-topbar no-print">
        <a href="laybuy_and_loans.php?branch_id=<?php echo (int)($recordData['branch_id'] ?? 0); ?>" class="page-topbar-back">
            <i class="fas fa-arrow-left"></i> Back to List
        </a>
        <div class="page-topbar-title">
            <i class="fas fa-receipt"></i> Laybuy Receipt
        </div>
        <div class="method-pill"><?php echo htmlspecialchars(strtoupper($status)); ?></div>
    </div>

    <div class="page-shell">

        <div class="receipt-container">
            <div class="receipt" id="receipt-content" data-size="80">
                <div class="receipt-header">
                    <div class="company-logo">
                        <img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="<?php echo htmlspecialchars($companyName); ?> Logo">
                    </div>
                    <div class="company-info">
                        <h2><?php echo htmlspecialchars($companyDetails['name']); ?></h2>
                        <p><?php echo htmlspecialchars($branch['branch_address'] ?? $companyDetails['address']); ?></p>
                        <p><?php echo htmlspecialchars($branch['branch_phone'] ?? $companyDetails['phone']); ?></p>
                        <p><?php echo htmlspecialchars($branch['branch_email'] ?? $companyDetails['email']); ?> &middot; <?php echo htmlspecialchars($branch['branch_website'] ?? $companyDetails['website']); ?></p>
                    </div>
                    <div class="receipt-doc-title">LAYBUY RECEIPT</div>
                </div>

                <div class="receipt-info">
                    <div class="receipt-info-column">
                        <p><span class="label">Record #:</span> <span><?php echo htmlspecialchars($recordData['record_number'] ?? $recordData['record_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'] ?? 'N/A'); ?></span></p>
                        <p><span class="label">Prepared By:</span> <span><?php echo htmlspecialchars($creatorName); ?></span></p>
                    </div>
                    <div class="receipt-info-column">
                        <p><span class="label">Customer:</span> <span><?php echo htmlspecialchars($recordData['customer_name'] ?? ''); ?></span></p>
                        <p><span class="label">Contact:</span> <span><?php echo htmlspecialchars($recordData['customer_contact'] ?? ''); ?></span></p>
                        <p><span class="label">Valid Until:</span> <span><?php echo $formattedValidUntil; ?></span></p>
                        <p><span class="label">Status:</span> <span class="status-badge"><?php echo ucfirst($status); ?></span></p>
                    </div>
                </div>

                <table class="receipt-table">
                    <thead>
                        <tr>
                            <th>Item</th>
                            <th class="num">Amount (MWK)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><?php echo htmlspecialchars($recordData['item_name'] ?? ''); ?></td>
                            <td class="num"><?php echo number_format($totalAmount, 2); ?></td>
                        </tr>
                    </tbody>
                </table>

                <div class="totals-section">
                    <div class="total-row">
                        <span class="label">Total Amount:</span>
                        <span class="amount">MWK <?php echo number_format($totalAmount, 2); ?></span>
                    </div>
                    <div class="total-row">
                        <span class="label">Total Paid:</span>
                        <span class="amount">MWK <?php echo number_format($totalPaid, 2); ?></span>
                    </div>
                    <div class="total-row grand-total balance-due">
                        <span class="label">Balance Due:</span>
                        <span class="amount">MWK <?php echo number_format($balance, 2); ?></span>
                    </div>
                </div>

                <?php if (!empty($payments)): ?>
                <div class="payments-section">
                    <h5>Payment History (<?php echo count($payments); ?> transaction<?php echo count($payments) === 1 ? '' : 's'; ?>)</h5>
                    <table class="payments-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Payment Option</th>
                                <th class="num">Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($payments as $payment): ?>
                            <tr>
                                <td><?php echo htmlspecialchars((new DateTime($payment['payment_date']))->format('d M Y')); ?></td>
                                <td><?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $payment['payment_method'] ?? 'cash'))); ?></td>
                                <td class="num"><?php echo number_format((float)($payment['body_amount'] ?? 0), 2); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="2">Total Paid</td>
                                <td class="num">MWK <?php echo number_format($totalPaid, 2); ?></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
                <?php endif; ?>

                <div class="receipt-notes">
                    <h5>Notes</h5>
                    <p><?php echo htmlspecialchars($recordData['notes'] ?? 'No additional notes provided.'); ?></p>
                </div>

                <div class="receipt-validity">
                    <p>This lay-buy is valid until <?php echo $formattedValidUntil; ?>.</p>
                </div>

                <div class="receipt-footer">
                    <p class="thank-you">Thank you for your business!</p>
                    <p>Contact us at <?php echo htmlspecialchars($companyDetails['phone']); ?> for any inquiries.</p>
                </div>
            </div>
        </div>

        <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="openReceiptPreview()">
                    <i class="fas fa-print"></i> Preview &amp; Print
                </button>
                <a href="generate_loan_laybuy_pdf.php?record_id=<?php echo $recordId; ?>" class="btn btn-secondary">
                    <i class="fas fa-download"></i> Download PDF
                </a>
                <a href="send_loan_laybuy_email.php?record_id=<?php echo $recordId; ?>" class="btn btn-success">
                    <i class="fas fa-envelope"></i> Email Receipt
                </a>
                <?php if (($recordData['branch_id'] ?? null) == $auth->getUserBranch($_SESSION['user_id'])): ?>
                <a href="edit_loan_or_laybuy.php?record_id=<?php echo $recordId; ?>" class="btn btn-secondary">
                    <i class="fas fa-edit"></i> Edit Record
                </a>
                <?php endif; ?>
            </div>
            <div class="action-printer">
                <span><i class="fas fa-print" style="color:#94A3B8;font-size:.75rem;margin-right:4px;"></i> Paper Size:</span>
                <select id="printer-size" aria-label="Receipt paper size">
                    <option value="80" selected>80 mm (Thermal)</option>
                    <option value="50">50 mm (Thermal)</option>
                    <option value="a4">A4 (Full Page)</option>
                </select>
            </div>
        </div>

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

    <script>
        const receiptPaperSizes = {
            '50': { width: '50mm', padding: '2mm' },
            '80': { width: '80mm', padding: '4mm' },
            'a4': { width: '190mm', padding: '15mm' }
        };

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

        function applyPaperSize() {
            const key = selectedPaperSize();
            const size = receiptPaperSizes[key] || receiptPaperSizes['80'];
            const receipt = document.getElementById('receipt-content');
            if (!receipt) return;
            receipt.style.setProperty('--receipt-width', size.width);
            receipt.style.setProperty('--receipt-padding', size.padding);
            receipt.dataset.size = key;
        }

        function openReceiptPreview() {
            applyPaperSize();
            const key = selectedPaperSize();
            const size = receiptPaperSizes[key] || receiptPaperSizes['80'];
            const isA4 = key === 'a4';
            const docTitle = isA4 ? 'Laybuy Invoice' : 'Laybuy Receipt';
            const receiptContent = document.getElementById('receipt-content').outerHTML;
            const baseStyles = document.querySelector('style').outerHTML;
            const faLink = document.querySelector('link[href*="font-awesome"]');
            const faLinkHtml = faLink ? faLink.outerHTML : '';

            const previewWindow = window.open('', '_blank');
            if (!previewWindow) {
                window.print();
                return;
            }

            previewWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <meta charset="UTF-8">
                    <title>${docTitle} Preview</title>
                    ${faLinkHtml}
                    ${baseStyles}
                    <style>
                        body { margin: 0; padding: 0; background: #E2E8F0; }
                        .preview-toolbar {
                            position: sticky; top: 0; z-index: 10;
                            background: #0F172A; color: #fff;
                            display: flex; align-items: center; justify-content: space-between;
                            padding: 12px 20px; box-shadow: 0 2px 8px rgba(0,0,0,.15);
                            font-family: 'Inter', system-ui, sans-serif;
                        }
                        .preview-toolbar-title { font-size: .88rem; font-weight: 700; display: flex; align-items: center; gap: 8px; }
                        .preview-toolbar-actions { display: flex; gap: 10px; }
                        .preview-toolbar button {
                            font-family: 'Inter', system-ui, sans-serif; font-size: .82rem; font-weight: 600;
                            padding: 8px 16px; border-radius: 7px; border: none; cursor: pointer;
                            display: inline-flex; align-items: center; gap: 6px; transition: background .15s;
                        }
                        .preview-print-btn { background: #4F46E5; color: #fff; }
                        .preview-print-btn:hover { background: #3730A3; }
                        .preview-close-btn { background: rgba(255,255,255,.1); color: #E2E8F0; border: 1px solid rgba(255,255,255,.15) !important; }
                        .preview-close-btn:hover { background: rgba(255,255,255,.18); }
                        .preview-body { padding: 28px 16px 60px; display: flex; justify-content: center; }
                        .receipt-container { padding: 0; }
                        .receipt {
                            width: ${size.width} !important;
                            max-width: ${size.width} !important;
                            padding: ${size.padding} !important;
                            margin: 0 auto;
                        }
                        @media print {
                            body { background: #fff; }
                            .preview-body { padding: 0; }
                            .receipt { box-shadow: none !important; }
                        }
                        @page { margin: ${isA4 ? '10mm' : '0'}; size: ${isA4 ? 'A4' : size.width + ' auto'}; }
                    </style>
                </head>
                <body>
                    <div class="preview-toolbar no-print">
                        <div class="preview-toolbar-title"><i class="fas fa-file-alt"></i> ${docTitle} Preview &mdash; ${isA4 ? 'A4' : key + 'mm'}</div>
                        <div class="preview-toolbar-actions">
                            <button class="preview-print-btn" onclick="window.print()"><i class="fas fa-print"></i> Print</button>
                            <button class="preview-close-btn" onclick="window.close()"><i class="fas fa-times"></i> Close</button>
                        </div>
                    </div>
                    <div class="preview-body">
                        <div class="receipt-container">${receiptContent}</div>
                    </div>
                </body>
                </html>
            `);
            previewWindow.document.close();
            previewWindow.focus();
        }

        document.addEventListener('DOMContentLoaded', function () {
            const printerSize = document.getElementById('printer-size');
            const savedSize = localStorage.getItem('laybuyReceiptPaperSize');
            if (printerSize && receiptPaperSizes[savedSize]) {
                printerSize.value = savedSize;
            }
            applyPaperSize();

            <?php if (isset($_GET['print'])): ?>
            openReceiptPreview();
            <?php endif; ?>

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

            document.addEventListener('keydown', function (e) {
                if (e.ctrlKey && e.key === 'p') {
                    e.preventDefault();
                    openReceiptPreview();
                }
            });
        });
    </script>
</body>
</html>
