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

<div class="d-flex justify-content-between align-items-start mb-3">
    <div>
        <h1 class="h3 mb-0">Folio #<?= $folio->id ?></h1>
        <p class="text-muted mb-0">
            <a href="<?= site_url('guests/' . $guest->id) ?>"><?= esc($guest->full_name) ?></a> ·
            <span class="badge bg-<?= $folio->status === 'open' ? 'success' : 'secondary' ?>"><?= esc(ucfirst($folio->status)) ?></span>
            <?php if ($corporateAccount): ?>
                · Billed to <a href="<?= site_url('corporate-accounts/' . $corporateAccount->id) ?>"><?= esc($corporateAccount->company_name) ?></a>
            <?php endif; ?>
        </p>
    </div>
    <div class="d-flex gap-2">
        <a href="<?= site_url('folios/' . $folio->id . '/invoice') ?>" class="btn btn-outline-secondary" target="_blank">
            <i class="bi bi-file-earmark-pdf"></i> Download Invoice
        </a>
        <div class="dropdown">
            <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                <i class="bi bi-envelope"></i> Email Invoice
            </button>
            <div class="dropdown-menu dropdown-menu-end p-3" style="min-width: 280px;">
                <form action="<?= site_url('folios/' . $folio->id . '/email-invoice') ?>" method="post">
                    <?= csrf_field() ?>
                    <label class="form-label small">Send to</label>
                    <input type="email" class="form-control form-control-sm mb-2" name="email" value="<?= esc($guest->email ?? '') ?>" placeholder="guest@example.com" required>
                    <button type="submit" class="btn btn-sm btn-primary w-100">Send</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-lg-8 mb-3">
        <div class="card shadow-sm mb-3">
            <div class="card-body">
                <h2 class="h6">Charges</h2>
                <div class="table-scroll">
                    <table class="table table-sm align-middle mb-0">
                        <thead class="table-light">
                            <tr><th>Date</th><th>Description</th><th>Category</th><th class="text-end">Amount</th></tr>
                        </thead>
                        <tbody>
                            <?php if (empty($lineItems)): ?>
                                <tr><td colspan="4" class="text-center text-muted py-3">No charges yet.</td></tr>
                            <?php endif; ?>
                            <?php foreach ($lineItems as $item): ?>
                                <tr>
                                    <td><?= esc($item->item_date) ?></td>
                                    <td><?= esc($item->description) ?></td>
                                    <td><span class="badge bg-light text-dark border"><?= esc($lookups->folioCategories[$item->category]['label'] ?? $item->category) ?></span></td>
                                    <td class="text-end"><?= format_money($item->amount) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr class="table-light">
                                <th colspan="3" class="text-end">Total Charges</th>
                                <th class="text-end"><?= format_money($total) ?></th>
                            </tr>
                        </tfoot>
                    </table>
                </div>

                <?php if ($folio->status === 'open'): ?>
                <form action="<?= site_url('folios/' . $folio->id . '/charges') ?>" method="post" class="row g-2 mt-3 align-items-end border-top pt-3">
                    <?= csrf_field() ?>
                    <div class="col-md-3">
                        <label class="form-label small">Date</label>
                        <input type="date" class="form-control form-control-sm" name="item_date" value="<?= date('Y-m-d') ?>" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label small">Description</label>
                        <input type="text" class="form-control form-control-sm" name="description" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small">Category</label>
                        <select class="form-select form-select-sm" name="category">
                            <?php foreach ($lookups->folioCategories as $key => $meta): ?>
                                <option value="<?= esc($key) ?>"><?= esc($meta['label']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small">Amount</label>
                        <input type="number" step="0.01" min="0.01" class="form-control form-control-sm" name="amount" required>
                    </div>
                    <div class="col-md-1">
                        <button type="submit" class="btn btn-sm btn-outline-primary w-100">Add</button>
                    </div>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <div class="card shadow-sm">
            <div class="card-body">
                <h2 class="h6">Split Billing — Payer Allocations</h2>
                <p class="text-muted small">How much of this folio each payer is responsible for (e.g. guest pays room, company pays extras).</p>
                <table class="table table-sm mb-2">
                    <thead class="table-light"><tr><th>Payer</th><th>Applies To</th><th class="text-end">Amount</th><th>Notes</th></tr></thead>
                    <tbody>
                        <?php if (empty($allocations)): ?>
                            <tr><td colspan="4" class="text-center text-muted py-2">No split — one payer covers the full balance.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($allocations as $alloc): ?>
                            <tr>
                                <td><?= esc($alloc->payer_name) ?></td>
                                <td class="small"><?= $alloc->folio_line_item_id ? esc($alloc->line_item_description) : '<span class="text-muted">Whole balance</span>' ?></td>
                                <td class="text-end"><?= format_money($alloc->amount) ?></td>
                                <td class="small text-muted"><?= esc($alloc->notes) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <?php if (! empty($allocations)): ?>
                        <tfoot>
                            <tr>
                                <th>Allocated</th>
                                <th></th>
                                <th class="text-end"><?= format_money($allocated) ?></th>
                                <th></th>
                            </tr>
                        </tfoot>
                    <?php endif; ?>
                </table>

                <?php if ($folio->status === 'open'): ?>
                <form action="<?= site_url('folios/' . $folio->id . '/allocations') ?>" method="post" class="row g-2 align-items-end border-top pt-3">
                    <?= csrf_field() ?>
                    <div class="col-md-4">
                        <label class="form-label small">Payer name</label>
                        <input type="text" class="form-control form-control-sm" name="payer_name" placeholder="e.g. Acme Ltd (company account)" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label small">Applies to</label>
                        <select class="form-select form-select-sm" name="folio_line_item_id">
                            <option value="">Whole balance</option>
                            <?php foreach ($lineItems as $item): ?>
                                <option value="<?= $item->id ?>"><?= esc($item->description) ?> (<?= format_money($item->amount) ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small">Amount</label>
                        <input type="number" step="0.01" min="0.01" class="form-control form-control-sm" name="amount" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small">Notes</label>
                        <input type="text" class="form-control form-control-sm" name="notes">
                    </div>
                    <div class="col-md-1">
                        <button type="submit" class="btn btn-sm btn-outline-primary w-100">Add</button>
                    </div>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <div class="card shadow-sm">
            <div class="card-body">
                <h2 class="h6">Corporate Billing</h2>
                <p class="text-muted small">Tag this folio to a company for their monthly statement — separate from the split-billing allocations above.</p>
                <form action="<?= site_url('folios/' . $folio->id . '/corporate-account') ?>" method="post" class="row g-2 align-items-end">
                    <?= csrf_field() ?>
                    <input type="hidden" name="corporate_account_id" id="corp_account_id" value="<?= (int) ($corporateAccount->id ?? 0) ?>">
                    <div class="col-md-8">
                        <label class="form-label small">Company</label>
                        <input type="text" class="form-control form-control-sm" id="corp_search" placeholder="Search company name"
                               value="<?= esc($corporateAccount->company_name ?? '') ?>">
                        <div id="corp-search-result" class="form-text"></div>
                    </div>
                    <div class="col-md-4">
                        <button type="submit" class="btn btn-sm btn-outline-primary w-100">Save</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card shadow-sm mb-3">
            <div class="card-body">
                <div class="d-flex justify-content-between"><span>Total Charges</span><strong><?= format_money($total) ?></strong></div>
                <div class="d-flex justify-content-between"><span>Amount Paid</span><strong><?= format_money($paid) ?></strong></div>
                <?php if ((float) $refunded > 0): ?>
                    <div class="d-flex justify-content-between text-danger"><span>Refunded</span><strong>&minus; <?= format_money($refunded) ?></strong></div>
                <?php endif; ?>
                <hr>
                <div class="d-flex justify-content-between fs-5">
                    <span>Balance Due</span>
                    <strong class="<?= (float) $balance > 0 ? 'text-danger' : 'text-success' ?> text-end"><?= format_money($balance, true, true) ?></strong>
                </div>
            </div>
        </div>

        <?php if ($loyaltyAccount): ?>
        <div class="card shadow-sm mb-3">
            <div class="card-body">
                <h2 class="h6 d-flex justify-content-between align-items-center">
                    Loyalty Points
                    <span class="badge bg-<?= ['gold' => 'warning text-dark', 'silver' => 'secondary', 'bronze' => 'danger-subtle text-dark'][$loyaltyAccount->tier] ?? 'secondary' ?>"><?= esc(ucfirst($loyaltyAccount->tier)) ?></span>
                </h2>
                <p class="mb-2"><strong class="fs-5"><?= number_format($loyaltyAccount->points_balance) ?></strong> <span class="text-muted small">points on file</span></p>
                <?php if ($loyaltyAccount->points_balance > 0): ?>
                <form action="<?= site_url('folios/' . $folio->id . '/redeem-points') ?>" method="post" class="row g-2 align-items-end">
                    <?= csrf_field() ?>
                    <div class="col-7">
                        <label class="form-label small">Redeem points</label>
                        <input type="number" class="form-control form-control-sm" name="points" min="1" max="<?= (int) $loyaltyAccount->points_balance ?>" placeholder="e.g. 100">
                    </div>
                    <div class="col-5">
                        <button type="submit" class="btn btn-sm btn-outline-primary w-100">Redeem</button>
                    </div>
                </form>
                <p class="text-muted small mb-0 mt-1">Applied as a credit on this folio.</p>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <?php if ($folio->status === 'open' && (float) $balance > 0): ?>
        <div class="card shadow-sm mb-3">
            <div class="card-body">
                <h2 class="h6">Hubtel Payment Request</h2>
                <?php if ($pendingPayment): ?>
                    <p class="small text-muted mb-2">A payment request for <?= format_money($pendingPayment->amount) ?> is awaiting the guest — send them this link:</p>
                    <div class="input-group input-group-sm mb-2">
                        <input type="text" class="form-control" value="<?= esc($pendingPayment->checkout_url) ?>" id="checkout-link" readonly onclick="this.select()">
                        <button class="btn btn-outline-secondary" type="button" onclick="navigator.clipboard.writeText(document.getElementById('checkout-link').value)">Copy</button>
                    </div>
                    <p class="small text-muted mb-0">Reference: <?= esc($pendingPayment->client_reference) ?> · <span class="badge bg-secondary">Awaiting payment</span></p>
                <?php else: ?>
                    <form action="<?= site_url('folios/' . $folio->id . '/hubtel-payment') ?>" method="post">
                        <?= csrf_field() ?>
                        <button type="submit" class="btn btn-sm btn-outline-primary w-100">Generate Payment Link — <?= format_money($balance) ?></button>
                    </form>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <div class="card shadow-sm">
            <div class="card-body">
                <h2 class="h6">Payments</h2>
                <table class="table table-sm mb-2">
                    <thead class="table-light"><tr><th>When</th><th>Method</th><th class="text-end">Amount</th></tr></thead>
                    <tbody>
                        <?php if (empty($payments)): ?>
                            <tr><td colspan="3" class="text-center text-muted py-2">No payments yet.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($payments as $payment): ?>
                            <tr class="<?= $payment->is_refund ? 'text-danger' : '' ?>">
                                <td class="small">
                                    <?= esc($payment->paid_at) ?>
                                    <?php if ($payment->is_refund): ?>
                                        <br><span class="badge bg-danger-subtle text-danger border border-danger-subtle">Refund</span>
                                        <?php if ($payment->refund_reason): ?><span class="small text-muted d-block"><?= esc($payment->refund_reason) ?></span><?php endif; ?>
                                    <?php endif; ?>
                                </td>
                                <td><span class="badge bg-light text-dark border"><?= esc($lookups->paymentMethods[$payment->method]['label'] ?? $payment->method) ?></span></td>
                                <td class="text-end"><?= $payment->is_refund ? '&minus; ' : '' ?><?= format_money($payment->amount) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

                <?php if ($folio->status === 'open'): ?>
                <form action="<?= site_url('folios/' . $folio->id . '/payments') ?>" method="post" class="border-top pt-3">
                    <?= csrf_field() ?>
                    <div class="mb-2">
                        <label class="form-label small">Amount</label>
                        <input type="number" step="0.01" min="0.01" class="form-control form-control-sm" name="amount" required>
                    </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-outline-primary w-100">Record Payment</button>
                </form>
                <?php endif; ?>

                <?php if ((float) $paid > 0): ?>
                <form action="<?= site_url('folios/' . $folio->id . '/refund') ?>" method="post" class="border-top pt-3 mt-3" onsubmit="return confirm('Record a refund of GHS ' + this.amount.value + '? This cannot be undone.');">
                    <?= csrf_field() ?>
                    <h3 class="h6 text-danger"><i class="bi bi-arrow-counterclockwise me-1"></i>Refund</h3>
                    <div class="mb-2">
                        <label class="form-label small">Amount <span class="text-muted">(up to <?= format_money($paid) ?>)</span></label>
                        <input type="number" step="0.01" min="0.01" max="<?= esc($paid) ?>" class="form-control form-control-sm" name="amount" required>
                    </div>
                    <div class="mb-2">
                        <label class="form-label small">Refunded via</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>
                    <div class="mb-2">
                        <label class="form-label small">Reason</label>
                        <input type="text" class="form-control form-control-sm" name="refund_reason" placeholder="e.g. Guest overcharged, cancelled extra night" required>
                    </div>
                    <button type="submit" class="btn btn-sm btn-outline-danger w-100">Record Refund</button>
                </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
const corpSearch = document.getElementById('corp_search');
if (corpSearch) {
    let debounce;
    corpSearch.addEventListener('input', function () {
        clearTimeout(debounce);
        const q = this.value.trim();
        const resultEl = document.getElementById('corp-search-result');
        if (!q) { document.getElementById('corp_account_id').value = 0; resultEl.innerHTML = ''; return; }
        debounce = setTimeout(() => {
            fetch('<?= site_url('corporate-accounts/lookup') ?>?q=' + encodeURIComponent(q))
                .then((r) => r.json())
                .then((data) => {
                    if (data.results.length) {
                        const first = data.results[0];
                        document.getElementById('corp_account_id').value = first.id;
                        resultEl.innerHTML = '<span class="text-success">Match: ' + first.company_name + '</span>';
                    } else {
                        document.getElementById('corp_account_id').value = 0;
                        resultEl.innerHTML = '<span class="text-muted">No match — <a href="<?= site_url('corporate-accounts/new') ?>" target="_blank">create a new account &rarr;</a></span>';
                    }
                });
        }, 300);
    });
}
</script>
<?= $this->endSection() ?>
