<?php
/**
 * thermal_print_buttons.php
 * ─────────────────────────────────────────────────────────────────────────────
 * Drop-in print panel for front_office_pos.php and planner.php.
 *
 * HOW TO ADD TO YOUR POS PAGES
 * ─────────────────────────────
 * Add these lines just before the footer include in BOTH files:
 *
 *   <?php if ($order): ?>
 *       <?php require_once __DIR__ . '/thermal_print_buttons.php'; ?>
 *   <?php endif; ?>
 *   <?php require_once __DIR__ . '/../../includes/footer.php'; ?>
 *
 * VARIABLES READ FROM HOST PAGE
 * ──────────────────────────────
 *   $order        – current order array         (required)
 *   $orderLines   – line items (front_office)   (auto-detected)
 *   $orderItems   – line items (planner)        (auto-detected)
 *   $paymentRows  – payments   (front_office)   (auto-detected)
 *   $payments     – payments   (planner)        (auto-detected)
 *   $splitRows    – split records (planner)     (optional)
 *   $orderTableSummary – table label (planner)  (optional)
 */

if (!isset($order) || !$order) return;

// ── Normalise variable names across both host files ───────────────────────────
$tp_lines    = $orderLines    ?? $orderItems  ?? [];
$tp_payments = $paymentRows   ?? $payments    ?? [];
$tp_splits   = $splitRows     ?? [];
$tp_table    = $orderTableSummary ?? ($order['table_no'] ?? '');
$tp_guest    = trim((string)($order['guest_name'] ?? ''));
$tp_room     = trim((string)($order['room_no']    ?? ''));
$tp_order_no = (string)($order['order_no'] ?? '');
$tp_covers   = (int)($order['covers'] ?? 1);
$tp_cashier  = trim((string)($order['cashier_name'] ?? ''));
$tp_surcharge_rate = defined('FO_POS_CARD_SURCHARGE_RATE')
    ? FO_POS_CARD_SURCHARGE_RATE
    : (defined('REST_POS_CARD_SURCHARGE_RATE') ? REST_POS_CARD_SURCHARGE_RATE : 0.03);

// ── Build items array for JS ──────────────────────────────────────────────────
$tp_items_js = [];
foreach ($tp_lines as $ln) {
    $tp_items_js[] = [
        'name'   => (string)($ln['item_name'] ?? ''),
        'qty'    => (float)($ln['qty']        ?? 1),
        'amount' => round((float)($ln['line_total'] ?? 0) + (float)($ln['tax_amount'] ?? 0), 2),
        'notes'  => (string)($ln['notes']     ?? ''),
        'status' => (string)($ln['status']    ?? 'active'),
        'seat'   => (int)($ln['seat_no']      ?? 0) ?: null,
        'role'   => (string)($ln['printer_role'] ?? 'kitchen'),
    ];
}

// ── Build payments array for JS ───────────────────────────────────────────────
$tp_pays_js = [];
foreach ($tp_payments as $pay) {
    $tp_pays_js[] = [
        'method'    => (string)($pay['payment_method'] ?? ''),
        'amount'    => (float)($pay['amount']          ?? 0),
        'reference' => (string)($pay['reference_no']   ?? ''),
    ];
}

// ── Build split bills for JS ──────────────────────────────────────────────────
$tp_splits_js = [];
foreach ($tp_splits as $sp) {
    $dest   = strtolower((string)($sp['payment_method'] ?? 'cash'));
    $card   = in_array($dest, ['pos','card','credit card','debit card','visa','mastercard','card payment','pos/card'], true);
    $amount = (float)($sp['split_amount'] ?? 0);
    $fee    = $card ? round($amount * $tp_surcharge_rate, 2) : 0;
    $tp_splits_js[] = [
        'payer'     => (string)($sp['payer_name'] ?? 'Guest'),
        'method'    => ucfirst($dest),
        'total'     => $amount,
        'surcharge' => $fee,
        'order_no'  => $tp_order_no,
        'items'     => [['name' => 'Bill share', 'qty' => 1, 'amount' => $amount]],
    ];
}

// ── Build kitchen/bar groups ──────────────────────────────────────────────────
$tp_kitchen_groups = [];
foreach ($tp_lines as $ln) {
    if (($ln['status'] ?? 'active') !== 'active') continue;
    $role = strtolower(trim((string)($ln['printer_role'] ?? 'kitchen'))) ?: 'kitchen';
    $tp_kitchen_groups[$role][] = [
        'name'  => (string)($ln['item_name'] ?? ''),
        'qty'   => (float)($ln['qty']        ?? 1),
        'seat'  => (int)($ln['seat_no']      ?? 0) ?: null,
        'notes' => (string)($ln['notes']     ?? ''),
    ];
}
$tp_kitchen_tickets_js = [];
foreach ($tp_kitchen_groups as $role => $items) {
    $tp_kitchen_tickets_js[] = [
        'station'  => $role,
        'order_no' => $tp_order_no,
        'table'    => $tp_table,
        'covers'   => $tp_covers,
        'items'    => $items,
    ];
}

// ── Totals ────────────────────────────────────────────────────────────────────
$tp_total    = round((float)($order['total_amount'] ?? 0), 2);
$tp_subtotal = round((float)($order['subtotal']     ?? $tp_total), 2);
$tp_tax      = round((float)($order['tax_total']    ?? 0), 2);

$tp_receipt_js = [
    'order_no' => $tp_order_no,
    'table'    => $tp_table,
    'guest'    => $tp_guest . ($tp_room ? ' • Room ' . $tp_room : ''),
    'cashier'  => $tp_cashier,
    'date'     => date('Y-m-d H:i'),
    'subtotal' => $tp_subtotal,
    'tax'      => $tp_tax,
    'total'    => $tp_total,
    'payments' => $tp_pays_js,
    'items'    => $tp_items_js,
];

$tp_has_kitchen = !empty($tp_kitchen_tickets_js);
$tp_has_splits  = !empty($tp_splits_js);
$tp_is_closed   = in_array((string)($order['status'] ?? ''), ['closed','void'], true);
?>

<!-- ── Thermal Print Panel ──────────────────────────────────────────────────── -->
<div class="card mt-3" id="thermalPrintPanel" style="border-radius:16px;box-shadow:0 8px 24px rgba(15,23,42,.07);">
    <div class="card-header d-flex justify-content-between align-items-center py-2">
        <strong><i class="bi bi-printer me-1"></i>Print</strong>
        <span class="badge bg-<?php echo $tp_is_closed ? 'success' : 'primary'; ?>">
            <?php echo $tp_is_closed ? 'Closed' : 'Open'; ?>
        </span>
    </div>
    <div class="card-body py-2">
        <div class="d-flex flex-wrap gap-2">

            <button type="button" class="btn btn-outline-dark btn-sm" id="btnPrintReceipt"
                    title="Print guest receipt">
                <i class="bi bi-receipt me-1"></i>Receipt
            </button>

            <?php if ($tp_has_kitchen): ?>
            <button type="button" class="btn btn-outline-warning btn-sm" id="btnPrintKitchen"
                    title="Send to kitchen / bar">
                <i class="bi bi-fire me-1"></i>Kitchen / Bar
            </button>
            <?php endif; ?>

            <?php if ($tp_has_splits): ?>
            <button type="button" class="btn btn-outline-success btn-sm" id="btnPrintSplits"
                    title="Print split bills">
                <i class="bi bi-receipt-cutoff me-1"></i>Split Bills (<?php echo count($tp_splits_js); ?>)
            </button>
            <?php endif; ?>

            <button type="button" class="btn btn-outline-secondary btn-sm" id="btnPrintBrowser"
                    title="Open browser print dialog (no network printer needed)">
                <i class="bi bi-printer-fill me-1"></i>Browser Print
            </button>

        </div>
        <div class="small text-muted mt-2">
            Tries ePOS HTTP then raw port 9100. Falls back to browser print if printer unreachable.
        </div>
    </div>
</div>

<?php if (!defined('THERMAL_PRINT_JS_LOADED')): define('THERMAL_PRINT_JS_LOADED', true); ?>
<script src="<?php echo rtrim(dirname($_SERVER['PHP_SELF']), '/'); ?>/thermal_print.js?v=<?php echo date('Ymd'); ?>"></script>
<?php endif; ?>

<script>
(function () {
    'use strict';

    const receipt = <?php echo json_encode($tp_receipt_js, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    const kitchen = <?php echo json_encode($tp_kitchen_tickets_js, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    const splits  = <?php echo json_encode($tp_splits_js,  JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;

    function ready(fn) {
        if (document.readyState !== 'loading') fn();
        else document.addEventListener('DOMContentLoaded', fn);
    }

    ready(function () {

        // Receipt
        const btnR = document.getElementById('btnPrintReceipt');
        if (btnR) btnR.addEventListener('click', function () {
            if (typeof ThermalPrint !== 'undefined') ThermalPrint.receipt(receipt);
            else alert('thermal_print.js not loaded. Check the file path.');
        });

        // Kitchen / Bar
        const btnK = document.getElementById('btnPrintKitchen');
        if (btnK && kitchen.length) btnK.addEventListener('click', function () {
            if (typeof ThermalPrint !== 'undefined') ThermalPrint.kitchen(kitchen);
        });

        // Split bills
        const btnS = document.getElementById('btnPrintSplits');
        if (btnS && splits.length) btnS.addEventListener('click', function () {
            if (typeof ThermalPrint !== 'undefined') ThermalPrint.split(splits);
        });

        // Browser-only fallback (always works)
        const btnB = document.getElementById('btnPrintBrowser');
        if (btnB) btnB.addEventListener('click', function () {
            if (typeof ThermalPrint === 'undefined') {
                alert('thermal_print.js not loaded. Check the file path.');
                return;
            }
            ThermalPrint.browserOnly([receipt].map(function (r) {
                const w = 48;
                const m = v => (parseFloat(v) || 0).toFixed(2);
                const p = (l, r, w) => { l=String(l||''); r=String(r||''); return l+' '.repeat(Math.max(1,w-l.length-r.length))+r; };
                const d = c => (c||'-').repeat(w);
                let out = [], sub = 0;
                out.push(d('='));
                if (r.order_no) out.push('Order:   ' + r.order_no);
                if (r.table)    out.push('Table:   ' + r.table);
                if (r.guest)    out.push('Guest:   ' + r.guest);
                if (r.cashier)  out.push('Cashier: ' + r.cashier);
                out.push('Date:    ' + (r.date || new Date().toLocaleString()));
                out.push(d('-'));
                (r.items || []).forEach(it => {
                    if ((it.status||'active') !== 'active') return;
                    const qty = parseFloat(it.qty||1)||1;
                    sub += parseFloat(it.amount||0);
                    const lbl = (qty!==1?(Number.isInteger(qty)?qty:qty.toFixed(2))+' x ':'')+(it.name||'Item');
                    out.push(p(lbl.substring(0,w-10), m(it.amount), w));
                    if (it.notes) out.push('  * '+it.notes);
                });
                out.push(d('-'));
                out.push(p('TOTAL', m(r.total||sub), w));
                (r.payments||[]).forEach(pay => {
                    out.push(p((pay.method||'').toUpperCase(), m(pay.amount||0), w));
                    if (pay.reference) out.push('  Ref: '+pay.reference);
                });
                out.push(d('='));
                out.push('Thank you!');
                return out.filter(Boolean).join('\n');
            })[0], 'Receipt – ' + receipt.order_no);
        });

    });
})();
</script>
