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

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

<div class="row">
    <div class="col-lg-7 mb-3">
        <div class="card">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-calendar-check" style="color: var(--brand);"></i> Reservation Details
            </div>
            <div class="card-body">
                <form action="<?= site_url('bookings/wizard/details') ?>" method="post">
                    <?= csrf_field() ?>

                    <h6 class="text-muted text-uppercase small fw-bold mb-2">Stay Information</h6>
                    <div class="row g-3 mb-3">
                        <div class="col-md-6">
                            <label class="form-label small">Check-in</label>
                            <div class="form-control bg-light"><?= esc(date('d M Y', strtotime($wizard['check_in']))) ?>, 2:00 PM</div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small">Check-out</label>
                            <div class="form-control bg-light"><?= esc(date('d M Y', strtotime($wizard['check_out']))) ?>, 12:00 PM</div>
                        </div>
                    </div>
                    <p class="text-muted small">Standard check-in/check-out times for this hotel — <?= $nights ?> night<?= $nights > 1 ? 's' : '' ?> total.</p>

                    <h6 class="text-muted text-uppercase small fw-bold mb-2 mt-4">Guests</h6>
                    <div class="row g-3 mb-3">
                        <div class="col-md-6">
                            <label class="form-label small fw-semibold">Adults</label>
                            <select class="form-select" name="adults">
                                <?php for ($i = 1; $i <= max(6, $room->capacity ?? 4); $i++): ?>
                                    <option value="<?= $i ?>" <?= (int) ($wizard['adults'] ?? 1) === $i ? 'selected' : '' ?>><?= $i ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small fw-semibold">Children</label>
                            <select class="form-select" name="children">
                                <?php for ($i = 0; $i <= 4; $i++): ?>
                                    <option value="<?= $i ?>" <?= (int) ($wizard['children'] ?? 0) === $i ? 'selected' : '' ?>><?= $i ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label small fw-semibold">Booking Source</label>
                        <select class="form-select" name="source">
                            <?php foreach ((new \Config\Lookups())->bookingSources as $key => $meta): ?>
                                <option value="<?= esc($key) ?>" <?= ($wizard['source'] ?? 'walk_in') === $key ? 'selected' : '' ?>><?= esc($meta['label']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label small fw-semibold">Bill to Corporate Account <span class="text-muted fw-normal">(optional)</span></label>
                        <input type="hidden" name="corporate_account_id" id="corporate_account_id" value="<?= (int) ($wizard['corporate_account_id'] ?? 0) ?>">
                        <input type="text" class="form-control" id="corporateSearch" placeholder="Search company name..." value="<?= esc($corporateAccount->company_name ?? '') ?>" autocomplete="off">
                        <div id="corporateResults" class="list-group mt-1"></div>
                        <div class="form-text" id="corporateHint"><?= $corporateAccount && $corporateAccount->default_rate_plan_id ? 'This company has a negotiated rate, applied automatically.' : 'Tags the folio for this stay to a company for monthly statement billing.' ?></div>
                    </div>

                    <?php if ($guestPreferences): ?>
                    <div class="alert alert-light border small mb-3">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <strong><i class="bi bi-stars me-1"></i>Guest Preferences on File</strong>
                                <ul class="mb-0 mt-1">
                                    <?php if ($guestPreferences->bed_type): ?><li>Bed: <?= esc($guestPreferences->bed_type) ?></li><?php endif; ?>
                                    <?php if ($guestPreferences->dietary_restrictions): ?><li>Dietary: <?= esc($guestPreferences->dietary_restrictions) ?></li><?php endif; ?>
                                    <?php if ($guestPreferences->allergies): ?><li>Allergies: <?= esc($guestPreferences->allergies) ?></li><?php endif; ?>
                                    <?php if ($guestPreferences->smoking_preference): ?><li>Smoking: <?= esc($lookups->smokingPreferences[$guestPreferences->smoking_preference]['label'] ?? $guestPreferences->smoking_preference) ?></li><?php endif; ?>
                                    <?php if ($guestPreferences->other_notes): ?><li><?= esc($guestPreferences->other_notes) ?></li><?php endif; ?>
                                </ul>
                            </div>
                            <button type="button" class="btn btn-sm btn-outline-secondary flex-shrink-0" id="copyPrefsBtn">Copy to Special Requests</button>
                        </div>
                    </div>
                    <?php endif; ?>

                    <div class="mb-4">
                        <label class="form-label small fw-semibold">Special Requests <span class="text-muted fw-normal">(optional)</span></label>
                        <textarea class="form-control" name="special_requests" id="specialRequests" rows="3" placeholder="Any special requests, arrival time, ..."><?= esc($wizard['special_requests'] ?? '') ?></textarea>
                    </div>

                    <div class="d-flex gap-2">
                        <a href="<?= site_url('bookings/wizard/guest') ?>" class="btn btn-outline-secondary">Back</a>
                        <button type="submit" class="btn btn-primary">Continue to Services</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-5">
        <div class="card shadow-sm">
            <div class="card-header">Room Information</div>
            <div class="card-body">
                <div class="d-flex gap-3 mb-3">
                    <?php if ($room->photo_path ?? null): ?>
                        <img src="<?= site_url('uploads/' . $room->photo_path) ?>" alt="" style="width:72px;height:72px;object-fit:cover;border-radius:8px;">
                    <?php else: ?>
                        <div class="d-flex align-items-center justify-content-center bg-light text-muted" style="width:72px;height:72px;border-radius:8px;"><i class="bi bi-door-closed fs-4"></i></div>
                    <?php endif; ?>
                    <div>
                        <div class="fw-semibold">Room <?= esc($room->room_number) ?></div>
                        <div class="text-muted small"><?= esc($room->room_type_name) ?></div>
                        <div class="text-muted small">Floor <?= esc($room->floor) ?> · Max <?= (int) $room->capacity ?> Guests</div>
                    </div>
                </div>
                <hr>
                <div class="d-flex justify-content-between">
                    <span class="text-muted">Rate / Night</span>
                    <strong><?= format_money($wizard['rate_applied']) ?></strong>
                </div>
                <?php if ($guest): ?>
                <hr>
                <div class="text-muted small text-uppercase fw-bold mb-1">Guest</div>
                <div class="fw-semibold"><?= esc($guest->full_name) ?></div>
                <div class="text-muted small"><?= esc($guest->phone) ?></div>
                <?php elseif (! empty($wizard['new_guest'])): ?>
                <hr>
                <div class="text-muted small text-uppercase fw-bold mb-1">Guest <span class="badge bg-info text-dark">New</span></div>
                <div class="fw-semibold"><?= esc($wizard['new_guest']['full_name']) ?></div>
                <div class="text-muted small"><?= esc($wizard['new_guest']['phone']) ?></div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
const corpSearch = document.getElementById('corporateSearch');
let corpDebounce;
corpSearch.addEventListener('input', function () {
    clearTimeout(corpDebounce);
    const q = this.value.trim();
    const resultsEl = document.getElementById('corporateResults');
    document.getElementById('corporate_account_id').value = 0;

    if (q.length < 2) {
        resultsEl.innerHTML = '';
        return;
    }

    corpDebounce = setTimeout(function () {
        fetch('<?= site_url('corporate-accounts/lookup') ?>?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 () {
                        corpSearch.value = a.company_name;
                        document.getElementById('corporate_account_id').value = a.id;
                        resultsEl.innerHTML = '';
                    });
                    resultsEl.appendChild(item);
                });
            });
    }, 300);
});

document.getElementById('copyPrefsBtn')?.addEventListener('click', function () {
    const items = Array.from(document.querySelectorAll('.alert ul li')).map((li) => li.textContent);
    const textarea = document.getElementById('specialRequests');
    const summary = items.join('; ');
    textarea.value = textarea.value ? textarea.value + ' | ' + summary : summary;
});
</script>
<?= $this->endSection() ?>
