<?php $this->start('body');
    $rows       = $this->data['rows']  ?? [];
    $types      = $this->data['types'] ?? [];
    $internal   = $this->data['internal'] ?? [];
    $filterType = (string)($this->data['filter_type'] ?? '');
    $box        = $this->data['box'] ?? null;
    $boxBal     = (float)($box['current_balance'] ?? 0);
    $boxMax     = (float)($box['max_disbursement'] ?? 0);
    $boxCur     = (string)($box['currency'] ?? 'TZS');
    $statusChip = [
        'APPROVED'   => ['#EAF2E8','#3F5C43','Approved · ready to disburse'],
        'PV_DRAFTED' => ['#FEF3E7','#8B6914','PV drafted'],
        'SCHEDULED'  => ['#E8EEF3','#7A8BA1','Scheduled for payment'],
        'ISSUED'     => ['#EDE7DC','#5B4F3C','Issued (petty cash)'],
        'PAID'       => ['#EAF2E8','#3F5C43','Paid'],
    ];
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <div>
        <h5 class="mb-0" style="font-weight:600;"><i class="fas fa-hand-holding-usd me-2 text-muted"></i>Cash-out queue</h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            Internal cash requests approved by the chain, awaiting Accountant disbursement (petty cash) or PV drafting.
        </div>
    </div>
    <div class="d-flex align-items-center gap-2">
        <?php if ($box): ?>
            <a href="<?= PROOT; ?>PettyCashBox" class="btn btn-sm text-decoration-none" style="background:#F8FAFC;color:#334155;border:1px solid #E2E8F0;font-weight:600;">
                <i class="fas fa-wallet me-1" style="color:#7A8BA1;"></i>Petty cash: <?= $boxCur; ?> <?= number_format($boxBal); ?>
            </a>
        <?php endif; ?>
        <a href="<?= PROOT; ?>CashRequests/new" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
            <i class="fas fa-plus me-1"></i>New cash request
        </a>
    </div>
</div>

<!-- Type filter chips -->
<div class="mb-3 d-flex flex-wrap gap-1">
    <a href="<?= PROOT; ?>CashRequests/queue" class="badge <?= $filterType === '' ? 'bg-dark' : 'bg-light text-muted'; ?>" style="text-decoration:none;padding:.35em .6em;">All types</a>
    <?php foreach ($internal as $t):
        $lbl = $types[$t]['label'] ?? $t;
        $ico = $types[$t]['icon']  ?? 'fas fa-wallet';
    ?>
        <a href="<?= PROOT; ?>CashRequests/queue?type=<?= $t; ?>" class="badge <?= $filterType === $t ? 'bg-dark' : 'bg-light text-muted'; ?>" style="text-decoration:none;padding:.35em .6em;">
            <i class="<?= $ico; ?> me-1"></i><?= htmlspecialchars($lbl); ?>
        </a>
    <?php endforeach; ?>
</div>

<div class="card border-0 shadow-sm">
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th>LPO #</th>
                    <th>Type</th>
                    <th>Project</th>
                    <th>Requester → Payee</th>
                    <th class="text-end">Amount</th>
                    <th>Purpose</th>
                    <th>Status</th>
                    <th class="text-end">Age</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rows as $r):
                    $lbl = $types[$r['lpo_type']]['label'] ?? $r['lpo_type'];
                    $ico = $types[$r['lpo_type']]['icon']  ?? 'fas fa-wallet';
                    $sc  = $statusChip[$r['cash_out_status']] ?? ['#F1F5F9','#334155', htmlspecialchars(strtolower(str_replace('_',' ', $r['cash_out_status'])))];
                    $ageDays = $r['requested_on'] ? floor((time() - strtotime($r['requested_on'])) / 86400) : 0;
                ?>
                    <tr>
                        <td><a href="<?= PROOT; ?>Lpos/view/<?= (int)$r['c0d']; ?>" class="text-decoration-none"><strong style="color:#7A8BA1;"><?= htmlspecialchars($r['lpo_no']); ?></strong></a></td>
                        <td class="small"><i class="<?= $ico; ?> me-1" style="color:#94A3B8;"></i><?= htmlspecialchars($lbl); ?></td>
                        <td class="small text-muted">
                            <?php if (!empty($r['project_no'])): ?>
                                <?= htmlspecialchars($r['project_no']); ?>
                            <?php else: ?>
                                <span class="text-muted"><em>Central</em></span>
                            <?php endif; ?>
                        </td>
                        <td class="small text-muted">
                            <?= htmlspecialchars($r['requested_by_name']); ?>
                            <?php if (!empty($r['payee_name']) && $r['payee_name'] !== $r['requested_by_name']): ?>
                                <br><span style="color:#94A3B8;">→ <?= htmlspecialchars($r['payee_name']); ?></span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end" style="font-weight:600;color:#334155;"><?= htmlspecialchars($r['currency']); ?> <?= number_format((float)$r['amount']); ?></td>
                        <td class="small text-muted" style="max-width:280px;color:#64748B;"><?= htmlspecialchars($r['purpose']); ?></td>
                        <td><span class="badge" style="background:<?= $sc[0]; ?>;color:<?= $sc[1]; ?>;border:1px solid <?= $sc[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($sc[2]); ?></span></td>
                        <td class="text-end small text-muted"><?= (int)$ageDays; ?>d</td>
                        <td class="text-end">
                            <?php
                                $amt = (float)$r['amount'];
                                $canPettyCash = $box && $r['cash_out_status'] === 'APPROVED'
                                    && $r['currency'] === $boxCur
                                    && $amt > 0 && $amt <= $boxBal;
                                $tooBigForBox = $box && $r['cash_out_status'] === 'APPROVED'
                                    && $r['currency'] === $boxCur
                                    && $boxMax > 0 && $amt > $boxMax;
                            ?>
                            <?php if ($canPettyCash): ?>
                                <button type="button" class="btn btn-sm btn_disburse me-1" data-lpo="<?= (int)$r['c0d']; ?>" data-ref="<?= htmlspecialchars($r['lpo_no']); ?>" data-amount="<?= $amt; ?>" data-currency="<?= $boxCur; ?>"
                                        title="<?= $tooBigForBox ? 'Amount above max single disbursement — draft PV instead' : 'Pay from petty cash tin'; ?>"
                                        style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;<?= $tooBigForBox ? 'opacity:.6;' : ''; ?>">
                                    <i class="fas fa-wallet me-1"></i>Petty cash
                                </button>
                            <?php endif; ?>
                            <a href="<?= PROOT; ?>Lpos/view/<?= (int)$r['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-right"></i></a>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($rows)): ?>
                    <tr><td colspan="9" class="text-center text-muted py-4">Nothing waiting. <i class="fas fa-check-circle text-success"></i></td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
(function () {
    document.querySelectorAll('.btn_disburse').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var lpoId = this.getAttribute('data-lpo');
            var ref   = this.getAttribute('data-ref');
            var amt   = this.getAttribute('data-amount');
            var cur   = this.getAttribute('data-currency');
            $.confirm({
                title: 'Disburse from petty cash?',
                content: '<div class="small">Pay <strong>' + cur + ' ' + Number(amt).toLocaleString() + '</strong> from the petty cash tin for <strong>' + ref + '</strong>?<br><span class="text-muted">The LPO will be marked PAID and the requester notified to collect the cash.</span></div>',
                type: 'green',
                buttons: {
                    yes: { text: 'Disburse', btnClass: 'btn-success', action: function () {
                        $.post('<?= PROOT; ?>PettyCashBox/disburseAj', { lpo_id: lpoId }, function (r) {
                            if (r && r.ok) { rsToast(r.msg || 'Disbursed.', 'success'); setTimeout(function(){location.reload();}, 500); }
                            else $.alert({title:'Could not disburse', content:(r && r.msg) || 'Server error', type:'red'});
                        }, 'json').fail(function () { $.alert({title:'Network error', type:'red'}); });
                    }},
                    cancel: function () {}
                }
            });
        });
    });
})();
</script>

<?php $this->end(); ?>
