<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

if (!function_exists('h')) {
    function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('money_fmt')) {
    function money_fmt($amount): string { return number_format((float)$amount, 2); }
}
if (!function_exists('fo_receipt_table_exists')) {
    function fo_receipt_table_exists(PDO $pdo, string $table): bool {
        static $cache = [];
        if (array_key_exists($table, $cache)) return $cache[$table];
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :t");
            $stmt->execute([':t' => $table]);
            return $cache[$table] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            return $cache[$table] = false;
        }
    }
}
if (!function_exists('fo_receipt_column_exists')) {
    function fo_receipt_column_exists(PDO $pdo, string $table, string $column): bool {
        static $cache = [];
        $key = $table . '.' . $column;
        if (array_key_exists($key, $cache)) return $cache[$key];
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = :t AND column_name = :c");
            $stmt->execute([':t' => $table, ':c' => $column]);
            return $cache[$key] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            return $cache[$key] = false;
        }
    }
}

$frontOrderId = (int)($_GET['front_order_id'] ?? $_GET['restaurant_order_id'] ?? 0);
$errors = [];

if ($frontOrderId <= 0) {
    $errors[] = 'Receipt could not be opened because no sale was selected.';
}

foreach (['restaurant_orders', 'restaurant_order_items', 'restaurant_payments'] as $table) {
    if (!fo_receipt_table_exists($pdo, $table)) {
        $errors[] = 'Required table missing: ' . $table;
    }
}

$hasProperties = fo_receipt_table_exists($pdo, 'properties');
$hasLinkedOrder = fo_receipt_column_exists($pdo, 'restaurant_orders', 'linked_order_id');
$hasLinkedFolio = fo_receipt_column_exists($pdo, 'restaurant_orders', 'linked_folio_id');
$hasRoomNo = fo_receipt_column_exists($pdo, 'restaurant_orders', 'room_no');
$hasCashierName = fo_receipt_column_exists($pdo, 'restaurant_orders', 'cashier_name');
$hasItemStatus = fo_receipt_column_exists($pdo, 'restaurant_order_items', 'status');
$hasPaymentStatus = fo_receipt_column_exists($pdo, 'restaurant_payments', 'status');

$order = null;
$lines = [];
$payments = [];
$folio = null;
$pmsBooking = null;

if (!$errors) {
    try {
        $propertySelect = $hasProperties ? "
            p.name AS property_name,
            p.code AS property_code,
            p.address AS property_address,
            p.phone AS property_phone,
            p.email AS property_email,
        " : "
            '' AS property_name,
            '' AS property_code,
            '' AS property_address,
            '' AS property_phone,
            '' AS property_email,
        ";

        $linkedOrderSelect = $hasLinkedOrder ? "ro.linked_order_id" : "NULL AS linked_order_id";
        $linkedFolioSelect = $hasLinkedFolio ? "ro.linked_folio_id" : "NULL AS linked_folio_id";
        $roomNoSelect = $hasRoomNo ? "ro.room_no" : "'' AS room_no";
        $cashierSelect = $hasCashierName ? "ro.cashier_name" : "'' AS cashier_name";

        $stmt = $pdo->prepare("
            SELECT
                ro.id,
                ro.order_no,
                ro.order_type,
                {$linkedOrderSelect},
                {$linkedFolioSelect},
                ro.guest_name,
                {$roomNoSelect},
                ro.status,
                ro.payment_status,
                ro.subtotal,
                ro.tax_total,
                ro.total_amount,
                ro.opened_at,
                ro.closed_at,
                ro.notes,
                {$cashierSelect},
                {$propertySelect}
                ro.property_id
            FROM restaurant_orders ro
            " . ($hasProperties ? "LEFT JOIN properties p ON p.id = ro.property_id" : "") . "
            WHERE ro.id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $frontOrderId]);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$order) throw new RuntimeException('Selected Front Office POS sale was not found.');

        $lineStatusWhere = $hasItemStatus ? "AND COALESCE(status,'active') <> 'void'" : "";
        $stmt = $pdo->prepare("
            SELECT id, item_name, qty, unit_price, tax_rate, tax_amount, line_total, notes, status
            FROM restaurant_order_items
            WHERE restaurant_order_id = :id
              {$lineStatusWhere}
            ORDER BY id ASC
        ");
        $stmt->execute([':id' => $frontOrderId]);
        $lines = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        $paymentStatusWhere = $hasPaymentStatus ? "AND COALESCE(status,'posted') = 'posted'" : "";
        $stmt = $pdo->prepare("
            SELECT payment_date, payment_method, amount, reference_no, status
            FROM restaurant_payments
            WHERE restaurant_order_id = :id
              {$paymentStatusWhere}
            ORDER BY id ASC
        ");
        $stmt->execute([':id' => $frontOrderId]);
        $payments = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        if (!empty($order['linked_folio_id']) && fo_receipt_table_exists($pdo, 'folios')) {
            $stmt = $pdo->prepare("
                SELECT id, folio_no, folio_name, folio_type, balance, COALESCE(window_no,1) AS window_no
                FROM folios
                WHERE id = :id
                LIMIT 1
            ");
            $stmt->execute([':id' => (int)$order['linked_folio_id']]);
            $folio = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
        }

        if (!empty($order['linked_order_id']) && fo_receipt_table_exists($pdo, 'orders')) {
            $stmt = $pdo->prepare("
                SELECT o.id, o.order_no, o.check_in, o.check_out,
                       TRIM(CONCAT(COALESCE(g.firstname,''), ' ', COALESCE(g.lastname,''))) AS guest_name
                FROM orders o
                LEFT JOIN guests g ON g.id = o.guest_id
                WHERE o.id = :id
                LIMIT 1
            ");
            $stmt->execute([':id' => (int)$order['linked_order_id']]);
            $pmsBooking = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
        }
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

$paidTotal = 0.00;
foreach ($payments as $payment) {
    $paidTotal += (float)($payment['amount'] ?? 0);
}

$totalAmount = (float)($order['total_amount'] ?? 0);
$balance = $totalAmount - $paidTotal;
if (($order['payment_status'] ?? '') === 'room_charged') {
    $balance = 0.00;
}

$propertyName = trim((string)($order['property_name'] ?? ''));
if ($propertyName === '') $propertyName = 'Front Office POS';
$receiptDate = $order ? ($order['closed_at'] ?: $order['opened_at']) : date('Y-m-d H:i:s');

$hasSurcharge = false;
foreach ($lines as $line) {
    if (stripos((string)$line['item_name'], 'surcharge') !== false) {
        $hasSurcharge = true;
        break;
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Receipt <?php echo $order ? h($order['order_no']) : ''; ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        *{box-sizing:border-box}
        body{margin:0;background:#f3f4f6;color:#111827;font-family:Arial,Helvetica,sans-serif;font-size:13px}
        .receipt-wrap{max-width:420px;margin:18px auto;background:#fff;border-radius:18px;box-shadow:0 18px 45px rgba(15,23,42,.14);overflow:hidden;border:1px solid #e5e7eb}
        .receipt-head{background:#0f172a;color:#fff;padding:18px 18px 14px;text-align:center}
        .receipt-head h1{margin:0;font-size:18px;line-height:1.15;font-weight:900;letter-spacing:.02em}
        .receipt-head .sub{margin-top:5px;font-size:11px;color:rgba(255,255,255,.75)}
        .receipt-body{padding:16px 18px 18px}
        .meta{border:1px solid #e5e7eb;border-radius:14px;padding:10px 12px;background:#f8fafc;margin-bottom:12px}
        .meta-row{display:flex;justify-content:space-between;gap:10px;padding:3px 0}
        .meta-row span:first-child{color:#64748b;font-weight:700}
        .meta-row span:last-child{text-align:right;font-weight:800}
        table{width:100%;border-collapse:collapse}
        th{text-align:left;color:#64748b;font-size:11px;text-transform:uppercase;letter-spacing:.04em;border-bottom:1px solid #e5e7eb;padding:7px 0}
        td{padding:8px 0;border-bottom:1px solid #f1f5f9;vertical-align:top}
        .num{text-align:right}
        .item-name{font-weight:800}
        .item-note{font-size:11px;color:#64748b;margin-top:2px}
        .totals{margin-top:12px;border-radius:14px;background:#111827;color:#fff;padding:12px}
        .total-row{display:flex;justify-content:space-between;padding:4px 0}
        .total-row span:first-child{color:rgba(255,255,255,.72)}
        .grand{border-top:1px solid rgba(255,255,255,.18);margin-top:6px;padding-top:8px;font-size:17px;font-weight:900}
        .payments{margin-top:12px;border:1px solid #e5e7eb;border-radius:14px;overflow:hidden}
        .payments h3{margin:0;padding:9px 12px;background:#f8fafc;font-size:12px;text-transform:uppercase;letter-spacing:.04em}
        .payment-row{display:flex;justify-content:space-between;gap:10px;padding:8px 12px;border-top:1px solid #f1f5f9}
        .badge{display:inline-block;padding:4px 8px;border-radius:999px;font-size:11px;font-weight:900;text-transform:uppercase;letter-spacing:.03em}
        .badge-paid{background:#dcfce7;color:#166534}
        .badge-open{background:#fef3c7;color:#92400e}
        .badge-folio{background:#dbeafe;color:#1d4ed8}
        .footer-note{margin-top:14px;text-align:center;color:#64748b;font-size:11px;line-height:1.45}
        .actions{max-width:420px;margin:0 auto 18px;display:flex;justify-content:center;gap:8px}
        .btn{border:0;border-radius:10px;padding:9px 13px;cursor:pointer;font-weight:800;text-decoration:none;display:inline-block}
        .btn-primary{background:#2563eb;color:#fff}
        .btn-light{background:#fff;color:#111827;border:1px solid #d1d5db}
        .error{max-width:680px;margin:20px auto;background:#fee2e2;color:#991b1b;border:1px solid #fecaca;border-radius:14px;padding:14px 16px}
        @media print{
            body{background:#fff}
            .receipt-wrap{margin:0 auto;box-shadow:none;border:0;border-radius:0;max-width:80mm}
            .actions{display:none}
            @page{size:80mm auto;margin:5mm}
        }
    </style>
</head>
<body>

<?php if ($errors): ?>
    <div class="error">
        <strong>Could not print receipt:</strong>
        <ul>
            <?php foreach ($errors as $err): ?>
                <li><?php echo h($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php else: ?>
    <div class="receipt-wrap">
        <div class="receipt-head">
            <h1><?php echo h($propertyName); ?></h1>
            <div class="sub">
                <?php if (!empty($order['property_code'])) echo h($order['property_code']) . ' • '; ?>
                Front Office POS Receipt
            </div>
            <?php if (!empty($order['property_phone']) || !empty($order['property_email'])): ?>
                <div class="sub"><?php echo h(trim(($order['property_phone'] ?? '') . ' ' . ($order['property_email'] ?? ''))); ?></div>
            <?php endif; ?>
        </div>

        <div class="receipt-body">
            <div class="meta">
                <div class="meta-row"><span>Receipt No</span><span><?php echo h($order['order_no']); ?></span></div>
                <div class="meta-row"><span>Date</span><span><?php echo h(date('Y-m-d H:i', strtotime($receiptDate))); ?></span></div>
                <div class="meta-row"><span>Customer</span><span><?php echo h($order['guest_name'] ?: 'Walk-in Guest'); ?></span></div>
                <?php if (!empty($order['room_no'])): ?><div class="meta-row"><span>Room</span><span><?php echo h($order['room_no']); ?></span></div><?php endif; ?>
                <?php if ($pmsBooking): ?><div class="meta-row"><span>Booking</span><span><?php echo h($pmsBooking['order_no'] ?: ('#' . $pmsBooking['id'])); ?></span></div><?php endif; ?>
                <?php if ($folio): ?><div class="meta-row"><span>Folio</span><span><?php echo h(strtoupper($folio['folio_type']) . ' • ' . $folio['folio_no']); ?></span></div><?php endif; ?>
                <div class="meta-row"><span>Cashier</span><span><?php echo h($order['cashier_name'] ?: 'Cashier'); ?></span></div>
                <div class="meta-row">
                    <span>Status</span>
                    <span>
                        <?php if (($order['payment_status'] ?? '') === 'room_charged'): ?>
                            <span class="badge badge-folio">Folio Posted</span>
                        <?php elseif (($order['payment_status'] ?? '') === 'paid'): ?>
                            <span class="badge badge-paid">Paid</span>
                        <?php else: ?>
                            <span class="badge badge-open"><?php echo h(ucwords(str_replace('_',' ', (string)$order['payment_status']))); ?></span>
                        <?php endif; ?>
                    </span>
                </div>
            </div>

            <table>
                <thead><tr><th>Item</th><th class="num">Qty</th><th class="num">Amount</th></tr></thead>
                <tbody>
                <?php if (!$lines): ?>
                    <tr><td colspan="3">No items found.</td></tr>
                <?php else: ?>
                    <?php foreach ($lines as $line): ?>
                        <?php $lineGross = (float)$line['line_total'] + (float)$line['tax_amount']; ?>
                        <tr>
                            <td>
                                <div class="item-name"><?php echo h($line['item_name']); ?></div>
                                <div class="item-note">
                                    <?php echo money_fmt($line['unit_price']); ?>
                                    <?php if ((float)$line['tax_rate'] > 0): ?> • Tax <?php echo money_fmt($line['tax_rate']); ?>%<?php endif; ?>
                                    <?php if (!empty($line['notes'])): ?> • <?php echo h($line['notes']); ?><?php endif; ?>
                                </div>
                            </td>
                            <td class="num"><?php echo money_fmt($line['qty']); ?></td>
                            <td class="num"><?php echo money_fmt($lineGross); ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>

            <div class="totals">
                <div class="total-row"><span>Subtotal</span><strong><?php echo money_fmt($order['subtotal']); ?></strong></div>
                <div class="total-row"><span>Tax</span><strong><?php echo money_fmt($order['tax_total']); ?></strong></div>
                <div class="total-row grand"><span>Total</span><strong><?php echo money_fmt($order['total_amount']); ?></strong></div>
                <div class="total-row">
                    <span>Paid / Posted</span>
                    <strong><?php echo ($order['payment_status'] ?? '') === 'room_charged' ? money_fmt($order['total_amount']) : money_fmt($paidTotal); ?></strong>
                </div>
                <div class="total-row"><span>Balance</span><strong><?php echo money_fmt(max(0, $balance)); ?></strong></div>
            </div>

            <div class="payments">
                <h3>Settlement</h3>
                <?php if (($order['payment_status'] ?? '') === 'room_charged'): ?>
                    <div class="payment-row"><span>Posted to PMS Folio</span><strong><?php echo money_fmt($order['total_amount']); ?></strong></div>
                <?php elseif (!$payments): ?>
                    <div class="payment-row"><span>No payments recorded</span><strong>0.00</strong></div>
                <?php else: ?>
                    <?php foreach ($payments as $payment): ?>
                        <div class="payment-row">
                            <span>
                                <?php echo h($payment['payment_method']); ?>
                                <?php if (!empty($payment['reference_no'])): ?><br><small><?php echo h($payment['reference_no']); ?></small><?php endif; ?>
                            </span>
                            <strong><?php echo money_fmt($payment['amount']); ?></strong>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <div class="footer-note">
                Thank you.<br>
                Goods/services received in good order.
                <?php if ($hasSurcharge): ?><br>Card/POS payment includes automatic 3% surcharge.<?php endif; ?>
            </div>
        </div>
    </div>

    <div class="actions">
        <button type="button" class="btn btn-primary" onclick="window.print()">Print Receipt</button>
        <a class="btn btn-light" href="front_office_pos.php?front_order_id=<?php echo (int)$frontOrderId; ?>">Back to POS</a>
    </div>

    <script>
        window.addEventListener('load', function () {
            if (new URLSearchParams(window.location.search).get('auto_print') === '1') {
                window.print();
            }
        });
    </script>
<?php endif; ?>

</body>
</html>
