<?php
$statusColors = [
    'pending'=>'warning','confirmed'=>'info','cooking'=>'danger',
    'ready'=>'success','picked_up'=>'primary','on_the_way'=>'warning','delivered'=>'success',
];
$statusLabels = [
    'pending'=>'Pending','confirmed'=>'Confirmed','cooking'=>'Cooking',
    'ready'=>'Ready','picked_up'=>'Picked Up','on_the_way'=>'On the Way','delivered'=>'Delivered',
];
$collectedTotal = array_sum(array_column($collected, 'total_amount'));
?>
<!-- page header -->
<div class="page-header" style="flex-wrap:wrap;gap:8px;">
    <div>
        <h1><i class="bi bi-cash-coin me-2"></i>Cashier</h1>
        <p class="d-none d-md-block">Collect payments and view today's settled bills.</p>
    </div>
    <div class="d-flex align-items-center gap-2 flex-wrap">
        <span class="badge bg-danger" id="unpaidCount"><?= count($orders) ?> unpaid</span>
        <span class="badge bg-success"><?= count($collected) ?> collected today</span>
        <a href="<?= url('reports/cash-summary') ?>" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-bar-chart me-1"></i><span class="d-none d-sm-inline">Cash Summary</span>
        </a>
    </div>
</div>

<?= flash_alert() ?>

<!-- ═══════════════ UNPAID SECTION ══════════════════════════════════════════ -->
<div class="d-flex align-items-center gap-2 mb-2">
    <h6 class="mb-0 fw-700 text-danger"><i class="bi bi-hourglass-split me-1"></i>Unpaid Bills</h6>
    <span class="badge bg-danger" id="unpaidBadge"><?= count($orders) ?></span>
</div>

<?php if (empty($orders)): ?>
<div class="card text-center py-4 mb-4">
    <div style="font-size:2.5rem;">✅</div>
    <p class="mt-2 mb-0 text-secondary">No unpaid orders.</p>
</div>
<?php else: ?>

<!-- Desktop table (hidden on mobile) -->
<div class="card p-0 overflow-hidden mb-2 d-none d-md-block">
    <table class="table table-hover mb-0" id="cashierTable">
        <thead class="table-light">
            <tr>
                <th>Order</th>
                <th>Customer</th>
                <th>Rider</th>
                <th>Type</th>
                <th>Status</th>
                <th>Method</th>
                <th class="text-end">Amount</th>
                <th style="width:100px;"></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($orders as $o): ?>
        <?php
            $isDelivery = ($o['order_type'] ?? 'delivery') === 'delivery';
            $method     = strtolower($o['payment_method'] ?? 'cash');
        ?>
        <tr id="row-<?= $o['id'] ?>">
            <td>
                <a href="<?= url('orders/'.$o['id']) ?>" class="fw-700 text-accent">#<?= e($o['order_number']) ?></a>
                <div class="text-secondary" style="font-size:.7rem;"><?= date('h:i A', strtotime($o['placed_at'])) ?></div>
            </td>
            <td>
                <div class="fw-600"><?= e($o['customer_name']) ?></div>
                <?php if ($o['customer_phone']): ?>
                <div class="text-secondary" style="font-size:.72rem;"><?= e($o['customer_phone']) ?></div>
                <?php endif; ?>
            </td>
            <td>
                <?= $o['rider_name']
                    ? '<span class="badge bg-light text-dark border"><i class="bi bi-bicycle me-1"></i>'.e($o['rider_name']).'</span>'
                    : '<span class="text-secondary" style="font-size:.78rem;">—</span>' ?>
            </td>
            <td>
                <span class="badge" style="<?= $isDelivery ? 'background:#e3f2fd;color:#1565c0' : 'background:#e8f5e9;color:#2e7d32' ?>;">
                    <i class="bi bi-<?= $isDelivery ? 'bicycle' : 'shop' ?> me-1"></i><?= $isDelivery ? 'Delivery' : 'Pickup' ?>
                </span>
            </td>
            <td><span class="badge bg-<?= $statusColors[$o['status']] ?? 'secondary' ?>"><?= $statusLabels[$o['status']] ?? ucfirst($o['status']) ?></span></td>
            <td>
                <span class="badge <?= $method === 'cash' ? 'bg-warning text-dark' : 'bg-info text-white' ?>">
                    <?= ucfirst($method) ?>
                </span>
            </td>
            <td class="text-end fw-700 text-accent"><?= money((float)$o['total_amount']) ?></td>
            <td class="text-end">
                <button class="btn btn-success btn-sm"
                        onclick="openPayModal(<?= $o['id'] ?>,'<?= e(addslashes($o['order_number'])) ?>',<?= (float)$o['total_amount'] ?>)">
                    <i class="bi bi-cash me-1"></i>Collect
                </button>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Mobile cards (hidden on desktop) -->
<div class="d-md-none mb-2" id="mobileUnpaid">
    <?php foreach ($orders as $o): ?>
    <?php
        $isDelivery = ($o['order_type'] ?? 'delivery') === 'delivery';
        $method     = strtolower($o['payment_method'] ?? 'cash');
    ?>
    <div class="card mb-2 p-3" id="row-<?= $o['id'] ?>">
        <div class="d-flex justify-content-between align-items-start">
            <div>
                <a href="<?= url('orders/'.$o['id']) ?>" class="fw-700 text-accent">#<?= e($o['order_number']) ?></a>
                <span class="ms-2 badge bg-<?= $statusColors[$o['status']] ?? 'secondary' ?>" style="font-size:.65rem;">
                    <?= $statusLabels[$o['status']] ?? ucfirst($o['status']) ?>
                </span>
            </div>
            <span class="fw-700 text-accent fs-6"><?= money((float)$o['total_amount']) ?></span>
        </div>
        <div class="mt-1" style="font-size:.82rem;">
            <span class="fw-600"><?= e($o['customer_name']) ?></span>
            <?php if ($o['rider_name']): ?>
            <span class="text-secondary ms-2"><i class="bi bi-bicycle"></i> <?= e($o['rider_name']) ?></span>
            <?php endif; ?>
        </div>
        <div class="d-flex align-items-center justify-content-between mt-2">
            <div class="d-flex gap-1 flex-wrap">
                <span class="badge" style="font-size:.62rem;<?= $isDelivery ? 'background:#e3f2fd;color:#1565c0' : 'background:#e8f5e9;color:#2e7d32' ?>;">
                    <?= $isDelivery ? 'Delivery' : 'Pickup' ?>
                </span>
                <span class="badge <?= $method === 'cash' ? 'bg-warning text-dark' : 'bg-info' ?>" style="font-size:.62rem;">
                    <?= ucfirst($method) ?>
                </span>
                <span class="text-secondary" style="font-size:.68rem;"><?= date('h:i A', strtotime($o['placed_at'])) ?></span>
            </div>
            <button class="btn btn-success btn-sm"
                    onclick="openPayModal(<?= $o['id'] ?>,'<?= e(addslashes($o['order_number'])) ?>',<?= (float)$o['total_amount'] ?>)">
                <i class="bi bi-cash me-1"></i>Collect
            </button>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<div class="card p-3 d-flex flex-row align-items-center justify-content-between mb-4">
    <span class="text-secondary fw-600">Total unpaid</span>
    <span class="fw-700 fs-5 text-danger" id="totalUnpaid">
        <?= money(array_sum(array_column($orders, 'total_amount'))) ?>
    </span>
</div>

<?php endif; ?>

<!-- ═══════════════ COLLECTED SECTION ═══════════════════════════════════════ -->
<div class="d-flex align-items-center gap-2 mb-2 mt-2">
    <h6 class="mb-0 fw-700 text-success"><i class="bi bi-check-circle me-1"></i>Collected Today</h6>
    <span class="badge bg-success"><?= count($collected) ?></span>
    <?php if ($collectedTotal > 0): ?>
    <span class="ms-auto fw-700 text-success"><?= money($collectedTotal) ?></span>
    <?php endif; ?>
</div>

<?php if (empty($collected)): ?>
<div class="card text-center py-3">
    <p class="text-secondary mb-0" style="font-size:.85rem;">No payments collected yet today.</p>
</div>
<?php else: ?>

<!-- Desktop -->
<div class="card p-0 overflow-hidden d-none d-md-block">
    <table class="table table-hover mb-0">
        <thead class="table-light">
            <tr>
                <th>Order</th>
                <th>Customer</th>
                <th>Status</th>
                <th>Payment Splits</th>
                <th class="text-end">Amount</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($collected as $o): ?>
        <?php $os = $splits[$o['id']] ?? []; ?>
        <tr>
            <td>
                <a href="<?= url('orders/'.$o['id']) ?>" class="fw-700 text-accent">#<?= e($o['order_number']) ?></a>
                <div class="text-secondary" style="font-size:.7rem;"><?= date('h:i A', strtotime($o['placed_at'])) ?></div>
            </td>
            <td class="fw-600"><?= e($o['customer_name']) ?></td>
            <td><span class="badge bg-<?= $statusColors[$o['status']] ?? 'secondary' ?>"><?= $statusLabels[$o['status']] ?? ucfirst($o['status']) ?></span></td>
            <td>
                <?php if ($os): ?>
                    <?php foreach ($os as $sp): ?>
                    <span class="badge bg-light text-dark border me-1" style="font-size:.72rem;">
                        <?= e($sp['mode']) ?> <strong><?= money((float)$sp['amount']) ?></strong>
                    </span>
                    <?php endforeach; ?>
                <?php else: ?>
                    <span class="text-secondary" style="font-size:.78rem;"><?= e($o['collected_via'] ?? '—') ?></span>
                <?php endif; ?>
            </td>
            <td class="text-end fw-700 text-success"><?= money((float)$o['total_amount']) ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Mobile -->
<div class="d-md-none">
    <?php foreach ($collected as $o): ?>
    <?php $os = $splits[$o['id']] ?? []; ?>
    <div class="card mb-2 p-3">
        <div class="d-flex justify-content-between align-items-start">
            <div>
                <a href="<?= url('orders/'.$o['id']) ?>" class="fw-700 text-accent">#<?= e($o['order_number']) ?></a>
                <span class="ms-2 badge bg-<?= $statusColors[$o['status']] ?? 'secondary' ?>" style="font-size:.62rem;">
                    <?= $statusLabels[$o['status']] ?? ucfirst($o['status']) ?>
                </span>
            </div>
            <span class="fw-700 text-success"><?= money((float)$o['total_amount']) ?></span>
        </div>
        <div class="fw-600 mt-1" style="font-size:.82rem;"><?= e($o['customer_name']) ?></div>
        <div class="mt-1 d-flex flex-wrap gap-1">
            <?php if ($os): ?>
                <?php foreach ($os as $sp): ?>
                <span class="badge bg-light text-dark border" style="font-size:.68rem;">
                    <?= e($sp['mode']) ?> <strong><?= money((float)$sp['amount']) ?></strong>
                </span>
                <?php endforeach; ?>
            <?php else: ?>
                <span class="text-secondary" style="font-size:.75rem;"><?= e($o['collected_via'] ?? '—') ?></span>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<?php endif; ?>

<!-- ── Payment Modal ──────────────────────────────────────────────────────── -->
<div class="modal fade" id="payModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" style="max-width:420px;">
        <div class="modal-content">
            <div class="modal-header border-0 pb-0">
                <div>
                    <h6 class="modal-title fw-700">Collect Payment</h6>
                    <p class="text-secondary mb-0" style="font-size:.78rem;">
                        Order <strong id="modalOrderNum"></strong>
                    </p>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body pb-1">

                <!-- Bill + remaining -->
                <div class="d-flex justify-content-between align-items-center mb-3 p-3 rounded"
                     style="background:#f8fafc;border:1px solid #e2e8f0;">
                    <div>
                        <div class="text-secondary" style="font-size:.72rem;">Bill Amount</div>
                        <div class="fw-700 fs-5 text-accent" id="modalAmount"></div>
                    </div>
                    <div class="text-end">
                        <div class="text-secondary" style="font-size:.72rem;">Remaining</div>
                        <div class="fw-700 fs-5" id="modalRemaining"></div>
                    </div>
                </div>

                <!-- Split rows -->
                <div id="splitRows"></div>

                <!-- Add split -->
                <button type="button" class="btn btn-outline-secondary btn-sm w-100 mt-1"
                        id="addSplitBtn" onclick="addSplit()">
                    <i class="bi bi-plus-lg me-1"></i>Add Another Payment
                </button>

                <p class="text-danger mt-2 mb-0" id="splitError" style="font-size:.78rem;display:none;"></p>
            </div>
            <div class="modal-footer border-0 pt-2">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success px-4" id="confirmPayBtn" onclick="confirmPay()">
                    <i class="bi bi-check-lg me-1"></i>Mark Paid
                </button>
            </div>
        </div>
    </div>
</div>

<style>
.split-row { display:flex; gap:8px; align-items:center; margin-bottom:8px; }
.split-row select { flex:1; min-width:0; font-size:.82rem; }
.split-row input  { width:100px; min-width:0; font-size:.82rem; }
.split-row .rm-btn { flex-shrink:0; padding:4px 8px; }
@media(max-width:420px) {
    .split-row input { width:80px; }
}
</style>

<script>
const CSRF        = '<?= csrf_token() ?>';
const CASHIER_URL = '<?= url('cashier/') ?>';
const MODES       = <?= json_encode(array_column($paymentModes, 'name')) ?>;
let _payOrderId   = null;
let _orderTotal   = 0;
let _payModal     = null;

function openPayModal(orderId, orderNum, amount) {
    if (!_payModal) _payModal = new bootstrap.Modal(document.getElementById('payModal'));
    _payOrderId = orderId;
    _orderTotal = parseFloat(amount);
    document.getElementById('modalOrderNum').textContent = '#' + orderNum;
    document.getElementById('modalAmount').textContent   = 'Rs. ' + _orderTotal.toFixed(2);
    document.getElementById('splitError').style.display  = 'none';
    document.getElementById('splitRows').innerHTML       = '';
    addSplit(_orderTotal);   // first row = full amount
    updateRemaining();
    _payModal.show();
}

function modeOptions(selected) {
    if (!MODES.length) return '<option value="">No modes — add in Settings</option>';
    return MODES.map(m =>
        `<option value="${m}" ${m === selected ? 'selected' : ''}>${m}</option>`
    ).join('');
}

function calcRemaining() {
    let paid = 0;
    document.querySelectorAll('.split-amount').forEach(i => paid += parseFloat(i.value) || 0);
    return Math.round((_orderTotal - paid) * 100) / 100;
}

function addSplit(amount) {
    // If no amount given, auto-fill the current remaining balance
    const rem = amount !== undefined ? amount : calcRemaining();
    const defaultMode = MODES[0] ?? '';
    const row = document.createElement('div');
    row.className = 'split-row';
    row.innerHTML = `
        <select class="form-select form-select-sm split-mode" onchange="updateRemaining()">
            ${modeOptions(defaultMode)}
        </select>
        <input type="number" class="form-control form-control-sm split-amount"
               value="${rem > 0 ? rem.toFixed(2) : ''}"
               min="0.01" step="0.01" placeholder="Amount"
               oninput="updateRemaining()">
        <button type="button" class="btn btn-outline-danger btn-sm rm-btn"
                onclick="removeSplit(this)" title="Remove">
            <i class="bi bi-x-lg"></i>
        </button>`;
    document.getElementById('splitRows').appendChild(row);
    // Focus the amount field of the new row
    row.querySelector('.split-amount').select();
    updateRemaining();
}

function removeSplit(btn) {
    if (document.querySelectorAll('.split-row').length <= 1) return;
    btn.closest('.split-row').remove();
    updateRemaining();
}

function updateRemaining() {
    const rem = calcRemaining();
    const el  = document.getElementById('modalRemaining');
    if (Math.abs(rem) < 0.005) {
        el.textContent = '✓ Settled';
        el.style.color = '#16a34a';
    } else if (rem < 0) {
        el.textContent = 'Rs. ' + Math.abs(rem).toFixed(2) + ' over';
        el.style.color = '#f97316';
    } else {
        el.textContent = 'Rs. ' + rem.toFixed(2) + ' left';
        el.style.color = '#ef4444';
    }
    document.getElementById('addSplitBtn').style.display = rem > 0.005 ? '' : 'none';
}

async function confirmPay() {
    document.getElementById('splitError').style.display = 'none';
    const modes   = [...document.querySelectorAll('.split-mode')].map(s => s.value);
    const amounts = [...document.querySelectorAll('.split-amount')].map(i => parseFloat(i.value) || 0);

    if (modes.some(m => !m))  { showSplitError('Please select a payment mode for each row.'); return; }
    if (amounts.some(a => a <= 0)) { showSplitError('All amounts must be greater than zero.'); return; }
    const total = amounts.reduce((s, a) => s + a, 0);
    if (Math.abs(total - _orderTotal) > 0.5) {
        showSplitError(`Total (Rs. ${total.toFixed(2)}) must equal the bill (Rs. ${_orderTotal.toFixed(2)}).`);
        return;
    }

    const btn = document.getElementById('confirmPayBtn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';

    const fd = new FormData();
    fd.append('_csrf', CSRF);
    modes.forEach(m   => fd.append('modes[]',   m));
    amounts.forEach(a => fd.append('amounts[]', a));

    try {
        const res  = await fetch(CASHIER_URL + _payOrderId + '/pay', {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body: fd,
        });
        const data = await res.json();
        if (data.ok) {
            _payModal.hide();
            // Remove from unpaid (both desktop and mobile rows share same id)
            ['row-' + _payOrderId].forEach(id => {
                const el = document.getElementById(id);
                if (el) {
                    el.style.transition = 'opacity .4s';
                    el.style.opacity = '0';
                    setTimeout(() => { el.remove(); updateTotals(); }, 400);
                }
            });
            // Reload page after short delay so collected section updates
            setTimeout(() => location.reload(), 900);
        } else {
            showSplitError(data.message ?? 'Failed to update payment.');
        }
    } catch(e) {
        showSplitError('Network error.');
    }
    btn.disabled = false;
    btn.innerHTML = '<i class="bi bi-check-lg me-1"></i>Mark Paid';
}

function showSplitError(msg) {
    const el = document.getElementById('splitError');
    el.textContent = msg;
    el.style.display = '';
}

function updateTotals() {
    const desktopRows = document.querySelectorAll('#cashierTable tbody tr');
    const mobileCards = document.querySelectorAll('#mobileUnpaid .card');
    const count = Math.max(desktopRows.length, mobileCards.length);
    document.getElementById('unpaidCount').textContent = count + ' unpaid';
    document.getElementById('unpaidBadge').textContent = count;

    let total = 0;
    desktopRows.forEach(r => {
        const el = r.querySelector('td:nth-child(7)');
        if (el) total += parseFloat(el.textContent.replace(/[^\d.]/g, '')) || 0;
    });
    const totEl = document.getElementById('totalUnpaid');
    if (totEl) totEl.textContent = 'Rs. ' + total.toFixed(2);
}
</script>
