<?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__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Order.php';
require_once __DIR__ . '/../../includes/payment_options.php';

$database = new Database();
$conn     = $database->getConnection();
$auth     = new Auth($conn);
$orderObj = new Order($conn);

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

$orderId = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;
$order   = $orderObj->getOrderById($orderId);

if (!$order) {
    header('Location: list_orders.php?error=' . urlencode('Order not found.'));
    exit();
}

$isSuperAdmin = $auth->isSuperAdmin($_SESSION['user_id']);
$userBranchId = $auth->getUserBranch($_SESSION['user_id']);
if (!$isSuperAdmin && (int)$userBranchId !== (int)$order['branch_id']) {
    header('Location: list_orders.php?error=' . urlencode('Access denied.'));
    exit();
}
$orderBranding = Branding::documentDetailsForBranchId($conn, (int)$order['branch_id']);
$companyName = $orderBranding['name'];
$companyLogo = $orderBranding['logo'];
$companyLogoFile = $orderBranding['logo_file'];

// Orders that aren't completed yet have no assigned code — print a payment
// statement instead of a full receipt (no code banner, no "completed by" line).
$isCompleted = !empty($order['assigned_code']);

$payments  = $orderObj->getPayments($orderId);
$totalPaid = $orderObj->getTotalPaid($orderId);
$price     = round((float)$order['price'], 2);
$balance   = round($price - $totalPaid, 2);
$isFullyPaid = $balance <= 0.009;

// Completer name (completed orders only)
$completerName = 'N/A';
if ($isCompleted && !empty($order['completed_by'])) {
    $stmt = $conn->prepare("SELECT username FROM users WHERE user_id = :id");
    $stmt->execute([':id' => (int)$order['completed_by']]);
    $completerName = $stmt->fetchColumn() ?: 'N/A';
}

// Unique reference: combines order number + assigned code suffix once completed,
// otherwise a stable suffix from the order id/number alone so an in-progress
// statement still has a printable reference.
$receiptCode = $isCompleted
    ? strtoupper($order['order_number'] . '-' . substr(md5($order['assigned_code'] . $orderId), 0, 6))
    : strtoupper($order['order_number'] . '-' . substr(md5('STMT' . $orderId), 0, 6));

$docLabel = $isCompleted ? 'Order Receipt' : 'Payment Statement';
?>
<!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($docLabel . ' – ' . $order['order_number'])); ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap');

        *, *::before, *::after { box-sizing: border-box; }
        :root {
            --brand:          #4F46E5;
            --brand-dark:     #3730A3;
            --brand-light:    #EEF2FF;
            --success:        #059669;
            --success-bg:     #ECFDF5;
            --danger:         #DC2626;
            --danger-bg:      #FEF2F2;
            --n900: #0F172A; --n800: #1E293B; --n700: #334155; --n600: #475569;
            --n500: #64748B; --n400: #94A3B8; --n300: #CBD5E1; --n200: #E2E8F0;
            --n100: #F1F5F9; --n50:  #F8FAFC; --white: #FFFFFF;
            --r-sm: 6px; --r: 10px; --r-lg: 14px;
        }

        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background: var(--n100);
            padding: 28px 16px;
            color: var(--n800);
            -webkit-font-smoothing: antialiased;
        }
        .receipt-wrapper { max-width: 820px; margin: 0 auto; }

        .receipt-card {
            background: var(--white);
            border-radius: var(--r-lg);
            box-shadow: 0 1px 3px rgba(0,0,0,.06), 0 12px 32px rgba(15,23,42,.08);
            overflow: hidden;
            border: 1px solid var(--n200);
        }

        /* ---- Letterhead ---- */
        .receipt-header {
            padding: 32px 40px 24px;
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 20px;
            border-bottom: 3px solid var(--brand);
        }
        .company-block .company-name {
            font-size: 1.4rem;
            font-weight: 800;
            color: var(--n900);
            letter-spacing: -.01em;
        }
        .company-block .company-tagline { font-size: .74rem; color: var(--n500); margin-top: 5px; line-height: 1.6; max-width: 380px; }
        .company-block .company-details { font-size: .72rem; color: var(--n400); margin-top: 10px; line-height: 1.8; }
        .receipt-title-block { text-align: right; flex-shrink: 0; }
        .receipt-title-block .receipt-label {
            display: inline-block;
            background: var(--brand);
            color: #fff;
            padding: 6px 16px;
            border-radius: 20px;
            font-weight: 700;
            font-size: .78rem;
            text-transform: uppercase;
            letter-spacing: .06em;
        }
        .receipt-title-block .order-num {
            display: block;
            color: var(--n600);
            font-size: .84rem;
            font-weight: 600;
            margin-top: 10px;
        }
        .receipt-title-block .tpin { font-size: .72rem; color: var(--n400); margin-top: 4px; }

        /* ---- Code strip ---- */
        .code-banner {
            background: var(--brand-light);
            border-top: 1px solid var(--n200);
            border-bottom: 1px solid var(--n200);
            padding: 18px 40px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 16px;
            flex-wrap: wrap;
        }
        .code-banner .code-label {
            font-size: .68rem; font-weight: 700; color: var(--brand-dark);
            text-transform: uppercase; letter-spacing: .07em;
        }
        .code-banner .assigned-code {
            font-size: 1.55rem; font-weight: 800; letter-spacing: .07em;
            font-family: 'JetBrains Mono', Consolas, monospace; color: var(--n900); margin-top: 2px;
        }
        .code-banner .receipt-ref-block { text-align: right; }
        .code-banner .receipt-ref-value { font-size: .95rem; font-weight: 700; font-family: 'JetBrains Mono', Consolas, monospace; color: var(--n800); margin-top: 2px; }
        .code-banner .receipt-ref-date { font-size: .72rem; color: var(--n500); margin-top: 4px; }

        /* ---- Body ---- */
        .receipt-body { padding: 30px 40px; }

        .section-heading {
            font-size: .74rem;
            font-weight: 700;
            color: var(--n500);
            text-transform: uppercase;
            letter-spacing: .08em;
            margin-bottom: 14px;
            padding-bottom: 8px;
            border-bottom: 2px solid var(--n100);
        }
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
            gap: 16px;
            margin-bottom: 30px;
        }
        .info-item .info-label { font-size: .68rem; color: var(--n500); font-weight: 700; text-transform: uppercase; letter-spacing: .05em; }
        .info-item .info-value { font-size: .88rem; color: var(--n800); font-weight: 500; margin-top: 3px; }

        /* ---- Payments table ---- */
        .payments-table { width: 100%; border-collapse: collapse; margin-bottom: 24px; }
        .payments-table th {
            background: var(--n50);
            color: var(--n500);
            font-size: .68rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: .05em;
            padding: 10px 14px;
            text-align: left;
            border-bottom: 2px solid var(--n200);
        }
        .payments-table td {
            padding: 11px 14px;
            font-size: .84rem;
            color: var(--n700);
            border-bottom: 1px solid var(--n100);
        }
        .payments-table tr:last-child td { border-bottom: none; }
        .badge-method {
            display: inline-block;
            background: var(--success-bg);
            color: var(--success);
            border-radius: 20px;
            padding: 2px 10px;
            font-size: .7rem;
            font-weight: 600;
        }
        .badge-initial {
            display: inline-block;
            background: var(--brand-light);
            color: var(--brand-dark);
            border-radius: 20px;
            padding: 2px 8px;
            font-size: .64rem;
            font-weight: 600;
            margin-left: 4px;
        }
        .payment-num { color: var(--n300); font-weight: 700; }
        .no-payments-note { font-size: .84rem; color: var(--n400); font-style: italic; }

        /* ---- Totals ---- */
        .totals-block {
            background: var(--n50);
            border: 1px solid var(--n200);
            border-radius: var(--r);
            padding: 20px 24px;
            max-width: 340px;
            margin-left: auto;
        }
        .totals-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; font-size: .86rem; }
        .totals-row:last-child { margin-bottom: 0; }
        .totals-row .t-label { color: var(--n500); }
        .totals-row .t-value { font-weight: 600; color: var(--n800); font-variant-numeric: tabular-nums; }
        .totals-divider { border: none; border-top: 2px solid var(--n200); margin: 12px 0; }
        .totals-row.grand { font-size: 1.05rem; font-weight: 800; }
        .totals-row.grand .t-label { color: var(--n900); }
        .totals-row.grand .t-value { color: <?php echo $isFullyPaid ? 'var(--success)' : 'var(--danger)'; ?>; }

        /* ---- Footer ---- */
        .receipt-footer {
            background: var(--n50);
            padding: 18px 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 8px;
            border-top: 1px solid var(--n200);
            font-size: .76rem;
            color: var(--n500);
        }
        .completed-by { font-style: italic; }

        /* ---- Action bar ---- */
        .action-bar {
            display: flex;
            align-items: center;
            gap: 10px;
            justify-content: flex-end;
            margin-bottom: 18px;
            flex-wrap: wrap;
        }
        .paper-size-picker {
            display: flex;
            align-items: center;
            gap: 7px;
            font-size: .82rem;
            color: var(--n600);
            background: var(--white);
            border: 1px solid var(--n200);
            border-radius: var(--r-sm);
            padding: 7px 12px;
        }
        .paper-size-picker select {
            border: 1px solid var(--n300);
            border-radius: 5px;
            padding: 4px 8px;
            font-size: .82rem;
            color: var(--n800);
            background: var(--white);
        }
        .btn-print, .btn-back-link {
            padding: 9px 20px;
            border-radius: var(--r-sm);
            font-size: .84rem;
            font-weight: 600;
            cursor: pointer;
            transition: all .15s;
            border: none;
            display: inline-flex;
            align-items: center;
            gap: 7px;
            text-decoration: none;
        }
        .btn-print { background: var(--brand); color: #fff; }
        .btn-print:hover { background: var(--brand-dark); transform: translateY(-1px); box-shadow: 0 4px 12px rgba(79,70,229,.3); }
        .btn-back-link { background: var(--n200); color: var(--n700); }
        .btn-back-link:hover { background: var(--n300); color: var(--n800); text-decoration: none; }

        @media print {
            @page { size: A4; margin: 12mm; }
            body { background: #fff; padding: 0; }
            .action-bar { display: none; }
            .receipt-card { box-shadow: none; border-radius: 0; border: none; }
        }
    </style>
    <link href="/IMS/assets/css/responsive.css" rel="stylesheet">
</head>
<body>

<div class="receipt-wrapper">

    <div class="action-bar no-print">
        <a href="order_details.php?order_id=<?php echo $orderId; ?>" class="btn-back-link">
            <i class="fas fa-arrow-left"></i> Back to Order
        </a>
        <div class="paper-size-picker">
            <span><i class="fas fa-print"></i> Paper:</span>
            <select id="paper-size" aria-label="Print paper size">
                <option value="a4" selected>A4</option>
                <option value="80">80 mm</option>
                <option value="50">50 mm</option>
            </select>
        </div>
        <button class="btn-print" onclick="printDocument()">
            <i class="fas fa-print"></i> Print <?php echo $isCompleted ? 'Receipt' : 'Statement'; ?>
        </button>
    </div>

    <div class="receipt-card" id="receipt-content">

        <!-- Header -->
        <div class="receipt-header">
            <div class="company-block">
                <?php if ($companyLogoFile && file_exists($companyLogoFile)): ?>
                    <img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="Logo" style="max-height:50px;margin-bottom:10px;display:block;">
                <?php endif; ?>
                <div class="company-name"><?php echo htmlspecialchars($companyName); ?></div>
                <div class="company-tagline">
                    Dealers in: IT Consumables &amp; Electricals, Desktop Computers, Laptops,
                    Projectors, Computer Accessories, Digital Home Theaters, Stereo Headphones,
                    Household Furniture&rsquo;s &amp; many more
                </div>
                <div class="company-details">
                    P.O. Box 109, Limbe, Malawi, South East Africa<br>
                    Tel: +265 (0) 212 273 707 / Cell: +265 (0) 888 737 654<br>
                    Email: blessvantengani@gmail.com &bull; Web: www.brcomputers.mw
                </div>
            </div>
            <div class="receipt-title-block">
                <div class="receipt-label"><?php echo htmlspecialchars($docLabel); ?></div>
                <span class="order-num">No. <?php echo htmlspecialchars($order['order_number']); ?></span>
                <div class="tpin">TPIN: 30798774</div>
            </div>
        </div>

        <?php if ($isCompleted): ?>
        <!-- Unique Code Strip -->
        <div class="code-banner">
            <div>
                <div class="code-label">Assigned Item Code(s)</div>
                <div class="assigned-code"><?php echo htmlspecialchars($order['assigned_code']); ?></div>
            </div>
            <div class="receipt-ref-block">
                <div class="code-label">Receipt Reference</div>
                <div class="receipt-ref-value"><?php echo htmlspecialchars($receiptCode); ?></div>
                <div class="receipt-ref-date">
                    Completed: <?php echo $order['completed_at'] ? date('d M Y, H:i', strtotime($order['completed_at'])) : 'N/A'; ?>
                </div>
            </div>
        </div>
        <?php else: ?>
        <!-- Status strip (not yet completed — no item code assigned yet) -->
        <div class="code-banner">
            <div>
                <div class="code-label">Status</div>
                <div class="assigned-code" style="font-size:1.1rem;"><?php echo htmlspecialchars(ucfirst($order['status'] ?? 'pending')); ?> &mdash; Awaiting Completion</div>
            </div>
            <div class="receipt-ref-block">
                <div class="code-label">Statement Reference</div>
                <div class="receipt-ref-value"><?php echo htmlspecialchars($receiptCode); ?></div>
                <div class="receipt-ref-date">
                    Printed: <?php echo date('d M Y, H:i'); ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <div class="receipt-body">

            <!-- Customer & Order Info -->
            <div class="section-heading">Order &amp; Customer Details</div>
            <div class="info-grid">
                <div class="info-item">
                    <div class="info-label">Customer</div>
                    <div class="info-value"><?php echo htmlspecialchars($order['customer_name']); ?></div>
                </div>
                <div class="info-item">
                    <div class="info-label">Contact</div>
                    <div class="info-value"><?php echo nl2br(htmlspecialchars($order['customer_contact'])); ?></div>
                </div>
                <div class="info-item">
                    <div class="info-label">Item Ordered</div>
                    <div class="info-value"><?php echo htmlspecialchars($order['item_name']); ?></div>
                </div>
                <div class="info-item">
                    <div class="info-label">Order Price</div>
                    <div class="info-value">MWK <?php echo number_format($price, 2); ?></div>
                </div>
                <div class="info-item">
                    <div class="info-label">Order Date</div>
                    <div class="info-value"><?php echo date('d M Y', strtotime($order['created_at'])); ?></div>
                </div>
                <div class="info-item">
                    <div class="info-label">Delivery Date</div>
                    <div class="info-value"><?php echo date('d M Y', strtotime($order['delivery_date'])); ?></div>
                </div>
                <?php if (!empty($order['notes'])): ?>
                <div class="info-item" style="grid-column:1/-1;">
                    <div class="info-label">Notes</div>
                    <div class="info-value"><?php echo nl2br(htmlspecialchars($order['notes'])); ?></div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Payment Transactions -->
            <div class="section-heading">Payment Transactions</div>
            <?php if (!empty($payments)): ?>
            <table class="payments-table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Date</th>
                        <th>Amount (MWK)</th>
                        <th>Method</th>
                        <th>Notes</th>
                        <th>Recorded By</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($payments as $i => $p): ?>
                    <tr>
                        <td class="payment-num"><?php echo $i + 1; ?></td>
                        <td><?php echo date('d M Y, H:i', strtotime($p['payment_date'])); ?></td>
                        <td><strong><?php echo number_format($p['amount'], 2); ?></strong></td>
                        <td><span class="badge-method"><?php echo htmlspecialchars(paymentMethodLabel($p['payment_method'])); ?></span></td>
                        <td>
                            <?php echo htmlspecialchars($p['notes'] ?? '—'); ?>
                            <?php if ($p['is_initial']): ?><span class="badge-initial">Deposit</span><?php endif; ?>
                        </td>
                        <td><?php echo htmlspecialchars($p['recorded_by_name'] ?? '—'); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php else: ?>
            <p class="no-payments-note">No individual payment records found.</p>
            <?php endif; ?>

            <!-- Totals -->
            <div class="totals-block">
                <div class="totals-row">
                    <span class="t-label">Order Total</span>
                    <span class="t-value">MWK <?php echo number_format($price, 2); ?></span>
                </div>
                <div class="totals-row">
                    <span class="t-label">Total Paid (<?php echo count($payments); ?> payment<?php echo count($payments) !== 1 ? 's' : ''; ?>)</span>
                    <span class="t-value" style="color:var(--success);">MWK <?php echo number_format($totalPaid, 2); ?></span>
                </div>
                <hr class="totals-divider">
                <div class="totals-row grand">
                    <span class="t-label">Balance</span>
                    <span class="t-value">MWK <?php echo number_format(max(0, $balance), 2); ?></span>
                </div>
            </div>

        </div><!-- /receipt-body -->

        <!-- Footer -->
        <div class="receipt-footer">
            <div class="completed-by">
                <?php if ($isCompleted): ?>
                    Completed by <?php echo htmlspecialchars($completerName); ?>
                    <?php if ($order['completed_at']): ?>
                        on <?php echo date('d M Y \a\t H:i', strtotime($order['completed_at'])); ?>
                    <?php endif; ?>
                <?php else: ?>
                    This is a payment statement — the item code will be assigned once the order is completed.
                <?php endif; ?>
            </div>
            <div>
                <?php if ($isCompleted && !empty($order['eis_transaction_id'])): ?>
                    EIS Ref: <?php echo htmlspecialchars($order['eis_transaction_id']); ?>
                <?php endif; ?>
            </div>
        </div>

    </div><!-- /receipt-card -->

</div><!-- /receipt-wrapper -->

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
    const thermalPaperSizes = {
        '80': { width: 80, padding: 3, font: 12, detailFont: 11 },
        '50': { width: 50, padding: 2, font: 9,  detailFont: 9  }
    };

    function printDocument() {
        const size = document.getElementById('paper-size').value;
        if (size === 'a4') {
            window.print();
            return;
        }
        printThermal(thermalPaperSizes[size]);
    }

    function waitForPrintAssets(printWindow) {
        const images = Array.from(printWindow.document.images || []);
        const imagePromises = images.map((img) => img.complete
            ? Promise.resolve()
            : 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 printThermal(size) {
        const printWindow = window.open('', '_blank');
        if (!printWindow) {
            window.print();
            return;
        }
        const content = document.getElementById('receipt-content').outerHTML;

        printWindow.document.write(`
            <!DOCTYPE html>
            <html>
            <head>
                <title><?php echo htmlspecialchars($docLabel); ?></title>
                <style>
                    * { box-sizing: border-box; }
                    body {
                        margin: 0; padding: 0; background: #fff; color: #000;
                        font-family: Consolas, 'Lucida Console', 'Courier New', monospace;
                    }
                    .receipt-card {
                        width: ${size.width}mm; max-width: ${size.width}mm;
                        padding: ${size.padding}mm; box-sizing: border-box;
                        border: none; border-radius: 0; box-shadow: none; overflow: visible;
                        font-size: ${size.font}px; line-height: 1.25;
                    }
                    .receipt-header { display: block; border-bottom: 1px dashed #000; padding-bottom: 2mm; margin-bottom: 2mm; text-align: center; }
                    .company-block .company-name { font-size: ${size.font + 2}px; }
                    .company-block .company-tagline { display: none; }
                    .company-block .company-details { font-size: ${size.detailFont}px; margin-top: 4px; }
                    .receipt-title-block { text-align: center; margin-top: 4px; }
                    .receipt-title-block .receipt-label { font-size: ${size.detailFont}px; padding: 3px 10px; }
                    .receipt-title-block .order-num, .receipt-title-block .tpin { font-size: ${size.detailFont}px; }

                    .code-banner { display: block; text-align: center; border-top: 1px dashed #000; border-bottom: 1px dashed #000; padding: 2mm 0; margin-bottom: 2mm; background: none; }
                    .code-banner .receipt-ref-block { text-align: center; margin-top: 2mm; }
                    .code-banner .assigned-code { font-size: ${size.font + 1}px; }
                    .code-banner .code-label, .code-banner .receipt-ref-date { font-size: ${size.detailFont}px; }
                    .code-banner .receipt-ref-value { font-size: ${size.detailFont}px; }

                    .receipt-body { padding: 0; }
                    .section-heading { font-size: ${size.detailFont}px; margin: 3mm 0 2mm; }
                    .info-grid { display: block; margin-bottom: 3mm; }
                    .info-item { margin-bottom: 2mm; }
                    .info-item .info-label, .info-item .info-value { font-size: ${size.detailFont}px; }

                    .payments-table { font-size: ${size.detailFont}px; }
                    .payments-table th, .payments-table td { padding: 2px 3px; font-size: ${size.detailFont}px; }
                    .payments-table thead { display: none; }
                    .payments-table tbody tr { display: block; border-bottom: 1px dashed #000; padding-bottom: 2px; margin-bottom: 2px; }
                    .payments-table td { display: block; border: none; padding: 0; }
                    .payments-table td.payment-num { display: none; }
                    .badge-method, .badge-initial { background: none; color: #000; padding: 0; font-weight: 700; }

                    .totals-block { width: 100%; max-width: 100%; padding: 2mm 0; border: none; border-top: 1px dashed #000; background: none; margin: 0; }
                    .totals-row { font-size: ${size.detailFont}px; }
                    .totals-row.grand { font-size: ${size.font}px; }
                    .totals-row.grand .t-value { color: #000 !important; }

                    .receipt-footer { display: block; text-align: center; background: none; border-top: 1px dashed #000; font-size: ${size.detailFont}px; padding-top: 2mm; }
                    @page { size: ${size.width}mm auto; margin: 2mm; }
                </style>
            </head>
            <body>
                ${content}
            </body>
            </html>
        `);
        printWindow.document.close();

        waitForPrintAssets(printWindow).finally(() => {
            printWindow.focus();
            setTimeout(() => {
                printWindow.print();
                setTimeout(() => printWindow.close(), 500);
            }, 100);
        });
    }
</script>
</body>
</html>
