<?php
// /htdocs/pages/vendor/restaurant-pos.php — RESTAURANT POS COMMAND CENTER v2.3.0
// v2.3.0: Adds Z-Report (Close-Out) and Venue Switcher.
// v2.2.0: Adds split payments (by covers + by items). All v2.1.0 logic preserved.
// v2.1.0: Permission gate — requires pos.view OR vendor ownership.

// ============================================
// PRINT DISPATCH — runs before ANY other logic
// ============================================
$_printRaw = $_SERVER['QUERY_STRING'] ?? '';
$_printParams = [];
parse_str($_printRaw, $_printParams);
$_printAct = $_printParams['action'] ?? ($_GET['action'] ?? '');
$_printOid = (int)($_printParams['order_id'] ?? ($_GET['order_id'] ?? 0));

if ($_printAct === 'print_receipt' || $_printAct === 'print_kitchen') {
    if (!defined('APP_START')) define('APP_START', microtime(true));
    $__b = dirname(__DIR__, 2);
    foreach (['config.php', 'database.php', 'functions.php'] as $__f) {
        $__p = $__b . '/' . $__f;
        if (is_file($__p)) require_once $__p;
    }
    if (session_status() === PHP_SESSION_NONE) @session_start();
    if (!function_exists('getVendor') || !function_exists('db')) {
        http_response_code(500); exit('Bootstrap failed');
    }

    $__v = getVendor();
    if (!$__v) { http_response_code(403); exit('Vendor required — please log in and try again'); }
    $__vid = (int)$__v['id'];
    $__cur = $__v['currency'] ?? 'USD';
    $__db  = db();

    if ($_printOid <= 0) { http_response_code(400); exit('Missing order_id'); }

    $__ord = null;
    $__its = [];
    $__splits = [];
    $__tab = '';
    try {
        $__ord = $__db->fetchOne("SELECT * FROM pos_orders WHERE id = ? AND vendor_id = ?", [$_printOid, $__vid]);
        if ($__ord) {
            $__its = $__db->fetchAll("SELECT * FROM pos_order_items WHERE order_id = ? ORDER BY created_at ASC", [$_printOid]);
            if (!empty($__ord['table_id'])) {
                $__t = $__db->fetchOne("SELECT name FROM pos_tables WHERE id = ? LIMIT 1", [(int)$__ord['table_id']]);
                if ($__t) $__tab = (string)$__t['name'];
            }
            $__splits = $__db->fetchAll("SELECT * FROM pos_split_payments WHERE order_id = ? ORDER BY id ASC", [$_printOid]) ?: [];
        }
    } catch (Throwable $__e) { http_response_code(500); exit('DB: ' . $__e->getMessage()); }
    if (!$__ord) { http_response_code(404); exit('Order #' . $_printOid . ' not found for this vendor'); }

    $__kot = ($_printAct === 'print_kitchen');
    $__rn  = $__v['company_name'] ?? 'Restaurant';
    header('Content-Type: text/html; charset=utf-8');
    ?><!DOCTYPE html>
<html><head><meta charset="utf-8">
<title><?= $__kot ? 'KOT' : 'Receipt' ?> — <?= htmlspecialchars($__ord['order_number']) ?></title>
<style>
    body{font-family:'Courier New',monospace;font-size:<?= $__kot?'20px':'14px' ?>;color:#000;background:#fff;margin:0;padding:20px;max-width:<?= $__kot?'400px':'320px' ?>}
    h1{font-size:<?= $__kot?'26px':'18px' ?>;font-weight:bold;text-align:center;margin:0 0 6px;text-transform:uppercase;letter-spacing:1px}
    .sub{text-align:center;font-size:<?= $__kot?'16px':'11px' ?>;margin-bottom:10px}
    .meta{border-top:<?= $__kot?'3px':'2px' ?> dashed #000;border-bottom:<?= $__kot?'3px':'2px' ?> dashed #000;padding:8px 0;margin:10px 0;font-size:<?= $__kot?'18px':'12px' ?>;line-height:1.6}
    .meta-row{display:flex;justify-content:space-between}
    table{width:100%;border-collapse:collapse;margin:8px 0}
    th,td{text-align:left;padding:<?= $__kot?'6px 0':'4px 0' ?>;font-size:<?= $__kot?'18px':'12px' ?>}
    th{border-bottom:1px solid #000}
    .qty{font-weight:bold;width:40px}
    .item-name{font-weight:<?= $__kot?'bold':'normal' ?>}
    .price{text-align:right;white-space:nowrap}
    .totals{margin-top:10px;padding-top:10px;border-top:2px solid #000}
    .total-row{display:flex;justify-content:space-between;padding:3px 0;font-size:<?= $__kot?'18px':'12px' ?>}
    .total-row.grand{font-size:<?= $__kot?'24px':'16px' ?>;font-weight:bold;border-top:2px dashed #000;padding-top:8px;margin-top:6px}
    .notes{font-style:italic;font-size:<?= $__kot?'16px':'11px' ?>;margin-top:3px;padding-left:10px}
    .footer{text-align:center;font-size:<?= $__kot?'14px':'11px' ?>;margin-top:14px;padding-top:10px;border-top:1px dashed #000}
    .no-print{text-align:center;margin:20px 0}
    .no-print button,.no-print a{padding:10px 20px;font-size:14px;font-weight:bold;cursor:pointer;margin:0 5px;border:2px solid #000;background:#fff;color:#000;text-decoration:none;display:inline-block}
    @media print{.no-print{display:none!important}body{padding:0}}
</style></head>
<body onload="window.print()">
<h1><?= $__kot ? '🔥 KITCHEN' : 'RECEIPT' ?></h1>
<div class="sub"><?= htmlspecialchars($__rn) ?></div>
<div class="meta">
    <div class="meta-row"><span>Order:</span><strong><?= htmlspecialchars($__ord['order_number']) ?></strong></div>
    <div class="meta-row"><span>Date:</span><span><?= date('M j, Y H:i', strtotime($__ord['created_at'])) ?></span></div>
    <?php if ($__tab): ?>
        <div class="meta-row"><span>Table:</span><strong><?= htmlspecialchars($__tab) ?></strong></div>
    <?php else: ?>
        <div class="meta-row"><span>Type:</span><span><?= ucfirst(str_replace('_',' ',$__ord['order_type'])) ?></span></div>
    <?php endif; ?>
    <?php if (!empty($__ord['guest_name'])): ?><div class="meta-row"><span>Guest:</span><span><?= htmlspecialchars($__ord['guest_name']) ?></span></div><?php endif; ?>
    <?php if ((int)($__ord['covers'] ?? 0) > 1): ?><div class="meta-row"><span>Covers:</span><span><?= (int)$__ord['covers'] ?></span></div><?php endif; ?>
    <?php if (!empty($__ord['room_number'])): ?><div class="meta-row"><span>Room:</span><strong><?= htmlspecialchars($__ord['room_number']) ?></strong></div><?php endif; ?>
</div>
<table><thead><tr>
    <th class="qty">QTY</th><th>ITEM</th><?php if (!$__kot): ?><th class="price">AMT</th><?php endif; ?>
</tr></thead><tbody>
    <?php if (!empty($__its)): foreach ($__its as $__it): ?>
        <tr>
            <td class="qty"><?= (int)$__it['quantity'] ?>×</td>
            <td class="item-name"><?= htmlspecialchars($__it['item_name']) ?><?php if (!empty($__it['notes'])): ?><div class="notes">→ <?= htmlspecialchars($__it['notes']) ?></div><?php endif; ?></td>
            <?php if (!$__kot): ?><td class="price"><?= number_format((float)$__it['subtotal'], 2) ?></td><?php endif; ?>
        </tr>
    <?php endforeach; else: ?>
        <tr><td colspan="<?= $__kot?2:3 ?>" style="text-align:center">No items</td></tr>
    <?php endif; ?>
</tbody></table>
<?php if (!$__kot): ?>
<div class="totals">
    <div class="total-row"><span>Subtotal</span><span><?= number_format((float)$__ord['subtotal'], 2) ?></span></div>
    <?php if ((float)$__ord['discount'] > 0): ?><div class="total-row"><span>Discount</span><span>-<?= number_format((float)$__ord['discount'], 2) ?></span></div><?php endif; ?>
    <div class="total-row"><span>Service (5%)</span><span><?= number_format((float)$__ord['service_charge'], 2) ?></span></div>
    <div class="total-row"><span>Tax (10%)</span><span><?= number_format((float)$__ord['tax'], 2) ?></span></div>
    <div class="total-row grand"><span>TOTAL</span><span><?= htmlspecialchars($__cur) ?> <?= number_format((float)$__ord['total'], 2) ?></span></div>
</div>
<?php if (!empty($__splits)): ?>
<div style="margin-top:14px;padding-top:10px;border-top:2px dashed #000;">
    <div style="text-align:center;font-weight:bold;font-size:12px;margin-bottom:6px;">PAYMENT SPLITS</div>
    <?php foreach ($__splits as $__sp): ?>
    <div class="total-row" style="font-size:11px;">
        <span><?= htmlspecialchars($__sp['split_label'] ?: 'Split') ?> (<?= strtoupper($__sp['payment_method']) ?>)</span>
        <span><?= number_format((float)$__sp['amount'],2) ?></span>
    </div>
    <?php endforeach; ?>
    <div class="total-row grand" style="border-top:1px solid #000;font-size:14px;border-top-style:solid;">
        <span>PAID</span>
        <span><?= htmlspecialchars($__cur) ?> <?= number_format((float)array_sum(array_column($__splits,'amount')),2) ?></span>
    </div>
</div>
<?php endif; ?>
<?php endif; ?>
<div class="footer"><?= $__kot ? '— End of ticket —<br>' . count($__its) . ' item' . (count($__its)===1?'':'s') : 'Thank you for dining with us!' ?></div>
<div class="no-print">
    <button onclick="window.print()">🖨️ Print</button>
    <a href="?page=vendor-restaurant-pos&order_id=<?= (int)$_printOid ?>">← Back to POS</a>
</div>
</body></html>
    <?php exit;
}
// ============================================
// END PRINT DISPATCH
// ============================================

if (!defined('APP_START')) { http_response_code(403); exit('Direct access denied'); }

$vendor = getVendor();
if (!$vendor) {
    echo '<div style="padding:100px;text-align:center;color:white;">Vendor access required</div>';
    return;
}

$vendorId = (int)$vendor['id'];

/* Module access guard (Phase B2) */
if (!function_exists('vendorHasModule') || !vendorHasModule($vendorId, 'restaurant_pos')) {
    setMessage('This feature is not enabled on your current plan. Upgrade to access.', 'error');
    redirect('/?page=vendor-subscription');
    exit;
}

$userId = (int)($_SESSION['user_id'] ?? 0);
$db = db();
$baseCurrency = $vendor['currency'] ?? 'USD';

// ============================================
// PERMISSION GATE — v2.1.0
// ============================================
$__isSuperAdmin = function_exists('isSuperAdmin') ? isSuperAdmin() : false;
$__isVendorOwner = !empty($vendor['user_id']) && (int)$vendor['user_id'] === $userId;
$__hasPosView = function_exists('userCan') ? userCan('pos.view', $vendorId) : true;

if (!$__isSuperAdmin && !$__isVendorOwner && !$__hasPosView) {
    require_once __DIR__ . '/../../includes/header.php';
    echo '<div style="background:#0f0c29;min-height:100vh;padding:100px 20px;color:white;text-align:center;font-family:-apple-system,BlinkMacSystemFont,sans-serif;">';
    echo '<div style="max-width:520px;margin:0 auto;background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.08);border-radius:20px;padding:40px 32px;">';
    echo '<div style="width:80px;height:80px;border-radius:50%;background:rgba(245,87,108,0.15);display:flex;align-items:center;justify-content:center;margin:0 auto 24px;font-size:36px;color:#f5576c;">🔒</div>';
    echo '<h2 style="font-size:22px;font-weight:800;margin-bottom:10px;color:white;">POS Access Required</h2>';
    echo '<p style="color:#a0aec0;font-size:14px;line-height:1.6;margin-bottom:20px;">';
    echo 'You don\'t have permission to access the Restaurant POS. Contact your F&B Manager or Property Admin to be assigned a POS role:';
    echo '</p>';
    echo '<div style="display:flex;gap:6px;flex-wrap:wrap;justify-content:center;margin-bottom:24px;">';
    foreach (['Waiter','Bartender','Cashier','F&B Supervisor','F&B Manager'] as $role) {
        echo '<span style="padding:5px 12px;background:rgba(102,126,234,0.15);color:#a3bffa;border:1px solid rgba(102,126,234,0.3);border-radius:50px;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.04em;">' . $role . '</span>';
    }
    echo '</div>';
    echo '<a href="/?page=vendor-dashboard" style="display:inline-block;padding:12px 24px;background:linear-gradient(135deg,#667eea,#764ba2);color:white;border-radius:12px;font-weight:700;text-decoration:none;font-size:13px;">← Back to Dashboard</a>';
    echo '</div></div>';
    require_once __DIR__ . '/../../includes/footer.php';
    return;
}

// ============================================
// HELPERS
// ============================================
if (!function_exists('posQ')) {
    function posQ($s, $p = []) {
        try { return db()->fetchOne($s, $p); } catch (Throwable $e) { return null; }
    }
}
if (!function_exists('posQA')) {
    function posQA($s, $p = []) {
        try { return db()->fetchAll($s, $p); } catch (Throwable $e) { return []; }
    }
}
if (!function_exists('posExec')) {
    function posExec($s, $p = []) {
        try { return db()->query($s, $p); } catch (Throwable $e) {
            error_log('pos exec: ' . $e->getMessage());
            return false;
        }
    }
}
if (!function_exists('posMoney')) {
    function posMoney($a, $cur = 'USD') {
        return $cur . ' ' . number_format((float)$a, 2);
    }
}
if (!function_exists('posSplitsForOrder')) {
    function posSplitsForOrder(int $orderId): array {
        try {
            return db()->fetchAll(
                "SELECT * FROM pos_split_payments WHERE order_id = ? ORDER BY id ASC",
                [$orderId]
            ) ?: [];
        } catch (Throwable $e) { return []; }
    }
}
if (!function_exists('posSplitTotal')) {
    function posSplitTotal(array $splits): float {
        $t = 0.0;
        foreach ($splits as $s) $t += (float)$s['amount'];
        return $t;
    }
}

// ============================================
// ENSURE TABLES
// ============================================
try {
    $db->query("CREATE TABLE IF NOT EXISTS pos_tables (
        id INT AUTO_INCREMENT PRIMARY KEY,
        vendor_id INT NOT NULL,
        name VARCHAR(50) NOT NULL,
        capacity INT DEFAULT 4,
        zone VARCHAR(50) NULL,
        status ENUM('available','occupied','reserved','cleaning') DEFAULT 'available',
        current_order_id INT NULL,
        is_active TINYINT(1) DEFAULT 1,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_vendor (vendor_id),
        INDEX idx_status (status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Throwable $e) {}

try {
    $db->query("CREATE TABLE IF NOT EXISTS pos_orders (
        id INT AUTO_INCREMENT PRIMARY KEY,
        vendor_id INT NOT NULL,
        restaurant_id INT NULL,
        table_id INT NULL,
        order_number VARCHAR(30) UNIQUE,
        order_type ENUM('dine_in','takeaway','room_service') DEFAULT 'dine_in',
        status ENUM('open','preparing','served','paid','cancelled') DEFAULT 'open',
        guest_name VARCHAR(100) NULL,
        covers INT DEFAULT 1,
        room_number VARCHAR(20) NULL,
        folio_id INT NULL,
        subtotal DECIMAL(10,2) DEFAULT 0,
        tax DECIMAL(10,2) DEFAULT 0,
        service_charge DECIMAL(10,2) DEFAULT 0,
        discount DECIMAL(10,2) DEFAULT 0,
        discount_reason VARCHAR(100) NULL,
        total DECIMAL(10,2) DEFAULT 0,
        payment_method VARCHAR(30) NULL,
        notes TEXT NULL,
        created_by INT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        closed_at DATETIME NULL,
        INDEX idx_vendor (vendor_id),
        INDEX idx_status (status),
        INDEX idx_table (table_id),
        INDEX idx_created (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Throwable $e) {}

foreach ([
    "ALTER TABLE pos_orders ADD COLUMN guest_name VARCHAR(100) NULL",
    "ALTER TABLE pos_orders ADD COLUMN covers INT DEFAULT 1",
    "ALTER TABLE pos_orders ADD COLUMN room_number VARCHAR(20) NULL",
    "ALTER TABLE pos_orders ADD COLUMN folio_id INT NULL",
    "ALTER TABLE pos_orders ADD COLUMN discount DECIMAL(10,2) DEFAULT 0",
    "ALTER TABLE pos_orders ADD COLUMN discount_reason VARCHAR(100) NULL",
    "ALTER TABLE pos_orders ADD COLUMN created_by INT NULL",
    "ALTER TABLE pos_tables ADD COLUMN zone VARCHAR(50) NULL",
] as $alter) {
    try { $db->query($alter); } catch (Throwable $e) {}
}

try {
    $db->query("CREATE TABLE IF NOT EXISTS pos_order_items (
        id INT AUTO_INCREMENT PRIMARY KEY,
        order_id INT NOT NULL,
        menu_item_id INT NULL,
        item_name VARCHAR(255) NOT NULL,
        unit_price DECIMAL(10,2) NOT NULL,
        quantity INT DEFAULT 1,
        subtotal DECIMAL(10,2) NOT NULL,
        notes TEXT NULL,
        status ENUM('pending','preparing','ready','served') DEFAULT 'pending',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_order (order_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Throwable $e) {}

foreach ([
    "ALTER TABLE pos_order_items ADD COLUMN menu_item_id INT NULL",
] as $alter) {
    try { $db->query($alter); } catch (Throwable $e) {}
}

try {
    $db->query("CREATE TABLE IF NOT EXISTS pos_split_payments (
        id BIGINT AUTO_INCREMENT PRIMARY KEY,
        order_id INT NOT NULL,
        vendor_id INT NOT NULL,
        split_type ENUM('covers','items') NOT NULL DEFAULT 'covers',
        split_label VARCHAR(100) NULL,
        item_ids TEXT NULL,
        covers_count INT NULL,
        amount DECIMAL(10,2) NOT NULL,
        payment_method VARCHAR(30) NOT NULL,
        room_number VARCHAR(20) NULL,
        folio_id INT NULL,
        paid_by VARCHAR(100) NULL,
        created_by INT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_order (order_id),
        INDEX idx_vendor (vendor_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
} catch (Throwable $e) {}

// ============================================
// RECALCULATE ORDER TOTALS
// ============================================
if (!function_exists('posRecalculate')) {
    function posRecalculate(int $orderId): void {
        $subtotal = (float)(posQ(
            "SELECT COALESCE(SUM(subtotal),0) as s FROM pos_order_items WHERE order_id = ?",
            [$orderId]
        )['s'] ?? 0);

        $order = posQ("SELECT discount, vendor_id FROM pos_orders WHERE id = ?", [$orderId]);
        $discount = (float)($order['discount'] ?? 0);
        $afterDiscount = max(0, $subtotal - $discount);
        $tax = $afterDiscount * 0.10;
        $service = $afterDiscount * 0.05;
        $total = $afterDiscount + $tax + $service;

        posExec(
            "UPDATE pos_orders SET subtotal = ?, tax = ?, service_charge = ?, total = ? WHERE id = ?",
            [$subtotal, $tax, $service, $total, $orderId]
        );
    }
}

// ============================================
// POST HANDLERS
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $action = $_POST['action'] ?? '';

        if ($action === 'create_table') {
            if (!$__isSuperAdmin && !$__isVendorOwner && !userCan('fb.tables', $vendorId) && !userCan('fb.manage', $vendorId)) {
                throw new RuntimeException('Not allowed to create tables');
            }
            posExec(
                "INSERT INTO pos_tables (vendor_id, name, capacity, zone) VALUES (?, ?, ?, ?)",
                [
                    $vendorId,
                    trim($_POST['name'] ?? 'Table'),
                    max(1, (int)($_POST['capacity'] ?? 4)),
                    trim($_POST['zone'] ?? '') ?: null,
                ]
            );
            setMessage('✅ Table created');
            redirect('/?page=vendor-restaurant-pos');
        }

        if ($action === 'delete_table') {
            if (!$__isSuperAdmin && !$__isVendorOwner && !userCan('fb.tables', $vendorId) && !userCan('fb.manage', $vendorId)) {
                throw new RuntimeException('Not allowed');
            }
            $tableId = (int)($_POST['table_id'] ?? 0);
            posExec("DELETE FROM pos_tables WHERE id = ? AND vendor_id = ?", [$tableId, $vendorId]);
            setMessage('🗑️ Table deleted');
            redirect('/?page=vendor-restaurant-pos');
        }

        if ($action === 'set_table_status') {
            $tableId = (int)($_POST['table_id'] ?? 0);
            $status = $_POST['status'] ?? 'available';
            $valid = ['available', 'occupied', 'reserved', 'cleaning'];
            if (!in_array($status, $valid, true)) throw new RuntimeException('Invalid status');
            posExec(
                "UPDATE pos_tables SET status = ? WHERE id = ? AND vendor_id = ?",
                [$status, $tableId, $vendorId]
            );
            setMessage('✅ Table updated');
            redirect('/?page=vendor-restaurant-pos');
        }

        if ($action === 'create_order') {
            if (!$__isSuperAdmin && !$__isVendorOwner && !userCan('pos.order.create', $vendorId)) {
                throw new RuntimeException('Not allowed to create orders');
            }
            $tableId = (int)($_POST['table_id'] ?? 0) ?: null;
            $orderNumber = 'ORD-' . date('ymd') . '-' . strtoupper(substr(md5(uniqid()), 0, 5));

            if ($tableId) {
                $existing = posQ("SELECT id FROM pos_orders WHERE table_id = ? AND status IN ('open','preparing','served')", [$tableId]);
                if ($existing) throw new RuntimeException('Table already has an open order');
            }

                        $rid = (int)($_POST['restaurant_id'] ?? $selectedVenueId);
            posExec(
                "INSERT INTO pos_orders
                    (vendor_id, restaurant_id, table_id, order_number, order_type, status, guest_name, covers, room_number, notes, created_by)
                 VALUES (?, ?, ?, ?, ?, 'open', ?, ?, ?, ?, ?)",
                [
                    $vendorId, $rid ?: null, $tableId, $orderNumber,
                    $_POST['order_type'] ?? 'dine_in',
                    trim($_POST['guest_name'] ?? '') ?: null,
                    max(1, (int)($_POST['covers'] ?? 1)),
                    trim($_POST['room_number'] ?? '') ?: null,
                    trim($_POST['notes'] ?? '') ?: null,
                    $userId,
                ]
            );
            $orderId = (int)db()->lastInsertId();

            if ($tableId) {
                posExec(
                    "UPDATE pos_tables SET status = 'occupied', current_order_id = ? WHERE id = ?",
                    [$orderId, $tableId]
                );
            }
            setMessage('✅ Order created');
            $rid = (int)($_POST['restaurant_id'] ?? 0);
            redirect('/?page=vendor-restaurant-pos&order_id=' . $orderId . ($rid > 0 ? '&restaurant_id=' . $rid : ''));
        }

        if ($action === 'add_item') {
            if (!$__isSuperAdmin && !$__isVendorOwner && !userCan('pos.order.create', $vendorId)) {
                throw new RuntimeException('Not allowed');
            }
            $orderId = (int)($_POST['order_id'] ?? 0);
            $itemName = trim($_POST['item_name'] ?? '');
            $unitPrice = (float)($_POST['unit_price'] ?? 0);
            $quantity = max(1, (int)($_POST['quantity'] ?? 1));
            $itemNotes = trim($_POST['item_notes'] ?? '') ?: null;
            $menuItemId = (int)($_POST['menu_item_id'] ?? 0) ?: null;

            if ($orderId <= 0 || $itemName === '') throw new RuntimeException('Invalid item');

            $order = posQ("SELECT id FROM pos_orders WHERE id = ? AND vendor_id = ?", [$orderId, $vendorId]);
            if (!$order) throw new RuntimeException('Order not found');

            $subtotal = $unitPrice * $quantity;
            posExec(
                "INSERT INTO pos_order_items (order_id, menu_item_id, item_name, unit_price, quantity, subtotal, notes)
                 VALUES (?, ?, ?, ?, ?, ?, ?)",
                [$orderId, $menuItemId, $itemName, $unitPrice, $quantity, $subtotal, $itemNotes]
            );
            posRecalculate($orderId);
            setMessage('✅ Item added');
        }

        if ($action === 'delete_item') {
            if (!$__isSuperAdmin && !$__isVendorOwner && !userCan('pos.order.void', $vendorId)) {
                throw new RuntimeException('Not allowed to remove items');
            }
            $itemId = (int)($_POST['item_id'] ?? 0);
            $orderId = (int)($_POST['order_id'] ?? 0);
            posExec("DELETE FROM pos_order_items WHERE id = ?", [$itemId]);
            posRecalculate($orderId);
            setMessage('🗑️ Item removed');
        }

        if ($action === 'update_item_status') {
            if (!$__isSuperAdmin && !$__isVendorOwner && !userCan('pos.kds.update', $vendorId)) {
                throw new RuntimeException('Not allowed');
            }
            $itemId = (int)($_POST['item_id'] ?? 0);
            $status = $_POST['status'] ?? 'pending';
            $valid = ['pending', 'preparing', 'ready', 'served'];
            if (!in_array($status, $valid, true)) throw new RuntimeException('Invalid status');
            posExec("UPDATE pos_order_items SET status = ? WHERE id = ?", [$status, $itemId]);
            echo json_encode(['success' => true]);
            exit;
        }

        if ($action === 'update_order_status') {
            $orderId = (int)($_POST['order_id'] ?? 0);
            $status = $_POST['status'] ?? 'open';
            $valid = ['open', 'preparing', 'served', 'paid', 'cancelled'];
            if (!in_array($status, $valid, true)) throw new RuntimeException('Invalid status');
            posExec(
                "UPDATE pos_orders SET status = ? WHERE id = ? AND vendor_id = ?",
                [$status, $orderId, $vendorId]
            );
            setMessage('✅ Order status updated');
        }

        if ($action === 'apply_discount') {
            if (!$__isSuperAdmin && !$__isVendorOwner && !userCan('pos.order.discount', $vendorId)) {
                throw new RuntimeException('Not allowed to apply discounts');
            }
            $orderId = (int)($_POST['order_id'] ?? 0);
            $type = $_POST['discount_type'] ?? 'percent';
            $value = (float)($_POST['discount_value'] ?? 0);
            $reason = trim($_POST['discount_reason'] ?? '');

            $order = posQ("SELECT subtotal FROM pos_orders WHERE id = ? AND vendor_id = ?", [$orderId, $vendorId]);
            if (!$order) throw new RuntimeException('Order not found');

            $subtotal = (float)$order['subtotal'];
            $discountAmount = $type === 'percent' ? $subtotal * ($value / 100) : $value;
            $discountAmount = min($discountAmount, $subtotal);

            posExec(
                "UPDATE pos_orders SET discount = ?, discount_reason = ? WHERE id = ?",
                [$discountAmount, $reason ?: null, $orderId]
            );
            posRecalculate($orderId);
            setMessage('✅ Discount applied');
        }

        if ($action === 'close_order') {
            if (!$__isSuperAdmin && !$__isVendorOwner && !userCan('pos.order.close', $vendorId) && !userCan('pos.payment.collect', $vendorId)) {
                throw new RuntimeException('Not allowed to close orders');
            }
            $orderId = (int)($_POST['order_id'] ?? 0);
            $paymentMethod = $_POST['payment_method'] ?? 'cash';
            $chargeToRoom = $paymentMethod === 'room';
            $roomNumber = trim($_POST['room_number'] ?? '');

            $order = posQ("SELECT * FROM pos_orders WHERE id = ? AND vendor_id = ?", [$orderId, $vendorId]);
            if (!$order) throw new RuntimeException('Order not found');

            $folioId = null;
            if ($chargeToRoom && $roomNumber) {
                $folio = posQ(
                    "SELECT id FROM folios WHERE room_number = ? AND status = 'in_house' AND vendor_id = ? LIMIT 1",
                    [$roomNumber, $vendorId]
                );
                $folioId = $folio ? (int)$folio['id'] : null;
            }

            posExec(
                "UPDATE pos_orders
                 SET status = 'paid', closed_at = NOW(), payment_method = ?, folio_id = ?, room_number = ?
                 WHERE id = ?",
                [$paymentMethod, $folioId, $roomNumber ?: null, $orderId]
            );

            if ($order['table_id']) {
                posExec(
                    "UPDATE pos_tables SET status = 'cleaning', current_order_id = NULL WHERE id = ?",
                    [(int)$order['table_id']]
                );
            }

            if ($folioId) {
                posExec(
                    "INSERT INTO folio_charges (folio_id, description, amount, charge_type, created_at)
                     VALUES (?, ?, ?, 'restaurant', NOW())",
                    [$folioId, 'Restaurant: ' . $order['order_number'], (float)$order['total']]
                );
            }

            setMessage('✅ Order closed');
            redirect('/?page=vendor-restaurant-pos');
        }

        if ($action === 'void_order') {
            if (!$__isSuperAdmin && !$__isVendorOwner && !userCan('pos.order.void', $vendorId)) {
                throw new RuntimeException('Not allowed to void orders');
            }
            $orderId = (int)($_POST['order_id'] ?? 0);
            $order = posQ("SELECT table_id FROM pos_orders WHERE id = ? AND vendor_id = ?", [$orderId, $vendorId]);
            if (!$order) throw new RuntimeException('Order not found');

            posExec(
                "UPDATE pos_orders SET status = 'cancelled', closed_at = NOW() WHERE id = ?",
                [$orderId]
            );
            if ($order['table_id']) {
                posExec(
                    "UPDATE pos_tables SET status = 'cleaning', current_order_id = NULL WHERE id = ?",
                    [(int)$order['table_id']]
                );
            }
            setMessage('❌ Order voided');
            redirect('/?page=vendor-restaurant-pos');
        }

            if ($action === 'transfer_table') {
            if (!$__isSuperAdmin && !$__isVendorOwner && !userCan('fb.tables', $vendorId) && !userCan('fb.manage', $vendorId)) {
                throw new RuntimeException('Not allowed');
            }
            $orderId = (int)($_POST['order_id'] ?? 0);
            $newTableId = (int)($_POST['new_table_id'] ?? 0);
            $order = posQ("SELECT table_id FROM pos_orders WHERE id = ? AND vendor_id = ?", [$orderId, $vendorId]);
            if (!$order) throw new RuntimeException('Order not found');

            if ($order['table_id']) {
                posExec(
                    "UPDATE pos_tables SET status = 'available', current_order_id = NULL WHERE id = ?",
                    [(int)$order['table_id']]
                );
            }
            posExec(
                "UPDATE pos_tables SET status = 'occupied', current_order_id = ? WHERE id = ? AND vendor_id = ?",
                [$orderId, $newTableId, $vendorId]
            );
            posExec("UPDATE pos_orders SET table_id = ? WHERE id = ?", [$newTableId, $orderId]);
            setMessage('✅ Order transferred');
            redirect('/?page=vendor-restaurant-pos&order_id=' . $orderId);
        }

        // ── SPLIT: record one payment ──
        if ($action === 'add_split') {
            if (!$__isSuperAdmin && !$__isVendorOwner && !userCan('pos.payment.collect', $vendorId)) {
                throw new RuntimeException('Not allowed');
            }
            $orderId   = (int)($_POST['order_id'] ?? 0);
            $splitType = $_POST['split_type'] ?? 'covers';
            $amount    = (float)($_POST['split_amount'] ?? 0);
            $method    = $_POST['split_method'] ?? 'cash';
            $label     = trim($_POST['split_label'] ?? '');
            $paidBy    = trim($_POST['split_paid_by'] ?? '');
            $roomNum   = trim($_POST['split_room_number'] ?? '');
            $itemIds   = trim($_POST['split_item_ids'] ?? '');
            $covers    = (int)($_POST['split_covers'] ?? 0);

            if ($orderId <= 0 || $amount <= 0) throw new RuntimeException('Invalid split');

            $order = posQ("SELECT * FROM pos_orders WHERE id = ? AND vendor_id = ?", [$orderId, $vendorId]);
            if (!$order) throw new RuntimeException('Order not found');

            $existing = posSplitsForOrder($orderId);
            $alreadyPaid = posSplitTotal($existing);
            $remaining = (float)$order['total'] - $alreadyPaid;

            if ($amount > $remaining + 0.01) {
                throw new RuntimeException('Split exceeds remaining (' . posMoney($remaining, $baseCurrency) . ')');
            }

            $folioId = null;
            if ($method === 'room' && $roomNum) {
                $f = posQ("SELECT id FROM folios WHERE room_number = ? AND status = 'in_house' AND vendor_id = ? LIMIT 1", [$roomNum, $vendorId]);
                $folioId = $f ? (int)$f['id'] : null;
            }

            posExec(
                "INSERT INTO pos_split_payments
                 (order_id, vendor_id, split_type, split_label, item_ids, covers_count, amount, payment_method, room_number, folio_id, paid_by, created_by)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                [
                    $orderId, $vendorId, $splitType, $label ?: null,
                    $itemIds ?: null, $covers ?: null,
                    $amount, $method, $roomNum ?: null, $folioId, $paidBy ?: null, $userId,
                ]
            );

            if ($folioId) {
                posExec(
                    "INSERT INTO folio_charges (folio_id, description, amount, charge_type, created_at)
                     VALUES (?, ?, ?, 'restaurant', NOW())",
                    [$folioId, 'Restaurant split: ' . $order['order_number'], $amount]
                );
            }

            $newPaid = $alreadyPaid + $amount;
            if ($newPaid >= (float)$order['total'] - 0.01) {
                posExec("UPDATE pos_orders SET status = 'paid', closed_at = NOW(), payment_method = 'split' WHERE id = ?", [$orderId]);
                if (!empty($order['table_id'])) {
                    posExec("UPDATE pos_tables SET status = 'cleaning', current_order_id = NULL WHERE id = ?", [(int)$order['table_id']]);
                }
                setMessage('✅ All splits paid — order closed');
                redirect('/?page=vendor-restaurant-pos');
            }

            setMessage('✅ Split recorded — ' . posMoney($amount, $baseCurrency) . ' · Remaining: ' . posMoney($remaining - $amount, $baseCurrency));
        }

        // ── SPLIT: delete a split ──
        if ($action === 'delete_split') {
            if (!$__isSuperAdmin && !$__isVendorOwner && !userCan('pos.payment.collect', $vendorId)) {
                throw new RuntimeException('Not allowed');
            }
            $splitId = (int)($_POST['split_id'] ?? 0);
            posExec("DELETE FROM pos_split_payments WHERE id = ? AND vendor_id = ?", [$splitId, $vendorId]);
            setMessage('🗑️ Split removed');
        }

    } catch (Throwable $e) {
        setMessage('Error: ' . $e->getMessage(), 'error');
    }
    
    // Final redirect after POST
    $rid = (int)($_POST['restaurant_id'] ?? ($_GET['restaurant_id'] ?? 0));
    redirect('/?page=vendor-restaurant-pos' . (isset($_POST['order_id']) ? '&order_id=' . (int)$_POST['order_id'] : '') . ($rid > 0 ? '&restaurant_id=' . $rid : ''));
}

// ============================================
// LOAD DATA
// ============================================
$view = $_GET['view'] ?? 'pos';

// ── Venue Switcher Logic ──
$myVenues = posQA("SELECT id, name, venue_class FROM restaurants WHERE vendor_id = ? AND is_active = 1 ORDER BY name ASC", [$vendorId]);
$__isGroupMode = (($_GET['restaurant_id'] ?? '') === 'all');
$selectedVenueId = $__isGroupMode ? 0 : (int)($_GET['restaurant_id'] ?? 0);
if ($selectedVenueId === 0 && !$__isGroupMode && !empty($myVenues)) {
    $selectedVenueId = (int)$myVenues[0]['id'];
}
if (!in_array($view, ['pos', 'kitchen', 'reports', 'close-out'], true)) $view = 'pos';

$tables = posQA(
    "SELECT t.*,
            o.order_number,
            o.guest_name,
            o.covers,
            o.created_at as order_started,
            TIMESTAMPDIFF(MINUTE, o.created_at, NOW()) as elapsed_minutes
     FROM pos_tables t
     LEFT JOIN pos_orders o ON t.current_order_id = o.id
     WHERE t.vendor_id = ? AND (t.restaurant_id = ? OR ? = 1) AND t.is_active = 1
     ORDER BY t.zone, t.name",
    [$vendorId, $selectedVenueId, (int)$__isGroupMode]
);

$openOrders = posQA(
    "SELECT o.*, t.name as table_name,
            TIMESTAMPDIFF(MINUTE, o.created_at, NOW()) as elapsed_minutes
     FROM pos_orders o
     LEFT JOIN pos_tables t ON o.table_id = t.id
     WHERE o.vendor_id = ? AND (o.restaurant_id = ? OR ? = 1) 
       AND o.status IN ('open','preparing','served')
     ORDER BY FIELD(o.status, 'open','preparing','served'), o.created_at ASC",
    [$vendorId, $selectedVenueId, (int)$__isGroupMode]
);

$activeOrderId = (int)($_GET['order_id'] ?? 0);
$activeOrder = null;
$activeItems = [];
$activeSplits = [];
$activePaidAmount = 0.0;
$activeRemaining = 0.0;
if ($activeOrderId) {
    $activeOrder = posQ("SELECT * FROM pos_orders WHERE id = ? AND vendor_id = ?", [$activeOrderId, $vendorId]);
    if ($activeOrder) {
        $activeItems = posQA(
            "SELECT * FROM pos_order_items WHERE order_id = ? ORDER BY created_at ASC",
            [$activeOrderId]
        );
        $activeSplits = posSplitsForOrder($activeOrderId);
        $activePaidAmount = posSplitTotal($activeSplits);
        $activeRemaining = max(0, (float)$activeOrder['total'] - $activePaidAmount);
    }
}

// Menu items for the picker
$menuItems = [];
$__activeVenueName = 'Unknown Venue';
try {
    $menuItems = posQA(
        "SELECT mi.id, mi.name, mi.category, mi.price, mi.is_available, mi.is_sold_out
         FROM menu_items mi
         WHERE mi.restaurant_id = ? AND mi.is_available = 1 AND mi.is_sold_out = 0
         ORDER BY mi.category, mi.display_order, mi.name",
        [$selectedVenueId]
    );
    
    foreach ($myVenues as $mv) {
        if ((int)$mv['id'] === $selectedVenueId) {
            $__activeVenueName = $mv['name'] . ' (' . ucfirst($mv['venue_class']) . ')';
            break;
        }
    }
} catch (Throwable $e) {
    $__activeVenueName = "Error loading venue";
}

// Group menu by category
$menuByCat = [];
foreach ($menuItems as $mi) {
    $cat = $mi['category'] ?: 'other';
    if (!isset($menuByCat[$cat])) $menuByCat[$cat] = [];
    $menuByCat[$cat][] = $mi;
}

$catLabels = [
    'appetizer' => 'Appetizers', 'starter' => 'Starters', 'main' => 'Mains',
    'dessert' => 'Desserts', 'drink' => 'Drinks', 'beverage' => 'Beverages',
    'wine' => 'Wines', 'beer' => 'Beers', 'cocktail' => 'Cocktails',
    'breakfast' => 'Breakfast', 'lunch' => 'Lunch', 'dinner' => 'Dinner',
    'side' => 'Sides', 'soup' => 'Soups', 'salad' => 'Salads',
    'pizza' => 'Pizza', 'seafood' => 'Seafood', 'grill' => 'Grill',
    'coffee' => 'Coffee', 'tea' => 'Tea', 'other' => 'Other',
];

// Kitchen queue
$kitchenQueue = posQA(
    "SELECT i.*, o.order_number, o.table_id, o.guest_name, o.status as order_status,
            t.name as table_name,
            TIMESTAMPDIFF(MINUTE, i.created_at, NOW()) as elapsed_minutes
     FROM pos_order_items i
     JOIN pos_orders o ON i.order_id = o.id
     LEFT JOIN pos_tables t ON o.table_id = t.id
     WHERE o.vendor_id = ? AND o.restaurant_id = ? AND o.status IN ('open','preparing','served')
       AND i.status IN ('pending','preparing')
     ORDER BY
        FIELD(i.status, 'pending','preparing'),
        i.created_at ASC",
    [$vendorId, $selectedVenueId]
);

// ── DATE RANGE LOGIC ──
$range = $_GET['range'] ?? 'today';
$dateStart = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
$dateEnd   = $_GET['end_date']   ?? date('Y-m-d');

if ($range === 'yesterday') {
    $dateStart = date('Y-m-d', strtotime('-1 day'));
    $dateEnd   = date('Y-m-d', strtotime('-1 day'));
} elseif ($range === '7days') {
    $dateStart = date('Y-m-d', strtotime('-7 days'));
} elseif ($range === '30days') {
    $dateStart = date('Y-m-d', strtotime('-30 days'));
}

// KPIs
$today = date('Y-m-d'); // Still used for "Today's Sales" widget
$todayStats = posQ(
        "SELECT
            COUNT(*) as orders,
        COALESCE(SUM(total),0) as revenue,
        COALESCE(SUM(covers),0) as covers,
        COALESCE(SUM(total),0) / GREATEST(COUNT(*), 1) as avg_check
     FROM pos_orders
     WHERE vendor_id = ? AND restaurant_id = ? AND DATE(closed_at) = ? AND status = 'paid'",
    [$vendorId, $selectedVenueId, $today]
);
$todayStats['orders'] = (int)($todayStats['orders'] ?? 0);
$todayStats['revenue'] = (float)($todayStats['revenue'] ?? 0);
$todayStats['covers'] = (int)($todayStats['covers'] ?? 0);
$todayStats['avg_check'] = (float)($todayStats['avg_check'] ?? 0);

$openCount = count($openOrders);
$occupiedTables = count(array_filter($tables, fn($t) => $t['status'] === 'occupied'));
$availableTables = count(array_filter($tables, fn($t) => $t['status'] === 'available'));

// Reports data
$salesByDay = [];
$topItems = [];
$hourlySales = [];
if ($view === 'reports') {
    $dtStart = $dateStart . ' 00:00:00';
    $dtEnd   = $dateEnd . ' 23:59:59';

    // Filter condition: either specific venue (via table) or group
    $venueFilter = $__isGroupMode
        ? "1=1"
        : "t.restaurant_id = " . (int)$selectedVenueId;

    $salesByDay = posQA(
        "SELECT DATE(o.closed_at) as d,
                COUNT(*) as orders,
                COALESCE(SUM(o.total),0) as revenue
         FROM pos_orders o
         LEFT JOIN pos_tables t ON o.table_id = t.id
         WHERE o.vendor_id = ? AND o.status = 'paid'
           AND o.closed_at >= ? AND o.closed_at <= ?
           AND ({$venueFilter})
         GROUP BY DATE(o.closed_at)
         ORDER BY d DESC",
        [$vendorId, $dtStart, $dtEnd]
    );

    $topItems = posQA(
        "SELECT i.item_name, SUM(i.quantity) as qty, SUM(i.subtotal) as revenue
         FROM pos_order_items i
         JOIN pos_orders o ON i.order_id = o.id
         LEFT JOIN pos_tables t ON o.table_id = t.id
         WHERE o.vendor_id = ? AND o.status = 'paid'
           AND o.closed_at >= ? AND o.closed_at <= ?
           AND ({$venueFilter})
         GROUP BY i.item_name
         ORDER BY revenue DESC
         LIMIT 10",
        [$vendorId, $dtStart, $dtEnd]
    );

    $hourlySales = posQA(
        "SELECT HOUR(o.closed_at) as h,
                COUNT(*) as orders,
                COALESCE(SUM(o.total),0) as revenue
         FROM pos_orders o
         LEFT JOIN pos_tables t ON o.table_id = t.id
         WHERE o.vendor_id = ? AND o.status = 'paid'
           AND o.closed_at >= ? AND o.closed_at <= ?
           AND ({$venueFilter})
         GROUP BY HOUR(o.closed_at)
         ORDER BY h ASC",
        [$vendorId, $dtStart, $dtEnd]
    );
}

// ── Z-REPORT / CLOSE-OUT DATA ──
$zReport = null;
$zPayments = [];
$zTopItems = [];
$zVoids = null;
if ($view === 'close-out') 
$dtStart = $dateStart . ' 00:00:00';
$dtEnd   = $dateEnd . ' 23:59:59';
$venueFilter = $__isGroupMode
    ? "1=1"
    : "t.restaurant_id = " . (int)$selectedVenueId;

$individual = posQ(
    "SELECT COUNT(*) as orders, COALESCE(SUM(o.total),0) as revenue
     FROM pos_orders o
     LEFT JOIN pos_tables t ON o.table_id = t.id
     WHERE o.vendor_id = ? AND o.status = 'paid'
       AND (o.guest_name IS NULL OR o.guest_name = '')
       AND o.closed_at >= ? AND o.closed_at <= ?
       AND ({$venueFilter})",
    [$vendorId, $dtStart, $dtEnd]
);

$group = posQ(
    "SELECT COUNT(*) as orders, COALESCE(SUM(o.total),0) as revenue
     FROM pos_orders o
     LEFT JOIN pos_tables t ON o.table_id = t.id
     WHERE o.vendor_id = ? AND o.status = 'paid'
       AND o.guest_name IS NOT NULL AND o.guest_name != ''
       AND o.closed_at >= ? AND o.closed_at <= ?
       AND ({$venueFilter})",
    [$vendorId, $dtStart, $dtEnd]
);

    $zTopItems = posQA(
        "SELECT i.item_name, SUM(i.quantity) as qty, SUM(i.subtotal) as revenue
         FROM pos_order_items i
         JOIN pos_orders o ON i.order_id = o.id
         LEFT JOIN pos_tables t ON o.table_id = t.id
         WHERE o.vendor_id = ? AND o.status = 'paid'
           AND o.closed_at >= ? AND o.closed_at <= ?
           AND ({$venueFilter})
         GROUP BY i.item_name
         ORDER BY qty DESC
         LIMIT 10",
        [$vendorId, $dtStart, $dtEnd]
    );

    $zVoids = posQ(
        "SELECT COUNT(*) as count, COALESCE(SUM(o.total), 0) as amount
         FROM pos_orders o
         LEFT JOIN pos_tables t ON o.table_id = t.id
         WHERE o.vendor_id = ? AND o.status = 'cancelled'
           AND o.closed_at >= ? AND o.closed_at <= ?
           AND ({$venueFilter})",
        [$vendorId, $dtStart, $dtEnd]
    );
}

require_once __DIR__ . '/../../includes/header.php';
?>

<style>
:root {
    --grad: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    --glass: rgba(255,255,255,0.03);
    --border: rgba(255,255,255,0.08);
    --text-dim: #a0aec0;
    --text-hi: #a3bffa;
    --green: #00b894;
    --red: #f5576c;
    --orange: #f6ad55;
    --blue: #00d4ff;
    --purple: #b794f4;
}

.pos-page { background: #0f0c29; min-height: 100vh; padding: 100px 0 80px; color: white; }
.pos-page .container { max-width: 1800px; margin: 0 auto; padding: 0 20px; }

.pos-head { display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 16px; margin-bottom: 22px; }
.pos-head h1 { font-size: 28px; font-weight: 800; margin-bottom: 4px; display: flex; align-items: center; gap: 10px; }
.pos-head h1 .grad { background: var(--grad); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
.pos-head .sub { color: var(--text-dim); font-size: 13px; }
.pos-head .actions { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }

.btn-pos { padding: 10px 18px; border-radius: 10px; font-weight: 700; font-size: 12px; cursor: pointer;
    border: none; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; transition: all 0.2s; }
.btn-pos-primary { background: var(--grad); color: white; }
.btn-pos-primary:hover { transform: translateY(-1px); box-shadow: 0 8px 24px rgba(102,126,234,0.4); color: white; }
.btn-pos-outline { background: rgba(255,255,255,0.05); color: #cbd5e0; border: 1px solid var(--border); }
.btn-pos-outline:hover { background: rgba(255,255,255,0.1); color: white; }
.btn-pos-success { background: rgba(0,184,148,0.15); color: var(--green); border: 1px solid rgba(0,184,148,0.3); }
.btn-pos-danger { background: rgba(245,87,108,0.15); color: var(--red); border: 1px solid rgba(245,87,108,0.3); }
.btn-pos-purple { background: rgba(183,148,244,0.15); color: var(--purple); border: 1px solid rgba(183,148,244,0.3); }

.pos-views { display: flex; gap: 4px; background: rgba(255,255,255,0.03); border: 1px solid var(--border); border-radius: 12px; padding: 4px; }
.pos-view { padding: 8px 16px; border-radius: 8px; font-size: 12px; font-weight: 700; color: var(--text-dim); text-decoration: none; transition: all 0.2s; display: inline-flex; align-items: center; gap: 5px; }
.pos-view:hover { background: rgba(255,255,255,0.05); color: white; }
.pos-view.active { background: var(--grad); color: white; }

.pos-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; margin-bottom: 20px; }
.pos-stat { background: var(--glass); border: 1px solid var(--border); border-radius: 14px; padding: 16px; }
.pos-stat .v { font-size: 22px; font-weight: 800; color: var(--text-hi); margin-bottom: 2px; line-height: 1.1; }
.pos-stat .l { font-size: 11px; color: var(--text-dim); text-transform: uppercase; letter-spacing: 0.05em; font-weight: 800; }
.pos-stat.green .v { color: var(--green); }
.pos-stat.orange .v { color: var(--orange); }
.pos-stat.blue .v { color: var(--blue); }
.pos-stat.purple .v { color: var(--purple); }

.pos-split { display: grid; grid-template-columns: 1fr 460px; gap: 20px; }
@media (max-width: 1200px) { .pos-split { grid-template-columns: 1fr; } }

.pos-section { background: var(--glass); border: 1px solid var(--border); border-radius: 16px; padding: 20px; margin-bottom: 20px; }
.pos-section h2 { font-size: 16px; font-weight: 800; margin-bottom: 16px; display: flex; align-items: center; gap: 8px; }
.pos-section h2 .badge { margin-left: auto; padding: 3px 10px; border-radius: 50px; font-size: 11px; font-weight: 800; background: rgba(102,126,234,0.15); color: var(--text-hi); }

.tables-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 12px; }
.table-tile {
    border: 2px solid;
    border-radius: 14px;
    padding: 16px 12px;
    text-align: center;
    cursor: pointer;
    transition: all 0.2s;
    position: relative;
    min-height: 130px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}
.table-tile:hover { transform: translateY(-3px); box-shadow: 0 10px 30px rgba(0,0,0,0.3); }
.table-tile.available { border-color: rgba(0,184,148,0.4); background: rgba(0,184,148,0.05); }
.table-tile.occupied { border-color: rgba(0,212,255,0.5); background: rgba(0,212,255,0.08); }
.table-tile.reserved { border-color: rgba(246,173,85,0.4); background: rgba(246,173,85,0.05); }
.table-tile.cleaning { border-color: rgba(160,174,192,0.3); background: rgba(160,174,192,0.05); }

.table-tile .head { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px; }
.table-tile .icon {
    width: 36px; height: 36px;
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 16px;
    background: rgba(255,255,255,0.06);
}
.table-tile.occupied .icon { background: rgba(0,212,255,0.15); color: var(--blue); }
.table-tile.available .icon { background: rgba(0,184,148,0.15); color: var(--green); }
.table-tile.reserved .icon { background: rgba(246,173,85,0.15); color: var(--orange); }
.table-tile.cleaning .icon { background: rgba(160,174,192,0.15); color: var(--text-dim); }

.table-tile .timer {
    font-size: 10px;
    font-family: 'SF Mono', Monaco, monospace;
    font-weight: 800;
    padding: 3px 7px;
    border-radius: 50px;
    background: rgba(0,0,0,0.3);
    color: var(--blue);
}
.table-tile .timer.warn { background: rgba(246,173,85,0.2); color: var(--orange); }
.table-tile .timer.late { background: rgba(245,87,108,0.2); color: var(--red); }

.table-tile .name { font-weight: 800; font-size: 14px; margin-bottom: 2px; }
.table-tile .guest { font-size: 11px; color: var(--text-dim); margin-bottom: 2px; }
.table-tile .cap { font-size: 10px; color: var(--text-dim); }
.table-tile .status { font-size: 9px; text-transform: uppercase; font-weight: 800; letter-spacing: 0.05em; margin-top: 6px; }

.order-card {
    background: rgba(0,0,0,0.2);
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 14px 16px;
    margin-bottom: 10px;
    cursor: pointer;
    transition: all 0.2s;
    display: block;
    text-decoration: none;
    color: white;
}
.order-card:hover { border-color: rgba(102,126,234,0.4); color: white; transform: translateX(3px); }
.order-card.active { border-color: var(--purple); background: rgba(183,148,244,0.08); }
.order-card.urgent { border-left: 3px solid var(--red); }
.order-card .head { display: flex; justify-content: space-between; margin-bottom: 6px; }
.order-card .ref { font-family: 'SF Mono', Monaco, monospace; font-size: 12px; color: var(--text-hi); font-weight: 800; }
.order-card .total { font-size: 15px; font-weight: 800; color: var(--blue); font-family: 'SF Mono', Monaco, monospace; }
.order-card .meta { font-size: 12px; color: var(--text-dim); }
.order-card .meta .table { color: var(--text-hi); font-weight: 700; }
.order-card .status-pill {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 50px;
    font-size: 10px;
    font-weight: 800;
    text-transform: uppercase;
}
.status-pill.open { background: rgba(102,126,234,0.2); color: var(--text-hi); }
.status-pill.preparing { background: rgba(246,173,85,0.2); color: var(--orange); }
.status-pill.served { background: rgba(0,212,255,0.2); color: var(--blue); }
.status-pill.paid { background: rgba(0,184,148,0.2); color: var(--green); }

.cart-panel {
    background: var(--glass);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 20px;
    position: sticky;
    top: 90px;
    max-height: calc(100vh - 110px);
    overflow-y: auto;
}
.cart-header { margin-bottom: 16px; padding-bottom: 14px; border-bottom: 1px solid var(--border); }
.cart-header h3 { font-size: 17px; font-weight: 800; margin-bottom: 6px; }
.cart-header .ref { font-family: 'SF Mono', Monaco, monospace; font-size: 12px; color: var(--text-dim); display: flex; justify-content: space-between; align-items: center; }
.cart-header .ref .status-pill { font-family: -apple-system, sans-serif; }

.cart-items { max-height: 320px; overflow-y: auto; margin-bottom: 16px; padding-right: 4px; }
.cart-items::-webkit-scrollbar { width: 6px; }
.cart-items::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 3px; }

.cart-item {
    display: grid;
    grid-template-columns: 1fr auto auto;
    gap: 10px;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid rgba(255,255,255,0.05);
    font-size: 13px;
}
.cart-item:last-child { border-bottom: none; }
.cart-item-info { flex: 1; min-width: 0; }
.cart-item-name { font-weight: 600; margin-bottom: 2px; }
.cart-item-qty { font-size: 11px; color: var(--text-dim); }
.cart-item-notes { font-size: 10px; color: var(--orange); margin-top: 2px; font-style: italic; }
.cart-item-price { font-weight: 800; color: var(--blue); white-space: nowrap; font-family: 'SF Mono', Monaco, monospace; }
.cart-item-del {
    background: rgba(245,87,108,0.15);
    color: var(--red);
    border: none;
    width: 26px; height: 26px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 11px;
    display: flex; align-items: center; justify-content: center;
}

.cart-total { padding-top: 14px; border-top: 1px solid var(--border); }
.total-row { display: flex; justify-content: space-between; padding: 5px 0; font-size: 13px; }
.total-row.grand { font-size: 20px; font-weight: 800; padding-top: 12px; margin-top: 8px; border-top: 1px solid var(--border); color: var(--blue); font-family: 'SF Mono', Monaco, monospace; }

.fg-pos { margin-bottom: 12px; }
.fg-pos label { display: block; font-size: 11px; color: var(--text-hi); margin-bottom: 6px; text-transform: uppercase; font-weight: 700; letter-spacing: 0.04em; }
.fg-pos input, .fg-pos select, .fg-pos textarea {
    width: 100%; padding: 10px 13px;
    background: rgba(255,255,255,0.05);
    border: 1px solid var(--border);
    border-radius: 10px;
    color: white;
    font-size: 13px;
    outline: none;
    font-family: inherit;
    transition: all 0.2s;
}
.fg-pos textarea { min-height: 50px; resize: vertical; }
.fg-pos input:focus, .fg-pos select:focus, .fg-pos textarea:focus { border-color: #667eea; box-shadow: 0 0 0 3px rgba(102,126,234,0.2); }
.fg-pos select option { background: #1a1a2e; }
.frow-pos { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.frow-pos-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; }

.menu-search-wrap { position: relative; margin-bottom: 12px; }
.menu-search-wrap i { position: absolute; left: 14px; top: 50%; transform: translateY(-50%); color: var(--text-dim); font-size: 13px; }
.menu-search { width: 100%; padding: 12px 14px 12px 38px; background: rgba(255,255,255,0.05); border: 1px solid var(--border); border-radius: 12px; color: white; font-size: 13px; outline: none; }
.menu-search:focus { border-color: #667eea; box-shadow: 0 0 0 3px rgba(102,126,234,0.2); }

.menu-cats { display: flex; gap: 4px; margin-bottom: 12px; overflow-x: auto; padding-bottom: 2px; }
.menu-cat { flex-shrink: 0; padding: 6px 14px; border-radius: 50px; font-size: 11px; font-weight: 700; background: rgba(255,255,255,0.05); border: 1px solid var(--border); color: var(--text-dim); cursor: pointer; white-space: nowrap; font-family: inherit; transition: all 0.15s; }
.menu-cat:hover { background: rgba(102,126,234,0.15); color: white; }
.menu-cat.active { background: var(--grad); color: white; border-color: transparent; }

.menu-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 8px; max-height: 260px; overflow-y: auto; padding: 2px; }
.menu-item {
    background: rgba(0,0,0,0.2);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 10px 12px;
    cursor: pointer;
    transition: all 0.15s;
    text-align: left;
    font-family: inherit;
    color: white;
}
.menu-item:hover { border-color: rgba(102,126,234,0.4); background: rgba(102,126,234,0.08); transform: translateY(-2px); }
.menu-item .name { font-size: 12px; font-weight: 700; margin-bottom: 3px; line-height: 1.3; }
.menu-item .price { font-size: 11px; color: var(--blue); font-weight: 800; font-family: 'SF Mono', Monaco, monospace; }
.menu-item .cat { font-size: 9px; color: var(--text-dim); text-transform: uppercase; font-weight: 700; letter-spacing: 0.05em; margin-top: 2px; }

.kitchen-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 14px; }
.kitchen-ticket {
    background: rgba(0,0,0,0.25);
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 14px;
    position: relative;
    transition: all 0.2s;
}
.kitchen-ticket.pending { border-left: 3px solid var(--orange); }
.kitchen-ticket.preparing { border-left: 3px solid var(--blue); }
.kitchen-ticket.urgent { border-color: rgba(245,87,108,0.4); }
.kitchen-ticket .tk-head {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid var(--border);
}
.kitchen-ticket .tk-ref { font-family: 'SF Mono', Monaco, monospace; font-size: 11px; font-weight: 800; color: var(--text-hi); }
.kitchen-ticket .tk-table { font-size: 13px; font-weight: 800; }
.kitchen-ticket .tk-time { font-size: 10px; font-family: 'SF Mono', Monaco, monospace; font-weight: 800; }
.kitchen-ticket .tk-time.warn { color: var(--orange); }
.kitchen-ticket .tk-time.late { color: var(--red); }
.kitchen-ticket .tk-item { font-size: 13px; padding: 4px 0; display: flex; justify-content: space-between; }
.kitchen-ticket .tk-item .qty { font-weight: 800; color: var(--blue); font-family: 'SF Mono', Monaco, monospace; }
.kitchen-ticket .tk-notes { font-size: 11px; color: var(--orange); font-style: italic; margin-top: 6px; padding-top: 6px; border-top: 1px dashed var(--border); }

.pos-empty { padding: 50px 30px; text-align: center; color: var(--text-dim); }
.pos-empty i.big { font-size: 48px; opacity: 0.3; display: block; margin-bottom: 16px; color: var(--text-hi); }

.pos-modal { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.85); z-index: 9999; align-items: center; justify-content: center; padding: 20px; overflow-y: auto; }
.pos-modal.active { display: flex; }
.pos-modal-box { background: #1a1a2e; border: 1px solid rgba(102,126,234,0.3); border-radius: 20px; padding: 26px; max-width: 500px; width: 100%; max-height: 92vh; overflow-y: auto; }
.pos-modal-box h3 { font-size: 19px; font-weight: 800; margin-bottom: 6px; }
.pos-modal-box .m-sub { font-size: 12px; color: var(--text-dim); margin-bottom: 18px; }
.pos-modal-actions { display: flex; gap: 10px; margin-top: 20px; padding-top: 16px; border-top: 1px solid var(--border); }
.pos-modal-actions .btn-pos { flex: 1; justify-content: center; padding: 12px; }

@media (max-width: 720px) {
    .pos-head h1 { font-size: 22px; }
    .pos-split { grid-template-columns: 1fr; }
    .cart-panel { position: static; max-height: none; }
    .tables-grid { grid-template-columns: repeat(auto-fill, minmax(110px, 1fr)); }
    .table-tile { min-height: 110px; padding: 12px 8px; }
    .menu-grid { grid-template-columns: repeat(auto-fill, minmax(110px, 1fr)); }
    .frow-pos, .frow-pos-3 { grid-template-columns: 1fr; }
}
</style>

<div class="pos-page">
    <div class="container">

        <div class="pos-head">
    <div>
        <h1>🍽️ Restaurant <span class="grad">POS</span></h1>
       <p class="sub" style="display:flex; align-items:center; gap:10px;">
    <?= htmlspecialchars($vendor['company_name'] ?? '') ?>
    <?php if ($__isGroupMode): ?>
        <span style="color: var(--gold); font-weight: 700;">· 🏢 All Venues (Group View)</span>
    <?php endif; ?>
            
                        <?php if (count($myVenues) > 1): ?>
                <form method="GET" style="margin:0; display:flex; gap:8px; align-items:center; background:rgba(255,255,255,0.03); padding:4px; border-radius:8px; border:1px solid rgba(255,255,255,0.08);">
                    <input type="hidden" name="page" value="vendor-restaurant-pos">
                    <input type="hidden" name="view" value="<?= htmlspecialchars($view) ?>">
                    
                   <select name="restaurant_id" onchange="this.form.submit()" style="background: #1a1a2e; color: white; padding: 6px 12px; border-radius: 8px; border: 1px solid rgba(102,126,234,0.4); font-size: 13px; font-weight: 700; cursor: pointer; outline: none;">
    <option value="all" <?= ($_GET['restaurant_id'] ?? '') === 'all' ? 'selected' : '' ?>>🏢 All Venues (Group)</option>
    <?php foreach ($myVenues as $v): ?>
        <option value="<?= $v['id'] ?>" <?= (string)$selectedVenueId === (string)$v['id'] ? 'selected' : '' ?>>
            <?= htmlspecialchars($v['name']) ?> (<?= ucfirst($v['venue_class']) ?>)
        </option>
    <?php endforeach; ?>
</select>

                    <select name="range" onchange="this.form.submit()" style="background: #1a1a2e; color: white; padding: 6px 12px; border-radius: 6px; border: 1px solid rgba(102,126,234,0.4); font-size: 13px; font-weight: 700; cursor: pointer; outline: none;">
                        <option value="today" <?= ($_GET['range'] ?? 'today') === 'today' ? 'selected' : '' ?>>Today</option>
                        <option value="yesterday" <?= ($_GET['range'] ?? '') === 'yesterday' ? 'selected' : '' ?>>Yesterday</option>
                        <option value="7days" <?= ($_GET['range'] ?? '') === '7days' ? 'selected' : '' ?>>Last 7 Days</option>
                        <option value="30days" <?= ($_GET['range'] ?? '') === '30days' ? 'selected' : '' ?>>Last 30 Days</option>
                    </select>
                </form>
            <?php endif; ?>

            · <?= $openCount ?> open · <?= $occupiedTables ?> tables occupied
        </p>
    </div>
            <div class="actions">
                <div class="pos-views">
                    <a href="?page=vendor-restaurant-pos&view=pos&restaurant_id=<?= $selectedVenueId ?>" class="pos-view <?= $view === 'pos' ? 'active' : '' ?>">
                        <i class="fas fa-chair"></i> Floor
                    </a>
                    <a href="?page=vendor-restaurant-pos&view=kitchen&restaurant_id=<?= $selectedVenueId ?>" class="pos-view <?= $view === 'kitchen' ? 'active' : '' ?>">
                        <i class="fas fa-fire"></i> Kitchen
                        <?php if (count($kitchenQueue) > 0): ?>
                            <span style="background:var(--red); color:white; padding:1px 7px; border-radius:50px; font-size:9px; margin-left:4px;"><?= count($kitchenQueue) ?></span>
                        <?php endif; ?>
                    </a>
                    <a href="?page=vendor-restaurant-pos&view=reports&restaurant_id=<?= $selectedVenueId ?>" class="pos-view <?= $view === 'reports' ? 'active' : '' ?>">
                        <i class="fas fa-chart-line"></i> Reports
                    </a>
                    <a href="?page=vendor-restaurant-pos&view=close-out&restaurant_id=<?= $selectedVenueId ?>" class="pos-view <?= $view === 'close-out' ? 'active' : '' ?>">
                        <i class="fas fa-file-invoice-dollar"></i> Z-Report
                    </a>
                </div>
                <?php if ($__isSuperAdmin || $__isVendorOwner || userCan('fb.tables', $vendorId) || userCan('fb.manage', $vendorId)): ?>
                <button class="btn-pos btn-pos-primary" onclick="openModal('newTableModal')">
                    <i class="fas fa-plus"></i> Table
                </button>
                <?php endif; ?>
               <?php if (!$__isGroupMode && ($__isSuperAdmin || $__isVendorOwner || userCan('pos.order.create', $vendorId))): ?>
<button class="btn-pos btn-pos-purple" onclick="openModal('newOrderModal')">
    <i class="fas fa-receipt"></i> New Order
</button>
<?php endif; ?>
            </div>
        </div>

        <div class="pos-stats">
            <div class="pos-stat green">
                <div class="v"><?= posMoney($todayStats['revenue'], $baseCurrency) ?></div>
                <div class="l">Today's Sales</div>
            </div>
            <div class="pos-stat blue">
                <div class="v"><?= $todayStats['orders'] ?></div>
                <div class="l">Orders Closed</div>
            </div>
            <div class="pos-stat purple">
                <div class="v"><?= $todayStats['covers'] ?></div>
                <div class="l">Covers Today</div>
            </div>
            <div class="pos-stat orange">
                <div class="v"><?= posMoney($todayStats['avg_check'], $baseCurrency) ?></div>
                <div class="l">Avg Check</div>
            </div>
            <div class="pos-stat">
                <div class="v"><?= $occupiedTables ?></div>
                <div class="l">Tables Occupied</div>
            </div>
            <div class="pos-stat">
                <div class="v"><?= $availableTables ?></div>
                <div class="l">Available</div>
            </div>
        </div>

        <?php if ($view === 'pos'): ?>

        <div class="pos-split">

            <div>
                <div class="pos-section">
                    <h2>
                        <i class="fas fa-chair" style="color:var(--text-hi);"></i>
                        Tables
                        <span class="badge"><?= count($tables) ?></span>
                    </h2>
                    <?php if (!empty($tables)): ?>
                        <div class="tables-grid">
                            <?php foreach ($tables as $t):
                                $isActive = $activeOrderId && (int)$t['current_order_id'] === $activeOrderId;
                                $elapsed = (int)($t['elapsed_minutes'] ?? 0);
                                $timerClass = $elapsed > 60 ? 'late' : ($elapsed > 30 ? 'warn' : '');
                                $statusIcons = [
                                    'available' => 'fa-door-open',
                                    'occupied' => 'fa-users',
                                    'reserved' => 'fa-clock',
                                    'cleaning' => 'fa-broom',
                                ];
                            ?>
                                <div class="table-tile <?= $t['status'] ?> <?= $isActive ? 'active' : '' ?>"
                                     onclick="handleTable(<?= (int)$t['id'] ?>, '<?= $t['status'] ?>', <?= (int)($t['current_order_id'] ?? 0) ?>)">
                                    <div class="head">
                                        <div class="icon">
                                            <i class="fas <?= $statusIcons[$t['status']] ?? 'fa-chair' ?>"></i>
                                        </div>
                                        <?php if ($t['status'] === 'occupied' && $t['order_started']): ?>
                                            <div class="timer <?= $timerClass ?>"><?= $elapsed ?>m</div>
                                        <?php endif; ?>
                                    </div>
                                    <div>
                                        <div class="name"><?= htmlspecialchars($t['name']) ?></div>
                                        <?php if (!empty($t['guest_name'])): ?>
                                            <div class="guest"><?= htmlspecialchars($t['guest_name']) ?></div>
                                        <?php endif; ?>
                                        <div class="cap"><?= (int)$t['capacity'] ?> seats</div>
                                        <div class="status"><?= ucfirst($t['status']) ?></div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="pos-empty">
                            <i class="fas fa-chair big"></i>
                            <div style="font-weight: 700; margin-bottom: 8px;">No tables yet</div>
                            <p style="font-size: 12px; margin-bottom: 16px;">Add your first table to get started</p>
                            <?php if ($__isSuperAdmin || $__isVendorOwner || userCan('fb.tables', $vendorId) || userCan('fb.manage', $vendorId)): ?>
                            <button class="btn-pos btn-pos-primary" onclick="openModal('newTableModal')">
                                <i class="fas fa-plus"></i> Add Table
                            </button>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <?php if (!empty($openOrders)): ?>
                <div class="pos-section">
                    <h2>
                        <i class="fas fa-receipt" style="color:var(--blue);"></i>
                        Open Orders
                        <span class="badge"><?= count($openOrders) ?></span>
                    </h2>
                    <?php foreach ($openOrders as $o):
                        $elapsed = (int)($o['elapsed_minutes'] ?? 0);
                        $isUrgent = $elapsed > 45 && in_array($o['status'], ['open', 'preparing'], true);
                    ?>
                        <a href="?page=vendor-restaurant-pos&order_id=<?= (int)$o['id'] ?>&restaurant_id=<?= $selectedVenueId ?>"
                           class="order-card <?= $activeOrderId === (int)$o['id'] ? 'active' : '' ?> <?= $isUrgent ? 'urgent' : '' ?>">
                            <div class="head">
                                <div>
                                    <div class="ref"><?= htmlspecialchars($o['order_number']) ?></div>
                                    <div class="meta">
                                        <?php if ($o['table_name']): ?>
                                            <span class="table"><i class="fas fa-chair"></i> <?= htmlspecialchars($o['table_name']) ?></span>
                                        <?php else: ?>
                                            <?= ucfirst(str_replace('_', ' ', $o['order_type'])) ?>
                                        <?php endif; ?>
                                        <?php if ($o['guest_name']): ?>
                                            · <?= htmlspecialchars($o['guest_name']) ?>
                                        <?php endif; ?>
                                        <?php if ($o['covers'] > 1): ?>
                                            · <?= (int)$o['covers'] ?> covers
                                        <?php endif; ?>
                                        · <span style="color: <?= $isUrgent ? 'var(--red)' : 'var(--text-dim)' ?>;"><?= $elapsed ?>m ago</span>
                                    </div>
                                </div>
                                <div style="text-align: right;">
                                    <div class="total"><?= posMoney($o['total'], $baseCurrency) ?></div>
                                    <span class="status-pill <?= $o['status'] ?>"><?= ucfirst($o['status']) ?></span>
                                </div>
                            </div>
                        </a>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>

            <div>
                <?php if ($activeOrder): ?>
                    <div class="cart-panel">
                        <div style="background: rgba(102,126,234,0.1); border: 1px solid rgba(102,126,234,0.3); color: var(--text-hi); padding: 12px 16px; border-radius: 12px; margin-bottom: 16px; font-size: 13px; font-weight: 800; display: flex; align-items: center; gap: 8px;">
                            <i class="fas fa-map-marker-alt" style="color: var(--purple);"></i>
                            <?= htmlspecialchars($__activeVenueName) ?>
                        </div>
                        
                        <div class="cart-header">
                            <h3>Active Order</h3>
                            <div class="ref">
                                <span><?= htmlspecialchars($activeOrder['order_number']) ?></span>
                                <span class="status-pill <?= $activeOrder['status'] ?>"><?= ucfirst($activeOrder['status']) ?></span>
                            </div>
                            <?php if ($activeOrder['guest_name'] || $activeOrder['covers'] > 1): ?>
                                <div style="font-size: 12px; color: var(--text-dim); margin-top: 6px;">
                                    <?php if ($activeOrder['guest_name']): ?><?= htmlspecialchars($activeOrder['guest_name']) ?><?php endif; ?>
                                    <?php if ($activeOrder['covers'] > 1): ?> · <?= (int)$activeOrder['covers'] ?> covers<?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>

                        <?php if (!empty($menuItems) && ($__isSuperAdmin || $__isVendorOwner || userCan('pos.order.create', $vendorId))): ?>
                        <div class="fg-pos">
                            <label><i class="fas fa-book"></i> Menu</label>
                            <div class="menu-search-wrap">
                                <i class="fas fa-search"></i>
                                <input type="text" class="menu-search" id="menuSearch" placeholder="Search menu items…" oninput="filterMenu(this.value)">
                            </div>
                            <div class="menu-cats" id="menuCats">
                                <button type="button" class="menu-cat active" data-cat="all" onclick="filterMenuCat(this, 'all')">All</button>
                                <?php foreach ($menuByCat as $cat => $items): ?>
                                    <button type="button" class="menu-cat" data-cat="<?= htmlspecialchars($cat) ?>" onclick="filterMenuCat(this, '<?= htmlspecialchars($cat) ?>')">
                                        <?= htmlspecialchars($catLabels[$cat] ?? ucfirst($cat)) ?>
                                    </button>
                                <?php endforeach; ?>
                            </div>
                            <div class="menu-grid" id="menuGrid">
                                <?php foreach ($menuItems as $mi): ?>
                                    <button type="button" class="menu-item"
                                            data-cat="<?= htmlspecialchars($mi['category']) ?>"
                                            data-search="<?= htmlspecialchars(strtolower($mi['name'])) ?>"
                                            onclick="addMenuItem(<?= (int)$mi['id'] ?>, '<?= htmlspecialchars(addslashes($mi['name'])) ?>', <?= (float)$mi['price'] ?>)">
                                        <div class="name"><?= htmlspecialchars($mi['name']) ?></div>
                                        <div class="price"><?= posMoney($mi['price'], $baseCurrency) ?></div>
                                        <div class="cat"><?= htmlspecialchars($catLabels[$mi['category']] ?? $mi['category']) ?></div>
                                    </button>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php elseif (empty($menuItems)): ?>
                        <div style="padding: 16px; background: rgba(246,173,85,0.08); border: 1px solid rgba(246,173,85,0.3); border-radius: 10px; margin-bottom: 14px; font-size: 12px; color: #cbd5e0;">
                            <i class="fas fa-info-circle" style="color: var(--orange);"></i>
                            No menu items yet. <a href="/?page=vendor-menu" style="color: var(--text-hi); font-weight: 700;">Add menu items →</a>
                        </div>
                        <?php endif; ?>

                        <?php if ($__isSuperAdmin || $__isVendorOwner || userCan('pos.order.create', $vendorId)): ?>
                        <details style="margin-bottom: 14px;">
                            <summary style="font-size: 11px; font-weight: 700; color: var(--text-hi); text-transform: uppercase; letter-spacing: 0.04em; cursor: pointer; padding: 6px 0; user-select: none;">
                                <i class="fas fa-plus-circle"></i> Add custom item
                            </summary>
                            <form method="POST" style="margin-top: 10px;">
                                <input type="hidden" name="action" value="add_item">
                                <input type="hidden" name="order_id" value="<?= (int)$activeOrder['id'] ?>">
                                <input type="hidden" name="restaurant_id" value="<?= $selectedVenueId ?>">
                                <div class="fg-pos">
                                    <input type="text" name="item_name" placeholder="Item name" required>
                                </div>
                                <div class="frow-pos">
                                    <div class="fg-pos">
                                        <input type="number" step="0.01" name="unit_price" placeholder="Price" required>
                                    </div>
                                    <div class="fg-pos">
                                        <input type="number" name="quantity" value="1" min="1" placeholder="Qty">
                                    </div>
                                </div>
                                <div class="fg-pos">
                                    <input type="text" name="item_notes" placeholder="Special instructions (optional)">
                                </div>
                                <button type="submit" class="btn-pos btn-pos-success" style="width: 100%; justify-content: center;">
                                    <i class="fas fa-plus"></i> Add Item
                                </button>
                            </form>
                        </details>
                        <?php endif; ?>

                        <div class="cart-items">
                            <?php if (!empty($activeItems)): ?>
                                <?php foreach ($activeItems as $item):
                                    $itemStatusMeta = [
                                        'pending' => ['color' => 'var(--orange)', 'icon' => 'clock'],
                                        'preparing' => ['color' => 'var(--blue)', 'icon' => 'spinner'],
                                        'ready' => ['color' => 'var(--green)', 'icon' => 'check'],
                                        'served' => ['color' => 'var(--text-dim)', 'icon' => 'check-double'],
                                    ];
                                    $im = $itemStatusMeta[$item['status']] ?? $itemStatusMeta['pending'];
                                ?>
                                    <div class="cart-item">
                                        <div class="cart-item-info">
                                            <div class="cart-item-name">
                                                <i class="fas fa-<?= $im['icon'] ?>" style="color: <?= $im['color'] ?>; font-size: 10px; margin-right: 4px;"></i>
                                                <?= htmlspecialchars($item['item_name']) ?>
                                            </div>
                                            <div class="cart-item-qty"><?= (int)$item['quantity'] ?> × <?= posMoney($item['unit_price'], $baseCurrency) ?></div>
                                            <?php if (!empty($item['notes'])): ?>
                                                <div class="cart-item-notes">"<?= htmlspecialchars($item['notes']) ?>"</div>
                                            <?php endif; ?>
                                        </div>
                                        <div class="cart-item-price"><?= posMoney($item['subtotal'], $baseCurrency) ?></div>
                                        <?php if ($__isSuperAdmin || $__isVendorOwner || userCan('pos.order.void', $vendorId)): ?>
                                        <form method="POST" style="display: inline;">
                                            <input type="hidden" name="action" value="delete_item">
                                            <input type="hidden" name="item_id" value="<?= (int)$item['id'] ?>">
                                            <input type="hidden" name="order_id" value="<?= (int)$activeOrder['id'] ?>">
                                            <input type="hidden" name="restaurant_id" value="<?= $selectedVenueId ?>">
                                            <button type="submit" class="cart-item-del" onclick="return confirm('Remove item?')">
                                                <i class="fas fa-times"></i>
                                            </button>
                                        </form>
                                        <?php else: ?>
                                        <div style="width: 26px;"></div>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="pos-empty" style="padding: 30px 20px;">
                                    <i class="fas fa-shopping-basket" style="font-size: 32px;"></i>
                                    <div style="font-size: 12px; margin-top: 8px;">No items yet</div>
                                </div>
                            <?php endif; ?>
                        </div>

                        <div class="cart-total">
                            <div class="total-row"><span>Subtotal</span><span><?= posMoney($activeOrder['subtotal'], $baseCurrency) ?></span></div>
                            <?php if ((float)$activeOrder['discount'] > 0): ?>
                                <div class="total-row" style="color: var(--green);">
                                    <span>Discount <?= $activeOrder['discount_reason'] ? '(' . htmlspecialchars($activeOrder['discount_reason']) . ')' : '' ?></span>
                                    <span>-<?= posMoney($activeOrder['discount'], $baseCurrency) ?></span>
                                </div>
                            <?php endif; ?>
                            <div class="total-row"><span>Service (5%)</span><span><?= posMoney($activeOrder['service_charge'], $baseCurrency) ?></span></div>
                            <div class="total-row"><span>Tax (10%)</span><span><?= posMoney($activeOrder['tax'], $baseCurrency) ?></span></div>
                            <div class="total-row grand"><span>Total</span><span><?= posMoney($activeOrder['total'], $baseCurrency) ?></span></div>
                        </div>

                        <div style="margin-top: 14px; display: flex; gap: 6px; flex-wrap: wrap;">
                            <?php if ($__isSuperAdmin || $__isVendorOwner || userCan('pos.order.discount', $vendorId)): ?>
                            <button type="button" class="btn-pos btn-pos-outline" style="flex: 1; justify-content: center; font-size: 11px;" onclick="openModal('discountModal')">
                                <i class="fas fa-percent"></i> Discount
                            </button>
                            <?php endif; ?>
                            <?php if ($__isSuperAdmin || $__isVendorOwner || userCan('fb.tables', $vendorId) || userCan('fb.manage', $vendorId)): ?>
                            <button type="button" class="btn-pos btn-pos-outline" style="flex: 1; justify-content: center; font-size: 11px;" onclick="openModal('transferModal')">
                                <i class="fas fa-exchange-alt"></i> Transfer
                            </button>
                            <?php endif; ?>
                            <a href="?page=vendor-restaurant-pos&action=print_receipt&order_id=<?= (int)$activeOrder['id'] ?>" target="_blank" class="btn-pos btn-pos-outline" style="flex: 1; justify-content: center; font-size: 11px;">
                                <i class="fas fa-print"></i> Receipt
                            </a>
                            <a href="?page=vendor-restaurant-pos&action=print_kitchen&order_id=<?= (int)$activeOrder['id'] ?>" target="_blank" class="btn-pos btn-pos-outline" style="flex: 1; justify-content: center; font-size: 11px;">
                                <i class="fas fa-fire"></i> KOT
                            </a>
                        </div>

                        <?php if (!empty($activeSplits)): ?>
                        <div style="margin-top: 14px; padding: 12px; background: rgba(0,212,255,0.08); border: 1px solid rgba(0,212,255,0.3); border-radius: 10px;">
                            <div style="font-size: 11px; font-weight: 800; color: var(--blue); text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 8px;">
                                Splits (<?= count($activeSplits) ?>) — Paid: <?= posMoney($activePaidAmount, $baseCurrency) ?> · Remaining: <?= posMoney($activeRemaining, $baseCurrency) ?>
                            </div>
                            <?php foreach ($activeSplits as $sp): ?>
                                <div style="display: grid; grid-template-columns: 1fr auto auto; gap: 8px; align-items: center; padding: 6px 0; border-bottom: 1px solid rgba(255,255,255,0.06); font-size: 12px;">
                                    <div>
                                        <strong><?= htmlspecialchars($sp['split_label'] ?: 'Split') ?></strong>
                                        <div style="font-size: 10px; color: var(--text-dim);">
                                            <?= strtoupper($sp['payment_method']) ?>
                                            <?= $sp['paid_by'] ? ' · ' . htmlspecialchars($sp['paid_by']) : '' ?>
                                            <?= $sp['room_number'] ? ' · Room ' . htmlspecialchars($sp['room_number']) : '' ?>
                                        </div>
                                    </div>
                                    <div style="font-weight: 800; color: var(--green); font-family: monospace;">
                                        <?= posMoney($sp['amount'], $baseCurrency) ?>
                                    </div>
                                    <form method="POST" style="margin: 0;">
                                        <input type="hidden" name="action" value="delete_split">
                                        <input type="hidden" name="split_id" value="<?= (int)$sp['id'] ?>">
                                        <input type="hidden" name="order_id" value="<?= (int)$activeOrder['id'] ?>">
                                        <input type="hidden" name="restaurant_id" value="<?= $selectedVenueId ?>">
                                        <button type="submit" style="background: rgba(245,87,108,0.15); color: var(--red); border: none; padding: 4px 8px; border-radius: 6px; cursor: pointer; font-size: 10px;" onclick="return confirm('Remove split?')">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </form>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>

                        <?php if ($activeOrder['status'] !== 'paid' && ($__isSuperAdmin || $__isVendorOwner || userCan('pos.payment.collect', $vendorId))): ?>
                        <button type="button" class="btn-pos btn-pos-outline" style="width: 100%; justify-content: center; margin-top: 14px;" onclick="openModal('splitModal')">
                            <i class="fas fa-users"></i> Split Payment
                        </button>
                        <?php endif; ?>

                        <?php if ($__isSuperAdmin || $__isVendorOwner || userCan('pos.order.close', $vendorId) || userCan('pos.payment.collect', $vendorId)): ?>
                        <form method="POST" style="margin-top: 14px;">
                            <input type="hidden" name="action" value="close_order">
                            <input type="hidden" name="order_id" value="<?= (int)$activeOrder['id'] ?>">
                            <input type="hidden" name="restaurant_id" value="<?= $selectedVenueId ?>">
                            <div class="fg-pos">
                                <label>Payment Method</label>
                                <select name="payment_method" id="paymentMethod" onchange="toggleRoomCharge(this.value)">
                                    <option value="cash">💵 Cash</option>
                                    <option value="card">💳 Card</option>
                                    <option value="mobile">📱 Mobile Money</option>
                                    <option value="room">🏨 Charge to Room</option>
                                </select>
                            </div>
                            <div class="fg-pos" id="roomChargeField" style="display: none;">
                                <label>Room Number</label>
                                <input type="text" name="room_number" placeholder="e.g., 305">
                            </div>
                            <button type="submit" class="btn-pos btn-pos-primary" style="width: 100%; justify-content: center;" onclick="return confirm('Close this order and process payment?')">
                                <i class="fas fa-check"></i> Close Order & Payment
                            </button>
                        </form>
                        <?php endif; ?>

                        <?php if ($__isSuperAdmin || $__isVendorOwner || userCan('pos.order.void', $vendorId)): ?>
                        <form method="POST" style="margin-top: 8px;" onsubmit="return confirm('Void this entire order?')">
                            <input type="hidden" name="action" value="void_order">
                            <input type="hidden" name="order_id" value="<?= (int)$activeOrder['id'] ?>">
                            <input type="hidden" name="restaurant_id" value="<?= $selectedVenueId ?>">
                            <button type="submit" class="btn-pos btn-pos-danger" style="width: 100%; justify-content: center; padding: 10px;">
                                <i class="fas fa-ban"></i> Void Order
                            </button>
                        </form>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div class="cart-panel">
                        <div class="pos-empty">
                            <i class="fas fa-cash-register big"></i>
                            <div style="font-weight: 700; margin-bottom: 8px;">No order selected</div>
                            <p style="font-size: 12px; margin-bottom: 16px;">Select an open order or click an available table</p>
                            <?php if ($__isSuperAdmin || $__isVendorOwner || userCan('pos.order.create', $vendorId)): ?>
                            <button class="btn-pos btn-pos-primary" onclick="openModal('newOrderModal')">
                                <i class="fas fa-plus"></i> New Order
                            </button>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <?php elseif ($view === 'kitchen'): ?>

        <div class="pos-section">
            <h2>
                <i class="fas fa-fire" style="color:var(--red);"></i>
                Kitchen Display System
                <span class="badge"><?= count($kitchenQueue) ?> tickets</span>
                <span style="margin-left: auto; font-size: 11px; color: var(--text-dim); font-weight: 500;">
                    Auto-refresh every 15s
                </span>
            </h2>

            <?php if (empty($kitchenQueue)): ?>
                <div class="pos-empty">
                    <i class="fas fa-check-circle big" style="color: var(--green);"></i>
                    <div style="font-weight: 700; margin-bottom: 8px;">All caught up!</div>
                    <p style="font-size: 12px;">No items in the kitchen queue right now.</p>
                </div>
            <?php else: ?>
                <div class="kitchen-grid">
                    <?php foreach ($kitchenQueue as $item):
                        $elapsed = (int)($item['elapsed_minutes'] ?? 0);
                        $timeClass = $elapsed > 20 ? 'late' : ($elapsed > 10 ? 'warn' : '');
                        $isUrgent = $elapsed > 20;
                    ?>
                        <div class="kitchen-ticket <?= $item['status'] ?> <?= $isUrgent ? 'urgent' : '' ?>">
                            <div class="tk-head">
                                <div>
                                    <div class="tk-ref"><?= htmlspecialchars($item['order_number']) ?></div>
                                    <div class="tk-table">
                                        <?php if ($item['table_name']): ?>
                                            <i class="fas fa-chair"></i> <?= htmlspecialchars($item['table_name']) ?>
                                        <?php else: ?>
                                            Takeaway
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div style="text-align: right;">
                                    <div class="tk-time <?= $timeClass ?>"><?= $elapsed ?>m</div>
                                    <div style="font-size: 9px; color: var(--text-dim); text-transform: uppercase; font-weight: 800; margin-top: 2px;">
                                        <?= ucfirst($item['status']) ?>
                                    </div>
                                </div>
                            </div>
                            <div class="tk-item">
                                <span><span class="qty"><?= (int)$item['quantity'] ?>×</span> <?= htmlspecialchars($item['item_name']) ?></span>
                                <span style="font-size: 11px; color: var(--text-dim);"><?= posMoney($item['subtotal'], $baseCurrency) ?></span>
                            </div>
                            <?php if (!empty($item['notes'])): ?>
                                <div class="tk-notes">                                    <i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($item['notes']) ?>
                                </div>
                            <?php endif; ?>
                            <?php if ($__isSuperAdmin || $__isVendorOwner || userCan('pos.kds.update', $vendorId)): ?>
                            <div style="margin-top: 12px; display: flex; gap: 6px;">
                                <?php if ($item['status'] === 'pending'): ?>
                                    <button type="button" class="btn-pos btn-pos-primary" style="flex: 1; justify-content: center; padding: 8px; font-size: 11px;" onclick="updateItemStatus(<?= (int)$item['id'] ?>, 'preparing')">
                                        <i class="fas fa-play"></i> Start
                                    </button>
                                <?php elseif ($item['status'] === 'preparing'): ?>
                                    <button type="button" class="btn-pos btn-pos-success" style="flex: 1; justify-content: center; padding: 8px; font-size: 11px;" onclick="updateItemStatus(<?= (int)$item['id'] ?>, 'ready')">
                                        <i class="fas fa-check"></i> Ready
                                    </button>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <?php elseif ($view === 'reports'): ?>

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
            <div class="pos-section">
                <h2><i class="fas fa-fire" style="color:var(--orange);"></i> Top Selling Items (30d)</h2>
                <?php if (!empty($topItems)): ?>
                    <?php $maxRev = max(array_column($topItems, 'revenue')) ?: 1; ?>
                    <?php foreach ($topItems as $i => $ti):
                        $pct = round(($ti['revenue'] / $maxRev) * 100);
                    ?>
                        <div style="display: grid; grid-template-columns: 1fr auto auto; gap: 12px; align-items: center; margin-bottom: 12px;">
                            <div>
                                <div style="font-size: 12px; font-weight: 700;"><?= htmlspecialchars(mb_substr($ti['item_name'], 0, 34)) ?></div>
                                <div style="font-size: 10px; color: var(--text-dim); margin-top: 2px;"><?= (int)$ti['qty'] ?> sold</div>
                            </div>
                            <div style="width: 100px; height: 6px; background: rgba(255,255,255,0.06); border-radius: 50px; overflow: hidden;">
                                <div style="height: 100%; width: <?= $pct ?>%; background: var(--grad); border-radius: 50px;"></div>
                            </div>
                            <div style="font-family: 'SF Mono', Monaco, monospace; font-weight: 800; color: var(--text-hi); font-size: 13px; min-width: 90px; text-align: right;">
                                <?= posMoney($ti['revenue'], $baseCurrency) ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="pos-empty" style="padding: 30px;">
                        <i class="fas fa-chart-bar" style="font-size: 32px;"></i>
                        <p style="font-size: 12px; margin-top: 8px;">No sales data yet</p>
                    </div>
                <?php endif; ?>
            </div>

            <div class="pos-section">
                <h2><i class="fas fa-clock" style="color:var(--blue);"></i> Today's Hourly Sales</h2>
                <?php if (!empty($hourlySales)): ?>
                    <?php $maxHourly = max(array_column($hourlySales, 'revenue')) ?: 1; ?>
                    <?php foreach ($hourlySales as $hs):
                        $pct = round(($hs['revenue'] / $maxHourly) * 100);
                    ?>
                        <div style="display: grid; grid-template-columns: 60px 1fr auto; gap: 12px; align-items: center; margin-bottom: 10px;">
                            <div style="font-size: 12px; font-weight: 700; color: var(--text-hi); font-family: 'SF Mono', Monaco, monospace;">
                                <?= str_pad((string)$hs['h'], 2, '0', STR_PAD_LEFT) ?>:00
                            </div>
                            <div style="height: 6px; background: rgba(255,255,255,0.06); border-radius: 50px; overflow: hidden;">
                                <div style="height: 100%; width: <?= $pct ?>%; background: linear-gradient(90deg, #00d4ff, #667eea); border-radius: 50px;"></div>
                            </div>
                            <div style="font-family: 'SF Mono', Monaco, monospace; font-weight: 800; color: var(--text-hi); font-size: 12px; min-width: 90px; text-align: right;">
                                <?= posMoney($hs['revenue'], $baseCurrency) ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="pos-empty" style="padding: 30px;">
                        <i class="fas fa-clock" style="font-size: 32px;"></i>
                        <p style="font-size: 12px; margin-top: 8px;">No sales yet today</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- ── GROUP VS INDIVIDUAL SALES ── -->
        <div class="pos-section">
            <h2><i class="fas fa-users" style="color:var(--purple);"></i> Sales Breakdown</h2>
            <div style="display:grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                <div style="background:rgba(0,212,255,0.05); border:1px solid rgba(0,212,255,0.2); border-radius:12px; padding:16px;">
                    <div style="font-size:12px; color:var(--text-dim); text-transform:uppercase; font-weight:800; margin-bottom:8px;">Individual Sales (Walk-ins)</div>
                                       <?php
                        $individual = posQ(
                            "SELECT COUNT(*) as orders, COALESCE(SUM(total),0) as revenue
                             FROM pos_orders
                             WHERE vendor_id = ? AND restaurant_id = ? AND status = 'paid'
                               AND (guest_name IS NULL OR guest_name = '')
                               AND closed_at >= ? AND closed_at <= ?",
                            [$vendorId, $selectedVenueId, $dateStart . ' 00:00:00', $dateEnd . ' 23:59:59']
                        );
                    ?>
                    <div style="font-size:24px; font-weight:800; color:var(--blue);"><?= posMoney($individual['revenue'] ?? 0, $baseCurrency) ?></div>
                    <div style="font-size:11px; color:var(--text-dim);"><?= (int)($individual['orders'] ?? 0) ?> orders</div>
                </div>

                <div style="background:rgba(183,148,244,0.05); border:1px solid rgba(183,148,244,0.2); border-radius:12px; padding:16px;">
                    <div style="font-size:12px; color:var(--text-dim); text-transform:uppercase; font-weight:800; margin-bottom:8px;">Group Sales (Reservations)</div>
                                       <?php
                        $group = posQ(
                            "SELECT COUNT(*) as orders, COALESCE(SUM(total),0) as revenue
                             FROM pos_orders
                             WHERE vendor_id = ? AND restaurant_id = ? AND status = 'paid'
                               AND guest_name IS NOT NULL AND guest_name != ''
                               AND closed_at >= ? AND closed_at <= ?",
                            [$vendorId, $selectedVenueId, $dateStart . ' 00:00:00', $dateEnd . ' 23:59:59']
                        );
                    ?>
                    <div style="font-size:24px; font-weight:800; color:var(--purple);"><?= posMoney($group['revenue'] ?? 0, $baseCurrency) ?></div>
                    <div style="font-size:11px; color:var(--text-dim);"><?= (int)($group['orders'] ?? 0) ?> orders</div>
                </div>
            </div>
        </div>

            <div class="pos-section">
                <h2><i class="fas fa-chart-line" style="color:var(--green);"></i> 30-Day Sales</h2>
            <?php if (!empty($salesByDay)): ?>
                <?php $maxDaily = max(array_column($salesByDay, 'revenue')) ?: 1; ?>
                <div style="display: flex; align-items: flex-end; gap: 4px; height: 200px; padding: 10px 0;">
                    <?php foreach (array_reverse($salesByDay) as $sd):
                        $pct = ($sd['revenue'] / $maxDaily) * 100;
                    ?>
                        <div style="flex: 1; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; gap: 4px; height: 100%;">
                            <div style="width: 100%; height: <?= max(2, $pct) ?>%; background: linear-gradient(180deg, #667eea, #764ba2); border-radius: 4px 4px 0 0; min-height: 4px; position: relative;"
                                 title="<?= date('M j', strtotime($sd['d'])) ?>: <?= posMoney($sd['revenue'], $baseCurrency) ?> (<?= (int)$sd['orders'] ?> orders)">
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div style="display: flex; justify-content: space-between; font-size: 10px; color: var(--text-dim); margin-top: 8px;">
                    <span><?= date('M j', strtotime(end($salesByDay)['d'])) ?></span>
                    <span><?= date('M j', strtotime($salesByDay[0]['d'])) ?></span>
                </div>
            <?php else: ?>
                <div class="pos-empty" style="padding: 40px;">
                    <i class="fas fa-chart-line" style="font-size: 32px;"></i>
                    <p style="font-size: 12px; margin-top: 8px;">No sales data yet</p>
                </div>
            <?php endif; ?>
        </div>

        <?php elseif ($view === 'close-out'): ?>

        <div class="pos-section" style="max-width: 800px; margin: 0 auto;">
            <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 20px;">
                <div>
                    <h2 style="margin-bottom: 4px;"><i class="fas fa-file-invoice-dollar" style="color:var(--green);"></i> Z-Report</h2>
                    <p style="color: var(--text-dim); font-size: 13px;">
                        Shift Close-Out for <strong><?= htmlspecialchars($__activeVenueName) ?></strong> · <?= date('l, F j, Y') ?>
                    </p>
                </div>
                <div style="display: flex; gap: 8px;">
                    <button onclick="window.print()" class="btn-pos btn-pos-primary">
                        <i class="fas fa-print"></i> Print Report
                    </button>
                </div>
            </div>

            <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin-bottom: 24px;">
                <div style="background: rgba(255,255,255,0.03); border: 1px solid var(--border); border-radius: 12px; padding: 16px; text-align: center;">
                    <div style="font-size: 24px; font-weight: 800; color: var(--green);"><?= posMoney($zReport['grand_total'] ?? 0, $baseCurrency) ?></div>
                    <div style="font-size: 11px; color: var(--text-dim); text-transform: uppercase; font-weight: 800; margin-top: 4px;">Total Revenue</div>
                </div>
                <div style="background: rgba(255,255,255,0.03); border: 1px solid var(--border); border-radius: 12px; padding: 16px; text-align: center;">
                    <div style="font-size: 24px; font-weight: 800; color: var(--blue);"><?= (int)($zReport['total_orders'] ?? 0) ?></div>
                    <div style="font-size: 11px; color: var(--text-dim); text-transform: uppercase; font-weight: 800; margin-top: 4px;">Total Orders</div>
                </div>
                <div style="background: rgba(255,255,255,0.03); border: 1px solid var(--border); border-radius: 12px; padding: 16px; text-align: center;">
                    <div style="font-size: 24px; font-weight: 800; color: var(--purple);"><?= (int)($zReport['total_covers'] ?? 0) ?></div>
                    <div style="font-size: 11px; color: var(--text-dim); text-transform: uppercase; font-weight: 800; margin-top: 4px;">Total Covers</div>
                </div>
                <div style="background: rgba(245,87,108,0.08); border: 1px solid rgba(245,87,108,0.2); border-radius: 12px; padding: 16px; text-align: center;">
                    <div style="font-size: 24px; font-weight: 800; color: var(--red);"><?= posMoney($zVoids['amount'] ?? 0, $baseCurrency) ?></div>
                    <div style="font-size: 11px; color: var(--red); text-transform: uppercase; font-weight: 800; margin-top: 4px;">Voids (<?= (int)($zVoids['count'] ?? 0) ?>)</div>
                </div>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <!-- Payment Breakdown -->
                <div>
                    <h3 style="font-size: 14px; font-weight: 800; margin-bottom: 12px; border-bottom: 1px solid var(--border); padding-bottom: 8px;">Payment Breakdown</h3>
                    <?php if (!empty($zPayments)): ?>
                        <table style="width: 100%; border-collapse: collapse; font-size: 13px;">
                            <?php foreach ($zPayments as $p): ?>
                                <tr style="border-bottom: 1px solid rgba(255,255,255,0.04);">
                                    <td style="padding: 8px 0; text-transform: capitalize; font-weight: 700;">
                                        <?= str_replace('_', ' ', $p['payment_method']) ?>
                                        <span style="color: var(--text-dim); font-weight: 400; margin-left: 6px;">(<?= (int)$p['count'] ?> orders)</span>
                                    </td>
                                    <td style="padding: 8px 0; text-align: right; font-family: monospace; font-weight: 800; color: var(--green);">
                                        <?= posMoney($p['amount'], $baseCurrency) ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </table>
                    <?php else: ?>
                        <p style="color: var(--text-dim); font-size: 13px;">No payments recorded today.</p>
                    <?php endif; ?>
                </div>

                <!-- Top Items -->
                <div>
                    <h3 style="font-size: 14px; font-weight: 800; margin-bottom: 12px; border-bottom: 1px solid var(--border); padding-bottom: 8px;">Top Selling Items</h3>
                    <?php if (!empty($zTopItems)): ?>
                        <table style="width: 100%; border-collapse: collapse; font-size: 13px;">
                            <?php foreach ($zTopItems as $item): ?>
                                <tr style="border-bottom: 1px solid rgba(255,255,255,0.04);">
                                    <td style="padding: 8px 0; font-weight: 700;">
                                        <span style="color: var(--blue); font-family: monospace; margin-right: 6px;"><?= (int)$item['qty'] ?>×</span>
                                        <?= htmlspecialchars($item['item_name']) ?>
                                    </td>
                                    <td style="padding: 8px 0; text-align: right; font-family: monospace; color: var(--text-dim);">
                                        <?= posMoney($item['revenue'], $baseCurrency) ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </table>
                    <?php else: ?>
                        <p style="color: var(--text-dim); font-size: 13px;">No items sold today.</p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Signature / Cash Drop -->
            <div style="margin-top: 32px; padding-top: 24px; border-top: 1px dashed var(--border); display: grid; grid-template-columns: 1fr 1fr; gap: 40px;">
                <div>
                    <div style="font-size: 11px; color: var(--text-dim); text-transform: uppercase; font-weight: 800; margin-bottom: 30px;">Manager Signature</div>
                    <div style="border-bottom: 1px solid var(--text-dim);"></div>
                </div>
                <div>
                    <div style="font-size: 11px; color: var(--text-dim); text-transform: uppercase; font-weight: 800; margin-bottom: 8px;">Cash Drawer Count</div>
                    <div style="display: flex; justify-content: space-between; font-size: 13px; margin-bottom: 4px;">
                        <span>Expected Cash:</span>
                        <span style="font-family: monospace; font-weight: 800;"><?= posMoney(array_sum(array_map(function($p) { return $p['payment_method'] === 'cash' ? $p['amount'] : 0; }, $zPayments)), $baseCurrency) ?></span>
                    </div>
                    <div style="display: flex; justify-content: space-between; font-size: 13px;">
                        <span>Actual Cash:</span>
                        <span style="font-family: monospace; font-weight: 800; border-bottom: 1px solid var(--text-dim); width: 120px; display: inline-block;"></span>
                    </div>
                </div>
            </div>
            
            <div style="text-align: center; margin-top: 40px;">
                <a href="?page=vendor-restaurant-pos&restaurant_id=<?= $selectedVenueId ?>" class="btn-pos btn-pos-outline">
                    <i class="fas fa-arrow-left"></i> Back to Floor
                </a>
            </div>
        </div>

        <style>
        @media print {
            body * { visibility: hidden; }
            .pos-section, .pos-section * { visibility: visible; }
            .pos-section { position: absolute; left: 0; top: 0; width: 100%; max-width: 100% !important; background: white !important; color: black !important; border: none !important; padding: 0 !important; }
            .pos-section h2, .pos-section p, .pos-section h3, .pos-section div { color: black !important; }
            .pos-section table td, .pos-section table th { color: black !important; border-bottom: 1px solid #ccc !important; }
            .btn-pos, .pos-head, .pos-stats, .pos-views { display: none !important; }
            .pos-section > div:first-child { margin-bottom: 20px !important; }
        }
        </style>

        <?php endif; ?>

    </div>
</div>

<?php if ($__isSuperAdmin || $__isVendorOwner || userCan('fb.tables', $vendorId) || userCan('fb.manage', $vendorId)): ?>
<div class="pos-modal" id="newTableModal">
    <div class="pos-modal-box">
        <h3>➕ Add Table</h3>
        <p class="m-sub">Create a new table for the floor plan.</p>
        <form method="POST">
            <input type="hidden" name="action" value="create_table">
            <div class="fg-pos">
                <label>Table Name</label>
                <input type="text" name="name" placeholder="e.g., Table 1, T5, Patio 3" required autofocus>
            </div>
            <div class="frow-pos">
                <div class="fg-pos">
                    <label>Capacity</label>
                    <input type="number" name="capacity" value="4" min="1" max="20">
                </div>
                <div class="fg-pos">
                    <label>Zone (optional)</label>
                    <input type="text" name="zone" placeholder="e.g., Patio">
                </div>
            </div>
            <div class="pos-modal-actions">
                <button type="button" class="btn-pos btn-pos-outline" onclick="closeModal('newTableModal')">Cancel</button>
                <button type="submit" class="btn-pos btn-pos-primary">
                    <i class="fas fa-check"></i> Create
                </button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<?php if ($__isSuperAdmin || $__isVendorOwner || userCan('pos.order.create', $vendorId)): ?>
<div class="pos-modal" id="newOrderModal">
    <div class="pos-modal-box">
        <h3>🍽️ New Order</h3>
        <p class="m-sub">Start an order for a table or takeaway.</p>
        <form method="POST">
            <input type="hidden" name="action" value="create_order">
            <input type="hidden" name="restaurant_id" value="<?= $selectedVenueId ?>">
            <div class="frow-pos">
                <div class="fg-pos">
                    <label>Order Type</label>
                    <select name="order_type">
                        <option value="dine_in">🍽️ Dine In</option>
                        <option value="takeaway">🥡 Takeaway</option>
                        <option value="room_service">🛎️ Room Service</option>
                    </select>
                </div>
                <div class="fg-pos">
                    <label>Table (optional)</label>
                    <select name="table_id">
                        <option value="">— No table / Takeaway —</option>
                        <?php foreach ($tables as $t): if ($t['status'] === 'available'): ?>
                            <option value="<?= (int)$t['id'] ?>">
                                <?= htmlspecialchars($t['name']) ?> (<?= (int)$t['capacity'] ?> seats)
                            </option>
                        <?php endif; endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="frow-pos">
                <div class="fg-pos">
                    <label>Guest Name (optional)</label>
                    <input type="text" name="guest_name" placeholder="e.g., Mr. Smith">
                </div>
                <div class="fg-pos">
                    <label>Covers</label>
                    <input type="number" name="covers" value="1" min="1" max="30">
                </div>
             </div>
            <div class="fg-pos">
                <label>Room Number (for room service)</label>
                <input type="text" name="room_number" placeholder="e.g., 305">
            </div>
            <div class="pos-modal-actions">
                <button type="button" class="btn-pos btn-pos-outline" onclick="closeModal('newOrderModal')">Cancel</button>
                <button type="submit" class="btn-pos btn-pos-primary">
                    <i class="fas fa-check"></i> Create Order
                </button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<?php if ($activeOrder && ($__isSuperAdmin || $__isVendorOwner || userCan('pos.order.discount', $vendorId))): ?>
<div class="pos-modal" id="discountModal">
    <div class="pos-modal-box">
        <h3>💸 Apply Discount</h3>
        <p class="m-sub">Current subtotal: <strong style="color: var(--blue);"><?= posMoney($activeOrder['subtotal'], $baseCurrency) ?></strong></p>
        <form method="POST">
            <input type="hidden" name="action" value="apply_discount">
            <input type="hidden" name="order_id" value="<?= (int)$activeOrder['id'] ?>">
            <input type="hidden" name="restaurant_id" value="<?= $selectedVenueId ?>">
            <div class="frow-pos">
                <div class="fg-pos">
                    <label>Type</label>
                    <select name="discount_type">
                        <option value="percent">Percentage (%)</option>
                        <option value="fixed">Fixed Amount</option>
                    </select>
                </div>
                <div class="fg-pos">
                    <label>Value</label>
                    <input type="number" step="0.01" name="discount_value" placeholder="e.g., 10" required>
                </div>
            </div>
            <div class="fg-pos">
                <label>Reason</label>
                <input type="text" name="discount_reason" placeholder="e.g., Manager approval, loyalty">
            </div>
            <div class="pos-modal-actions">
                <button type="button" class="btn-pos btn-pos-outline" onclick="closeModal('discountModal')">Cancel</button>
                <button type="submit" class="btn-pos btn-pos-success">
                    <i class="fas fa-check"></i> Apply Discount
                </button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<?php if ($activeOrder && ($__isSuperAdmin || $__isVendorOwner || userCan('fb.tables', $vendorId) || userCan('fb.manage', $vendorId))): ?>
<div class="pos-modal" id="transferModal">
    <div class="pos-modal-box">
        <h3>🔄 Transfer Order</h3>
        <p class="m-sub">Move this order to a different table.</p>
        <form method="POST">
            <input type="hidden" name="action" value="transfer_table">
            <input type="hidden" name="order_id" value="<?= (int)$activeOrder['id'] ?>">
            <input type="hidden" name="restaurant_id" value="<?= $selectedVenueId ?>">
            <div class="fg-pos">
                <label>New Table</label>
                <select name="new_table_id" required>
                    <option value="">— Select table —</option>
                    <?php foreach ($tables as $t): if ($t['status'] === 'available' && (int)$t['id'] !== (int)$activeOrder['table_id']): ?>
                        <option value="<?= (int)$t['id'] ?>">
                            <?= htmlspecialchars($t['name']) ?> (<?= (int)$t['capacity'] ?> seats)
                        </option>
                    <?php endif; endforeach; ?>
                </select>
            </div>
            <div class="pos-modal-actions">
                <button type="button" class="btn-pos btn-pos-outline" onclick="closeModal('transferModal')">Cancel</button>
                <button type="submit" class="btn-pos btn-pos-primary">
                    <i class="fas fa-check"></i> Transfer
                </button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<?php if ($activeOrder && $activeOrder['status'] !== 'paid' && ($__isSuperAdmin || $__isVendorOwner || userCan('pos.payment.collect', $vendorId))): ?>
<div class="pos-modal" id="splitModal">
    <div class="pos-modal-box" style="max-width: 600px;">
        <h3>👥 Split Payment</h3>
        <p class="m-sub">Total: <strong style="color: var(--blue);"><?= posMoney($activeOrder['total'], $baseCurrency) ?></strong> · Paid: <?= posMoney($activePaidAmount, $baseCurrency) ?> · Remaining: <strong style="color: var(--orange);"><?= posMoney($activeRemaining, $baseCurrency) ?></strong></p>

        <div style="display: flex; gap: 6px; margin-bottom: 16px;">
            <button type="button" class="btn-pos btn-pos-primary" style="flex: 1; justify-content: center;" onclick="showSplitMode('covers')">
                <i class="fas fa-users"></i> Split by Covers
            </button>
            <button type="button" class="btn-pos btn-pos-outline" style="flex: 1; justify-content: center;" onclick="showSplitMode('items')">
                <i class="fas fa-list"></i> Split by Items
            </button>
        </div>

        <form method="POST" id="splitCoversForm" style="display: block;">
            <input type="hidden" name="action" value="add_split">
            <input type="hidden" name="order_id" value="<?= (int)$activeOrder['id'] ?>">
            <input type="hidden" name="restaurant_id" value="<?= $selectedVenueId ?>">
            <input type="hidden" name="split_type" value="covers">
            <div class="frow-pos">
                <div class="fg-pos">
                    <label>How many ways?</label>
                    <input type="number" id="splitWays" min="2" max="50" value="<?= max(2, (int)$activeOrder['covers']) ?>" oninput="recalcSplitAmount()">
                </div>
                <div class="fg-pos">
                    <label>Per-person amount</label>
                    <input type="text" id="splitPerAmount" readonly style="background: rgba(0,212,255,0.1); color: var(--blue); font-weight: 800;">
                </div>
            </div>
            <div class="fg-pos">
                <label>Label (optional)</label>
                <input type="text" name="split_label" placeholder="e.g., Person 1, Table A, Alice">
            </div>
            <div class="frow-pos">
                <div class="fg-pos">
                    <label>Payment Method</label>
                    <select name="split_method" onchange="document.getElementById('splitRoomField').style.display = this.value === 'room' ? 'block' : 'none';">
                        <option value="cash">💵 Cash</option>
                        <option value="card">💳 Card</option>
                        <option value="mobile">📱 Mobile</option>
                        <option value="room">🏨 Room</option>
                    </select>
                </div>
                <div class="fg-pos">
                    <label>Paid by (optional)</label>
                    <input type="text" name="split_paid_by" placeholder="Person name">
                </div>
            </div>
            <div class="fg-pos" id="splitRoomField" style="display: none;">
                <label>Room Number</label>
                <input type="text" name="split_room_number" placeholder="e.g., 305">
            </div>
            <input type="hidden" name="split_amount" id="splitAmountInput" value="">
            <div class="pos-modal-actions">
                <button type="button" class="btn-pos btn-pos-outline" onclick="closeModal('splitModal')">Cancel</button>
                <button type="submit" class="btn-pos btn-pos-primary">
                    <i class="fas fa-check"></i> Record Payment
                </button>
            </div>
        </form>

        <form method="POST" id="splitItemsForm" style="display: none;">
            <input type="hidden" name="action" value="add_split">
            <input type="hidden" name="order_id" value="<?= (int)$activeOrder['id'] ?>">
            <input type="hidden" name="restaurant_id" value="<?= $selectedVenueId ?>">
            <input type="hidden" name="split_type" value="items">
            <input type="hidden" name="split_amount" id="itemsAmountInput" value="">
            <input type="hidden" name="split_item_ids" id="itemsIdsInput" value="">
            <div class="fg-pos">
                <label>Select items for this person</label>
                <div style="max-height: 250px; overflow-y: auto; background: rgba(0,0,0,0.2); border: 1px solid var(--border); border-radius: 10px; padding: 10px;">
                    <?php foreach ($activeItems as $it): ?>
                        <label style="display: flex; align-items: center; gap: 10px; padding: 8px; border-bottom: 1px solid rgba(255,255,255,0.04); cursor: pointer; text-transform: none; font-size: 13px; color: #cbd5e0; font-weight: 400; letter-spacing: 0;">
                            <input type="checkbox" class="split-item-check" value="<?= (int)$it['id'] ?>" data-amount="<?= (float)$it['subtotal'] ?>" onchange="recalcItemSplit()" style="width: auto;">
                            <span style="flex: 1;"><?= (int)$it['quantity'] ?>× <?= htmlspecialchars($it['item_name']) ?></span>
                            <span style="font-weight: 800; color: var(--blue); font-family: monospace;"><?= posMoney($it['subtotal'], $baseCurrency) ?></span>
                        </label>
                    <?php endforeach; ?>
                </div>
            </div>
            <div class="fg-pos">
                <label>Amount for this split</label>
                <input type="text" id="itemsAmountDisplay" readonly style="background: rgba(0,212,255,0.1); color: var(--blue); font-weight: 800;">
            </div>
            <div class="fg-pos">
                <label>Label</label>
                <input type="text" name="split_label" placeholder="e.g., Alice, Person 2">
            </div>
            <div class="frow-pos">
                <div class="fg-pos">
                    <label>Payment Method</label>
                    <select name="split_method" onchange="document.getElementById('splitRoomFieldItems').style.display = this.value === 'room' ? 'block' : 'none';">
                        <option value="cash">💵 Cash</option>
                        <option value="card">💳 Card</option>
                        <option value="mobile">📱 Mobile</option>
                        <option value="room">🏨 Room</option>
                    </select>
                </div>
                <div class="fg-pos">
                    <label>Paid by</label>
                    <input type="text" name="split_paid_by" placeholder="Person name">
                </div>
            </div>
            <div class="fg-pos" id="splitRoomFieldItems" style="display: none;">
                <label>Room Number</label>
                <input type="text" name="split_room_number" placeholder="e.g., 305">
            </div>
            <div class="pos-modal-actions">
                <button type="button" class="btn-pos btn-pos-outline" onclick="closeModal('splitModal')">Cancel</button>
                <button type="submit" class="btn-pos btn-pos-primary">
                    <i class="fas fa-check"></i> Record Payment
                </button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<script>
function openModal(id) { document.getElementById(id)?.classList.add('active'); }
function closeModal(id) { document.getElementById(id)?.classList.remove('active'); }
document.querySelectorAll('.pos-modal').forEach(m => {
    m.addEventListener('click', e => { if (e.target === m) m.classList.remove('active'); });
});
document.addEventListener('keydown', e => {
    if (e.key === 'Escape') document.querySelectorAll('.pos-modal').forEach(m => m.classList.remove('active'));
});

let currentMenuCat = 'all';
let currentMenuSearch = '';

function filterMenu(q) {
    currentMenuSearch = q.toLowerCase().trim();
    applyMenuFilters();
}

function filterMenuCat(btn, cat) {
    document.querySelectorAll('.menu-cat').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    currentMenuCat = cat;
    applyMenuFilters();
}

function applyMenuFilters() {
    document.querySelectorAll('.menu-item').forEach(item => {
        const catMatch = currentMenuCat === 'all' || item.dataset.cat === currentMenuCat;
        const searchMatch = !currentMenuSearch || item.dataset.search.includes(currentMenuSearch);
        item.style.display = catMatch && searchMatch ? '' : 'none';
    });
}

function addMenuItem(id, name, price) {
    if (!confirm('Add "' + name + '" — ' + price.toFixed(2) + '?')) return;

    const form = document.createElement('form');
    form.method = 'POST';
    form.innerHTML = '<input name="action" value="add_item">'
        + '<input name="order_id" value="<?= (int)($activeOrder['id'] ?? 0) ?>">'
        + '<input name="restaurant_id" value="<?= (int)$selectedVenueId ?>">'
        + '<input name="menu_item_id" value="' + id + '">'
        + '<input name="item_name" value="' + name.replace(/"/g, '&quot;') + '">'
        + '<input name="unit_price" value="' + price + '">'
        + '<input name="quantity" value="1">';
    document.body.appendChild(form);
    form.submit();
}
function handleTable(tableId, status, orderId) {
    if (status === 'occupied' && orderId) {
        window.location.href = '?page=vendor-restaurant-pos&order_id=' + orderId + '&restaurant_id=<?= (int)$selectedVenueId ?>';
    } else if (status === 'available') {
        if (confirm('Create a new order for this table?')) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = '<input name="action" value="create_order">'
                + '<input name="table_id" value="' + tableId + '">'
                + '<input name="order_type" value="dine_in">'
                + '<input name="covers" value="1">'
                + '<input name="restaurant_id" value="<?= (int)$selectedVenueId ?>">';
            document.body.appendChild(form);
            form.submit();
        }
    } else if (status === 'cleaning' || status === 'reserved') {
        if (confirm('Mark this table as available?')) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = '<input name="action" value="set_table_status">'
                + '<input name="table_id" value="' + tableId + '">'
                + '<input name="status" value="available">'
                + '<input name="restaurant_id" value="<?= (int)$selectedVenueId ?>">';
            document.body.appendChild(form);
            form.submit();
        }
    }
}

function updateItemStatus(itemId, status) {
    const fd = new FormData();
    fd.append('action', 'update_item_status');
    fd.append('item_id', itemId);
    fd.append('status', status);
    fetch('?page=vendor-restaurant-pos&restaurant_id=<?= (int)$selectedVenueId ?>', { method: 'POST', body: fd })
        .then(r => r.json())
        .then(j => {
            if (j.success) location.reload();
        })
        .catch(() => alert('Failed to update'));
}

function toggleRoomCharge(value) {
    const field = document.getElementById('roomChargeField');
    if (field) field.style.display = value === 'room' ? '' : 'none';
}

var SPLIT_REMAINING = <?= (float)($activeRemaining ?? 0) ?>;
var SPLIT_CURRENCY = <?= json_encode($baseCurrency) ?>;

function showSplitMode(mode) {
    document.getElementById('splitCoversForm').style.display = mode === 'covers' ? 'block' : 'none';
    document.getElementById('splitItemsForm').style.display = mode === 'items' ? 'block' : 'none';
    if (mode === 'covers') recalcSplitAmount();
}

function recalcSplitAmount() {
    var waysEl = document.getElementById('splitWays');
    if (!waysEl) return;
    var ways = Math.max(2, parseInt(waysEl.value) || 2);
    var per = SPLIT_REMAINING / ways;
    document.getElementById('splitPerAmount').value = SPLIT_CURRENCY + ' ' + per.toFixed(2);
    document.getElementById('splitAmountInput').value = per.toFixed(2);
}

function recalcItemSplit() {
    var total = 0;
    var ids = [];
    document.querySelectorAll('.split-item-check:checked').forEach(function(cb) {
        total += parseFloat(cb.dataset.amount) || 0;
        ids.push(cb.value);
    });
    document.getElementById('itemsAmountDisplay').value = SPLIT_CURRENCY + ' ' + total.toFixed(2);
    document.getElementById('itemsAmountInput').value = total.toFixed(2);
    document.getElementById('itemsIdsInput').value = ids.join(',');
}

if (document.getElementById('splitWays')) recalcSplitAmount();

<?php if ($view === 'kitchen'): ?>
setInterval(() => {
    if (!document.hidden) location.reload();
}, 15000);
<?php endif; ?>

document.addEventListener('keydown', e => {
    if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
    if (e.ctrlKey || e.metaKey || e.altKey) return;

    if (e.key === 'F1') { e.preventDefault(); document.getElementById('menuSearch')?.focus(); }
    if (e.key === 'F2') { e.preventDefault(); openModal('newOrderModal'); }
    if (e.key === 'F3') { e.preventDefault(); openModal('newTableModal'); }
});
</script>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>