<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="d-flex justify-content-between align-items-start mb-3">
    <h1 class="h3 mb-0">Order #<?= $order->id ?></h1>
    <span class="badge bg-<?= esc($lookups->posOrderStatuses[$order->status]['badge'] ?? 'secondary') ?> fs-6">
        <?= esc($lookups->posOrderStatuses[$order->status]['label'] ?? $order->status) ?>
    </span>
</div>
<p class="text-muted mb-3">
    <?= esc($lookups->posOrderTypes[$order->order_type]['label'] ?? $order->order_type) ?>
    <?php if ($order->table_number): ?> · Table <?= esc($order->table_number) ?><?php endif; ?>
</p>

<div class="row">
    <div class="col-md-7 mb-3">
        <div class="card shadow-sm mb-3">
            <div class="card-body">
                <h2 class="h6">Items</h2>
                <table class="table table-sm mb-0">
                    <thead class="table-light"><tr><th>Item</th><th>Qty</th><th class="text-end">Line Total</th><th>Kitchen</th></tr></thead>
                    <tbody>
                        <?php if (empty($items)): ?>
                            <tr><td colspan="4" class="text-center text-muted py-3">No items yet.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($items as $item): ?>
                            <tr>
                                <td><?= esc($item->item_name) ?></td>
                                <td><?= (int) $item->quantity ?></td>
                                <td class="text-end"><?= format_money(money_multiply($item->unit_price, $item->quantity)) ?></td>
                                <td><span class="badge bg-<?= $item->kitchen_status === 'ready' ? 'success' : 'secondary' ?>"><?= esc(ucfirst($item->kitchen_status)) ?></span></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr class="table-light"><th colspan="2" class="text-end">Total</th><th class="text-end"><?= format_money($total) ?></th><th></th></tr>
                    </tfoot>
                </table>

                <?php if ($order->status === 'open'): ?>
                <form action="<?= site_url('pos/orders/' . $order->id . '/items') ?>" method="post" class="row g-2 mt-3 align-items-end border-top pt-3">
                    <?= csrf_field() ?>
                    <div class="col-6">
                        <label class="form-label small">Menu Item</label>
                        <select class="form-select form-select-sm" name="menu_item_id" required>
                            <?php foreach ($menuGroups as $category => $menuItems): ?>
                                <optgroup label="<?= esc($category) ?>">
                                    <?php foreach ($menuItems as $mi): ?>
                                        <option value="<?= $mi->id ?>"><?= esc($mi->name) ?> — <?= format_money($mi->price) ?></option>
                                    <?php endforeach; ?>
                                </optgroup>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-3">
                        <label class="form-label small">Qty</label>
                        <input type="number" class="form-control form-control-sm" name="quantity" value="1" min="1" required>
                    </div>
                    <div class="col-3">
                        <button type="submit" class="btn btn-sm btn-outline-primary w-100">Add</button>
                    </div>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <div class="d-flex gap-2">
            <?php if ($order->status === 'open'): ?>
                <form action="<?= site_url('pos/orders/' . $order->id . '/send') ?>" method="post">
                    <?= csrf_field() ?>
                    <button type="submit" class="btn btn-warning" <?= empty($items) ? 'disabled' : '' ?>>Send to Kitchen</button>
                </form>
            <?php elseif ($order->status === 'sent_to_kitchen'): ?>
                <form action="<?= site_url('pos/orders/' . $order->id . '/served') ?>" method="post">
                    <?= csrf_field() ?>
                    <button type="submit" class="btn btn-primary">Mark Served</button>
                </form>
            <?php endif; ?>
        </div>
    </div>

    <?php if (in_array($order->status, ['open', 'sent_to_kitchen', 'served'], true) && ! empty($items)): ?>
    <div class="col-md-5 mb-3">
        <div class="card shadow-sm">
            <div class="card-body">
                <h2 class="h6">Settle</h2>

                <ul class="nav nav-tabs nav-fill mb-3" role="tablist">
                    <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#pay-direct">Pay Directly</button></li>
                    <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#charge-room">Charge to Room</button></li>
                </ul>

                <div class="tab-content">
                    <div class="tab-pane fade show active" id="pay-direct">
                        <form action="<?= site_url('pos/orders/' . $order->id . '/settle-direct') ?>" method="post">
                            <?= csrf_field() ?>
                            <input type="hidden" name="guest_id" id="direct_guest_id" value="0">
                            <div class="mb-2">
                                <label class="form-label small">Phone</label>
                                <div class="input-group input-group-sm">
                                    <input type="text" class="form-control" id="direct_phone" placeholder="024XXXXXXX">
                                    <button type="button" class="btn btn-outline-secondary" id="direct-lookup-btn">Look up</button>
                                </div>
                                <div id="direct-lookup-result" class="form-text"></div>
                            </div>
                            <div class="mb-2">
                                <label class="form-label small">Name</label>
                                <input type="text" class="form-control form-control-sm" name="full_name" id="direct_full_name">
                            </div>
                            <input type="hidden" name="phone" id="direct_phone_hidden">
                            <div class="mb-2">
                                <label class="form-label small">Bill to Corporate Account <span class="text-muted">(optional)</span></label>
                                <input type="hidden" name="corporate_account_id" id="direct_corporate_id" value="0">
                                <input type="text" class="form-control form-control-sm" id="direct_corporate_search" placeholder="Search company..." autocomplete="off">
                                <div id="direct_corporate_results" class="list-group mt-1"></div>
                            </div>
                            <div class="mb-2">
                                <label class="form-label small">Method</label>
                                <select class="form-select form-select-sm" name="method" required>
                                    <?php foreach ($lookups->manualPaymentMethods() as $key => $meta): ?>
                                        <option value="<?= esc($key) ?>"><?= esc($meta['label']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-sm btn-success w-100">Settle — <?= format_money($total) ?></button>
                        </form>
                    </div>
                    <div class="tab-pane fade" id="charge-room">
                        <form action="<?= site_url('pos/orders/' . $order->id . '/settle-room') ?>" method="post">
                            <?= csrf_field() ?>
                            <input type="hidden" name="guest_id" id="room_guest_id" value="0">
                            <div class="mb-2">
                                <label class="form-label small">In-house guest phone</label>
                                <div class="input-group input-group-sm">
                                    <input type="text" class="form-control" id="room_phone" placeholder="024XXXXXXX">
                                    <button type="button" class="btn btn-outline-secondary" id="room-lookup-btn">Look up</button>
                                </div>
                                <div id="room-lookup-result" class="form-text"></div>
                            </div>
                            <button type="submit" class="btn btn-sm btn-success w-100">Charge to Room — <?= format_money($total) ?></button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
document.getElementById('direct-lookup-btn')?.addEventListener('click', function () {
    const phone = document.getElementById('direct_phone').value.trim();
    const resultEl = document.getElementById('direct-lookup-result');
    if (!phone) return;
    fetch('<?= site_url('pos/orders/lookup-guest') ?>?phone=' + encodeURIComponent(phone))
        .then((r) => r.json())
        .then((data) => {
            document.getElementById('direct_phone_hidden').value = phone;
            if (data.found) {
                document.getElementById('direct_guest_id').value = data.guest.id;
                document.getElementById('direct_full_name').value = data.guest.full_name;
                const directVip = data.guest.segmentLabel ? ' <span class="badge bg-' + data.guest.segmentBadge + '">' + data.guest.segmentLabel + '</span>' : '';
                const directDining = data.guest.diningLabel ? ' <span class="badge bg-' + data.guest.diningBadge + '">' + data.guest.diningLabel + ' Dining</span>' : '';
                resultEl.innerHTML = '<span class="text-success">Guest: ' + data.guest.full_name + '</span>' + directVip + directDining;
            } else {
                document.getElementById('direct_guest_id').value = 0;
                resultEl.innerHTML = '<span class="text-muted">New guest — enter name.</span>';
            }
        });
});

const directCorpSearch = document.getElementById('direct_corporate_search');
let directCorpDebounce;
directCorpSearch?.addEventListener('input', function () {
    clearTimeout(directCorpDebounce);
    const q = this.value.trim();
    const resultsEl = document.getElementById('direct_corporate_results');
    document.getElementById('direct_corporate_id').value = 0;
    if (q.length < 2) { resultsEl.innerHTML = ''; return; }

    directCorpDebounce = setTimeout(function () {
        fetch('<?= site_url('pos/orders/lookup-corporate') ?>?q=' + encodeURIComponent(q))
            .then((r) => r.json())
            .then((data) => {
                resultsEl.innerHTML = '';
                data.results.forEach(function (a) {
                    const item = document.createElement('button');
                    item.type = 'button';
                    item.className = 'list-group-item list-group-item-action';
                    item.textContent = a.company_name;
                    item.addEventListener('click', function () {
                        directCorpSearch.value = a.company_name;
                        document.getElementById('direct_corporate_id').value = a.id;
                        resultsEl.innerHTML = '';
                    });
                    resultsEl.appendChild(item);
                });
            });
    }, 300);
});

document.getElementById('room-lookup-btn')?.addEventListener('click', function () {
    const phone = document.getElementById('room_phone').value.trim();
    const resultEl = document.getElementById('room-lookup-result');
    if (!phone) return;
    fetch('<?= site_url('pos/orders/lookup-guest') ?>?phone=' + encodeURIComponent(phone))
        .then((r) => r.json())
        .then((data) => {
            if (data.found) {
                document.getElementById('room_guest_id').value = data.guest.id;
                const roomVip = data.guest.segmentLabel ? ' <span class="badge bg-' + data.guest.segmentBadge + '">' + data.guest.segmentLabel + '</span>' : '';
                const roomDining = data.guest.diningLabel ? ' <span class="badge bg-' + data.guest.diningBadge + '">' + data.guest.diningLabel + ' Dining</span>' : '';
                resultEl.innerHTML = '<span class="text-success">Guest: ' + data.guest.full_name + '</span>' + roomVip + roomDining;
            } else {
                document.getElementById('room_guest_id').value = 0;
                resultEl.innerHTML = '<span class="text-danger">No guest with that phone — they must be an existing, checked-in guest.</span>';
            }
        });
});
</script>
<?= $this->endSection() ?>
