<div class="pos-wrap">
    <div class="pos-menu-col">

        <div class="panel" style="margin-bottom:14px;">
            <div class="order-type-banner">
                <i class="fa-solid fa-motorcycle"></i>
                <div>
                    <div class="otb-title">Online Delivery Order</div>
                    <div class="otb-sub">Free Delivery zones apply automatically based on the customer's area</div>
                </div>
            </div>

            <div class="form-group" style="margin-top:14px;">
                <label>Order Received Via</label>
                <div class="channel-toggle">
                    <button type="button" class="ch-btn active" data-channel="APP" onclick="rmsSetChannel('APP', this)"><i class="fa-solid fa-mobile-screen-button"></i> App</button>
                    <button type="button" class="ch-btn" data-channel="CALL" onclick="rmsSetChannel('CALL', this)"><i class="fa-solid fa-phone"></i> Call</button>
                    <button type="button" class="ch-btn" data-channel="WHATSAPP" onclick="rmsSetChannel('WHATSAPP', this)"><i class="fa-brands fa-whatsapp"></i> WhatsApp</button>
                </div>
            </div>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:14px;">
                <div class="form-group">
                    <label>Customer Phone</label>
                    <input type="text" id="rmsCustomerPhone" class="form-control" placeholder="07XXXXXXXX">
                </div>
                <div class="form-group">
                    <label>Customer Name</label>
                    <input type="text" id="rmsCustomerName" class="form-control" placeholder="Full name">
                </div>
            </div>
            <div class="form-group">
                <label>Delivery Zone</label>
                <select id="rmsDeliveryZone" class="form-control" onchange="rmsUpdateTotals()">
                    <option value="">— Select zone —</option>
                    <?php foreach ($zones as $z): ?>
                    <option value="<?= $z['id'] ?>" data-fee="<?= $z['is_free_delivery'] ? 0 : $z['delivery_fee'] ?>" data-free="<?= $z['is_free_delivery'] ?>">
                        <?= e($z['zone_name']) ?> <?= $z['is_free_delivery'] ? '(Free Delivery)' : '(Rs.' . number_format($z['delivery_fee'], 0) . ')' ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Delivery Address</label>
                <textarea id="rmsDeliveryAddress" class="form-control" rows="2" placeholder="Full address for delivery"></textarea>
            </div>
            <div class="form-group">
                <label><i class="fa-solid fa-motorcycle" style="margin-right:4px;"></i>Assign Delivery Rider (optional)</label>
                <select id="rmsRiderId" class="form-control">
                    <option value="">— Assign later from Delivery board —</option>
                    <?php foreach ($riders as $r): ?>
                    <option value="<?= $r['id'] ?>"><?= e($r['full_name']) ?> (<?= (int) $r['active_count'] ?> active)</option>
                    <?php endforeach; ?>
                </select>
                <?php if (empty($riders)): ?>
                <div style="font-size:11.5px;color:var(--color-text-muted);margin-top:4px;">No active riders yet — add one from Users (role: Rider).</div>
                <?php endif; ?>
            </div>
        </div>

        <?php foreach ($menuByCategory as $categoryName => $menuItems): ?>
        <div class="panel">
            <h3 class="menu-cat-title"><i class="fa-solid fa-layer-group"></i> <?= e($categoryName) ?> <span class="menu-cat-count"><?= count($menuItems) ?></span></h3>
            <div class="menu-grid">
                <?php foreach ($menuItems as $mi): ?>
                <div class="menu-item-card">
                    <?php if (!empty($mi['image_path'])): ?>
                    <img src="<?= BASE_URL ?>/<?= e($mi['image_path']) ?>" alt="" class="mi-icon-img">
                    <?php else: ?>
                    <div class="mi-icon"><i class="fa-solid fa-bowl-rice"></i></div>
                    <?php endif; ?>
                    <div class="mi-body">
                        <div class="mi-name"><?= e($mi['item_name']) ?></div>
                        <?php if (!empty($mi['description'])): ?>
                        <div class="mi-desc"><?= e($mi['description']) ?></div>
                        <?php endif; ?>
                        <div class="mi-price"><?= formatMoney((float) $mi['base_price']) ?></div>
                        <?php if (!empty($mi['variants'])): ?>
                            <select class="form-control mi-variant" style="margin-bottom:8px;font-size:12px;padding:6px 8px;">
                                <option value="" data-adj="0">Regular</option>
                                <?php foreach ($mi['variants'] as $v): ?>
                                <option value="<?= $v['id'] ?>" data-adj="<?= $v['price_adjustment'] ?>"><?= e($v['variant_name']) ?> (<?= $v['price_adjustment'] >= 0 ? '+' : '' ?><?= number_format($v['price_adjustment'], 0) ?>)</option>
                                <?php endforeach; ?>
                            </select>
                        <?php endif; ?>
                        <?php if (!$mi['track_stock']): ?>
                        <span class="badge badge-gray" style="margin-bottom:8px;">Made to order</span>
                        <?php endif; ?>
                        <button type="button" class="btn btn-secondary mi-add-btn"
                            onclick="rmsAddToCart(<?= $mi['id'] ?>, '<?= e(addslashes($mi['item_name'])) ?>', <?= $mi['base_price'] ?>, this)">
                            <i class="fa-solid fa-plus"></i> Add
                        </button>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endforeach; ?>
        <?php if (empty($menuByCategory)): ?>
        <div class="panel" style="text-align:center;padding:40px;color:var(--color-text-muted);">
            <i class="fa-solid fa-bowl-rice" style="font-size:26px;margin-bottom:10px;display:block;opacity:0.5;"></i>
            No menu items yet. Add items from the Menu module first.
        </div>
        <?php endif; ?>
    </div>

    <div class="pos-cart-col">
        <form method="POST" action="<?= Router::url('orders/store') ?>" id="rmsOrderForm">
            <?= $csrf ?>
            <input type="hidden" name="order_type" value="ONLINE_DELIVERY">
            <input type="hidden" name="order_source" id="rmsOrderSourceInput" value="APP">
            <input type="hidden" name="customer_phone" id="rmsCustomerPhoneInput">
            <input type="hidden" name="customer_name" id="rmsCustomerNameInput">
            <input type="hidden" name="delivery_zone_id" id="rmsDeliveryZoneInput">
            <input type="hidden" name="delivery_address" id="rmsDeliveryAddressInput">
            <input type="hidden" name="rider_id" id="rmsRiderIdInput">
            <input type="hidden" name="cart_json" id="rmsCartJson">

            <div class="panel cart-panel">
                <h3 style="margin-bottom:14px;"><i class="fa-solid fa-cart-shopping" style="color:var(--color-teal);margin-right:6px;"></i>Order Cart</h3>
                <div id="rmsCartList" class="cart-list">
                    <div class="cart-empty" id="rmsCartEmpty">No items added yet.</div>
                </div>

                <div class="cart-totals">
                    <div class="ct-row"><span>Subtotal</span><span id="rmsSubtotalDisplay">Rs. 0.00</span></div>
                    <div class="ct-row"><span>Delivery Fee</span><span id="rmsDeliveryFeeDisplay">Rs. 0.00</span></div>
                    <div class="ct-row ct-total"><span>Total</span><span id="rmsTotalDisplay">Rs. 0.00</span></div>
                </div>

                <div class="form-group">
                    <label>Notes</label>
                    <textarea name="notes" class="form-control" rows="2" placeholder="Special instructions (optional)"></textarea>
                </div>

                <div class="panel" style="background:var(--color-bg);margin-bottom:14px;box-shadow:none;">
                    <label style="font-size:12.5px;font-weight:700;display:block;margin-bottom:8px;">Settle Payment Now (optional)</label>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                        <select name="payment_method_id" class="form-control">
                            <option value="">— No payment yet —</option>
                            <?php foreach ($paymentMethods as $m): ?>
                            <option value="<?= $m['id'] ?>"><?= e($m['method_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <input type="number" step="0.01" name="amount_collected" class="form-control" placeholder="Amount collected">
                    </div>
                </div>

                <button type="submit" class="btn btn-primary" style="width:100%;padding:13px;" id="rmsSubmitBtn" disabled>
                    <i class="fa-solid fa-check"></i> Place Order
                </button>
            </div>
        </form>
    </div>
</div>

<style>
.pos-wrap { display: grid; grid-template-columns: 1fr 360px; gap: 18px; align-items: start; }

.order-type-banner {
    display: flex; align-items: center; gap: 12px;
    background: linear-gradient(135deg, var(--stat-purple), var(--stat-purple-2));
    color: #fff; padding: 14px 16px; border-radius: 10px; font-size: 13px;
}
.order-type-banner i { font-size: 22px; }
.order-type-banner .otb-title { font-weight: 700; font-size: 14px; }
.order-type-banner .otb-sub { font-size: 11.5px; color: rgba(255,255,255,0.8); margin-top: 2px; }

.channel-toggle { display: flex; gap: 8px; flex-wrap: wrap; }
.ch-btn {
    flex: 1; min-width: 100px; padding: 9px 10px; border-radius: 8px; border: 1px solid var(--color-border);
    background: #fff; color: var(--color-text-muted); font-size: 12.5px; font-weight: 700; cursor: pointer;
    display: flex; align-items: center; justify-content: center; gap: 6px;
}
.ch-btn.active { background: var(--color-teal); color: #fff; border-color: var(--color-teal); }
.ch-btn[data-channel="WHATSAPP"].active { background: #25D366; border-color: #25D366; }

.menu-cat-title {
    font-size: 15px; margin-bottom: 14px; color: var(--color-accent);
    display: flex; align-items: center; gap: 8px;
    border-bottom: 2px solid var(--color-border); padding-bottom: 10px;
}
.menu-cat-count {
    margin-left: auto; background: rgba(193,135,46,0.14); color: #8A611F;
    font-size: 11px; font-weight: 700; padding: 2px 10px; border-radius: 100px;
}
.menu-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); gap: 12px; }
.menu-item-card {
    border: 1px solid var(--color-border); border-radius: 10px; padding: 14px;
    display: flex; gap: 10px; background: #fff;
}
.menu-item-card .mi-icon {
    width: 38px; height: 38px; border-radius: 9px; flex-shrink: 0;
    background: rgba(193,135,46,0.12); color: var(--color-accent);
    display: flex; align-items: center; justify-content: center; font-size: 16px;
}
.menu-item-card .mi-icon-img { width: 38px; height: 38px; border-radius: 9px; object-fit: cover; flex-shrink: 0; }
.menu-item-card .mi-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 4px; }
.menu-item-card .mi-name { font-size: 13.5px; font-weight: 700; }
.menu-item-card .mi-desc { font-size: 11px; color: var(--color-text-muted); line-height: 1.4; margin-bottom: 2px; }
.menu-item-card .mi-price { font-size: 12.5px; color: var(--color-accent); font-weight: 700; margin-bottom: 4px; }
.menu-item-card .mi-add-btn { font-size: 12px; padding: 7px; width: 100%; }

.pos-cart-col { position: sticky; top: 16px; }
.cart-panel { padding: 20px; }
.cart-list { max-height: 320px; overflow-y: auto; margin-bottom: 14px; }
.cart-empty { text-align: center; color: var(--color-text-muted); font-size: 12.5px; padding: 20px 0; }
.cart-line { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 0; border-bottom: 1px solid var(--color-border); font-size: 12.5px; }
.cart-line .cl-name { font-weight: 600; }
.cart-line .cl-controls { display: flex; align-items: center; gap: 6px; }
.cart-line .cl-qty-btn { width: 22px; height: 22px; border-radius: 6px; border: 1px solid var(--color-border); background: #fff; cursor: pointer; font-size: 12px; }
.cart-line .cl-remove { color: var(--color-danger); cursor: pointer; margin-left: 4px; }

.cart-totals { border-top: 2px solid var(--color-border); padding-top: 10px; margin-bottom: 14px; }
.ct-row { display: flex; justify-content: space-between; font-size: 13px; padding: 3px 0; color: var(--color-text-muted); }
.ct-row.ct-total { font-size: 16px; font-weight: 700; color: var(--color-text); border-top: 1px solid var(--color-border); margin-top: 6px; padding-top: 8px; }

@media (max-width: 980px) {
    .pos-wrap { grid-template-columns: 1fr; }
    .pos-cart-col { position: static; }
}
</style>

<script>
let rmsCart = [];

function rmsSetChannel(channel, btn) {
    document.getElementById('rmsOrderSourceInput').value = channel;
    document.querySelectorAll('.ch-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
}

function rmsAddToCart(id, name, basePrice, btnEl) {
    const card = btnEl.closest('.menu-item-card');
    const variantSelect = card.querySelector('.mi-variant');
    let variantId = null, variantName = '', priceAdj = 0;
    if (variantSelect && variantSelect.value) {
        variantId = parseInt(variantSelect.value);
        variantName = variantSelect.options[variantSelect.selectedIndex].text.replace(/\s*\([^)]*\)\s*$/, '');
        priceAdj = parseFloat(variantSelect.options[variantSelect.selectedIndex].dataset.adj || 0);
    }
    const unitPrice = basePrice + priceAdj;
    const cartKey = id + '-' + (variantId || 0);

    const existing = rmsCart.find(c => c.key === cartKey);
    if (existing) {
        existing.quantity += 1;
    } else {
        rmsCart.push({
            key: cartKey, menu_item_id: id, variant_id: variantId,
            name: name + (variantName ? ' (' + variantName + ')' : ''),
            unit_price: unitPrice, quantity: 1
        });
    }
    rmsRenderCart();
}

function rmsChangeQty(key, delta) {
    const line = rmsCart.find(c => c.key === key);
    if (!line) return;
    line.quantity += delta;
    if (line.quantity <= 0) {
        rmsCart = rmsCart.filter(c => c.key !== key);
    }
    rmsRenderCart();
}

function rmsRemoveLine(key) {
    rmsCart = rmsCart.filter(c => c.key !== key);
    rmsRenderCart();
}

function rmsRenderCart() {
    const list = document.getElementById('rmsCartList');
    const empty = document.getElementById('rmsCartEmpty');
    list.innerHTML = '';
    if (rmsCart.length === 0) {
        list.appendChild(empty);
    } else {
        rmsCart.forEach(line => {
            const row = document.createElement('div');
            row.className = 'cart-line';
            row.innerHTML = `
                <div>
                    <div class="cl-name">${line.name}</div>
                    <div style="color:var(--color-text-muted);">Rs. ${line.unit_price.toFixed(2)} each</div>
                </div>
                <div class="cl-controls">
                    <button type="button" class="cl-qty-btn" onclick="rmsChangeQty('${line.key}', -1)">−</button>
                    <span>${line.quantity}</span>
                    <button type="button" class="cl-qty-btn" onclick="rmsChangeQty('${line.key}', 1)">+</button>
                    <span class="cl-remove" onclick="rmsRemoveLine('${line.key}')"><i class="fa-solid fa-trash"></i></span>
                </div>`;
            list.appendChild(row);
        });
    }
    rmsUpdateTotals();
}

function rmsUpdateTotals() {
    const subtotal = rmsCart.reduce((sum, l) => sum + (l.unit_price * l.quantity), 0);
    let deliveryFee = 0;

    const zoneSelect = document.getElementById('rmsDeliveryZone');
    const opt = zoneSelect.options[zoneSelect.selectedIndex];
    if (opt && opt.value) {
        deliveryFee = opt.dataset.free === '1' ? 0 : parseFloat(opt.dataset.fee || 0);
    }
    document.getElementById('rmsDeliveryFeeDisplay').textContent = 'Rs. ' + deliveryFee.toFixed(2);

    const total = subtotal + deliveryFee;
    document.getElementById('rmsSubtotalDisplay').textContent = 'Rs. ' + subtotal.toFixed(2);
    document.getElementById('rmsTotalDisplay').textContent = 'Rs. ' + total.toFixed(2);
    document.getElementById('rmsSubmitBtn').disabled = rmsCart.length === 0;
}

document.getElementById('rmsOrderForm').addEventListener('submit', function (e) {
    document.getElementById('rmsCartJson').value = JSON.stringify(rmsCart.map(l => ({
        menu_item_id: l.menu_item_id, variant_id: l.variant_id, quantity: l.quantity
    })));
    document.getElementById('rmsCustomerPhoneInput').value = document.getElementById('rmsCustomerPhone').value;
    document.getElementById('rmsCustomerNameInput').value = document.getElementById('rmsCustomerName').value;
    document.getElementById('rmsDeliveryZoneInput').value = document.getElementById('rmsDeliveryZone').value;
    document.getElementById('rmsDeliveryAddressInput').value = document.getElementById('rmsDeliveryAddress').value;
    document.getElementById('rmsRiderIdInput').value = document.getElementById('rmsRiderId').value;

    if (rmsCart.length === 0) {
        e.preventDefault();
        alert('Please add at least one item to the cart.');
    }
});
</script>