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

<?= view('bookings/_wizard_steps', ['step' => 5]) ?>

<?php $existingQty = []; foreach ($wizard['services'] ?? [] as $item) { $existingQty[$item['service_id']] = $item['qty']; } ?>

<div class="row">
    <div class="col-lg-8 mb-3">
        <div class="card">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-bag-plus" style="color: var(--brand);"></i> Add Services / Extras
            </div>
            <div class="card-body">
                <?php if (empty($services)): ?>
                    <p class="text-muted text-center py-4 mb-0">No services configured for this hotel yet. Skip this step, or a manager can add some under Services &amp; Extras.</p>
                    <form action="<?= site_url('bookings/wizard/services') ?>" method="post">
                        <?= csrf_field() ?>
                        <div class="d-flex gap-2">
                            <a href="<?= site_url('bookings/wizard/details') ?>" class="btn btn-outline-secondary">Back</a>
                            <button type="submit" class="btn btn-primary">Continue to Payment</button>
                        </div>
                    </form>
                <?php else: ?>
                <form action="<?= site_url('bookings/wizard/services') ?>" method="post" id="servicesForm">
                    <?= csrf_field() ?>
                    <div class="table-scroll mb-3">
                        <table class="table align-middle mb-0" id="servicesTable">
                            <thead class="table-light">
                                <tr><th>Service</th><th>Unit</th><th class="text-end">Price</th><th class="text-center" style="width:100px;">Qty</th><th class="text-end">Total</th></tr>
                            </thead>
                            <tbody>
                                <?php foreach ($services as $svc):
                                    $catMeta = $lookups->serviceCategories[$svc->category] ?? ['icon' => 'bi-circle'];
                                ?>
                                    <tr class="service-row" data-price="<?= esc($svc->price) ?>">
                                        <td><i class="bi <?= $catMeta['icon'] ?> me-2 text-muted"></i><?= esc($svc->name) ?></td>
                                        <td class="text-muted small"><?= esc($lookups->serviceUnits[$svc->unit_label] ?? $svc->unit_label) ?></td>
                                        <td class="text-end"><?= format_money($svc->price) ?></td>
                                        <td class="text-center">
                                            <input type="number" min="0" class="form-control form-control-sm qty-input text-center" name="qty[<?= $svc->id ?>]" value="<?= (int) ($existingQty[$svc->id] ?? 0) ?>">
                                        </td>
                                        <td class="text-end fw-semibold row-total">GHS 0.00</td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <div class="d-flex gap-2">
                        <a href="<?= site_url('bookings/wizard/details') ?>" class="btn btn-outline-secondary">Back</a>
                        <button type="submit" class="btn btn-primary">Continue to Payment</button>
                    </div>
                </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php /* right-column summary continues below, unaffected by which branch above rendered */ ?>

    <div class="col-lg-4">
        <div class="card shadow-sm">
            <div class="card-header">Services Summary</div>
            <div class="card-body" id="servicesSummary">
                <p class="text-muted small mb-0" id="summaryEmpty">No services added yet.</p>
                <div id="summaryLines"></div>
                <hr class="d-none" id="summaryDivider">
                <div class="d-flex justify-content-between fw-bold d-none" id="summaryTotalRow">
                    <span>Subtotal</span>
                    <span id="summaryTotal">GHS 0.00</span>
                </div>
            </div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
function recalc() {
    let subtotal = 0;
    const lines = [];

    document.querySelectorAll('.service-row').forEach(function (row) {
        const price = parseFloat(row.dataset.price);
        const qty = parseInt(row.querySelector('.qty-input').value, 10) || 0;
        const total = price * qty;
        row.querySelector('.row-total').textContent = 'GHS ' + total.toFixed(2);

        if (qty > 0) {
            const name = row.querySelector('td').textContent.trim();
            lines.push({ name: name, qty: qty, total: total });
            subtotal += total;
        }
    });

    const summaryLines = document.getElementById('summaryLines');
    summaryLines.innerHTML = '';
    lines.forEach(function (line) {
        const div = document.createElement('div');
        div.className = 'd-flex justify-content-between small mb-1';
        div.innerHTML = '<span>' + line.name + ' (' + line.qty + ')</span><span>GHS ' + line.total.toFixed(2) + '</span>';
        summaryLines.appendChild(div);
    });

    document.getElementById('summaryEmpty').classList.toggle('d-none', lines.length > 0);
    document.getElementById('summaryDivider').classList.toggle('d-none', lines.length === 0);
    document.getElementById('summaryTotalRow').classList.toggle('d-none', lines.length === 0);
    document.getElementById('summaryTotal').textContent = 'GHS ' + subtotal.toFixed(2);
}

document.querySelectorAll('.qty-input').forEach(function (input) {
    input.addEventListener('input', recalc);
});
recalc();
</script>
<?= $this->endSection() ?>
