<?php $this->start('body');
    $rows          = $this->data['rows'] ?? [];
    $filterMethod  = (string)($this->data['filter_method'] ?? '');
    $methodChip = [
        'MOBILE_MONEY'  => ['#FEF3E7','#8B6914','Mobile money'],
        'BANK_TRANSFER' => ['#EEF2F6','#7A8BA1','Bank transfer'],
        'PETTY_CASH'    => ['#EAF2E8','#3F5C43','Petty cash'],
        'CASH_HANDOVER' => ['#F5EAE1','#C48579','Cash handover'],
        'CHEQUE'        => ['#F1F5F9','#334155','Cheque'],
    ];
    $filters = ['' => 'All methods'] + [
        'MOBILE_MONEY'  => 'Mobile money',
        'BANK_TRANSFER' => 'Bank transfer',
        'PETTY_CASH'    => 'Petty cash',
        'CASH_HANDOVER' => 'Cash handover',
        'CHEQUE'        => 'Cheque',
    ];
    // Group visible rows by method for the summary bar
    $byMethod = [];
    foreach ($rows as $r) {
        $key = $r['disburse_method'] ?: 'UNSET';
        if (!isset($byMethod[$key])) $byMethod[$key] = ['count' => 0, 'total' => 0.0];
        $byMethod[$key]['count']++;
        $byMethod[$key]['total'] += (float)$r['amount'];
    }
    $grandTotal = 0.0; foreach ($rows as $r) $grandTotal += (float)$r['amount'];
?>

<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-inbox me-2 text-muted"></i>Build payment schedule</h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            Pick BOOKED cash LPOs to batch into a payment schedule. Once submitted the batch goes to FM → Exec for funds approval (or Exec only if you're FM).
        </div>
    </div>
    <a href="<?= PROOT; ?>PaymentSchedules" class="btn btn-sm btn-outline-secondary"><i class="fas fa-list me-1"></i>All schedules</a>
</div>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-body p-2" style="background:#F8FAFC;">
        <?php foreach ($filters as $k => $lbl):
            $active = ($k === $filterMethod);
        ?>
            <a href="<?= PROOT; ?>PaymentSchedules/queue<?= $k ? '?method=' . $k : ''; ?>" class="btn btn-sm me-1 mb-1"
               style="background:<?= $active ? '#334155' : '#fff'; ?>;color:<?= $active ? '#fff' : '#334155'; ?>;border:1px solid #E2E8F0;font-weight:<?= $active ? 600 : 400; ?>;font-size:.68rem;">
                <?= htmlspecialchars($lbl); ?>
            </a>
        <?php endforeach; ?>
    </div>
</div>

<?php if (!empty($byMethod)): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-body p-3" style="background:#F8FAFC;">
        <div class="d-flex align-items-center gap-3 flex-wrap">
            <div class="small text-muted" style="font-size:.65rem;font-weight:600;text-transform:capitalize;">In the pool:</div>
            <?php foreach ($byMethod as $mk => $mv):
                $mc = $methodChip[$mk] ?? ['#F1F5F9','#334155',$mk];
            ?>
                <div class="small">
                    <span class="badge me-1" style="background:<?= $mc[0]; ?>;color:<?= $mc[1]; ?>;border:1px solid <?= $mc[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($mc[2]); ?></span>
                    <?= (int)$mv['count']; ?> · <strong><?= number_format((float)$mv['total']); ?></strong>
                </div>
            <?php endforeach; ?>
            <div class="ms-auto small" style="font-weight:600;color:#334155;">
                Grand total: TZS <?= number_format($grandTotal); ?>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="card border-0 shadow-sm">
    <div class="card-header py-2 d-flex align-items-center justify-content-between" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;">
        <div class="small" style="font-weight:600;color:#334155;">
            <input type="checkbox" id="chk_all" class="form-check-input me-2">
            BOOKED cash LPOs (<?= count($rows); ?>)
            <span id="pick_summary" class="text-muted ms-2" style="font-weight:400;font-size:.65rem;">Nothing selected</span>
        </div>
        <button type="button" id="btn_build" class="btn btn-sm" disabled style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;opacity:.5;">
            <i class="fas fa-paper-plane me-1"></i>Create schedule + submit
        </button>
    </div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th style="width:36px;"></th>
                    <th>LPO #</th>
                    <th>Requester</th>
                    <th class="text-end" style="width:130px;">Amount</th>
                    <th style="width:130px;">Method</th>
                    <th>Destination</th>
                    <th>Purpose</th>
                    <th style="width:110px;">Scheduled</th>
                </tr>
            </thead>
            <tbody id="pool_tbody">
                <?php foreach ($rows as $r):
                    $mc = $methodChip[$r['disburse_method'] ?? ''] ?? ['#F1F5F9','#334155', strtolower(str_replace('_',' ', $r['disburse_method'] ?? ''))];
                    $acctMasked = !empty($r['dest_account']) && strlen($r['dest_account']) > 4
                                  ? str_repeat('•', max(3, strlen($r['dest_account']) - 4)) . substr($r['dest_account'], -4)
                                  : $r['dest_account'];
                ?>
                    <tr data-lpo-id="<?= (int)$r['c0d']; ?>" data-amount="<?= (float)$r['amount']; ?>" data-method="<?= htmlspecialchars($r['disburse_method'] ?: 'UNSET'); ?>">
                        <td><input type="checkbox" class="form-check-input row_chk"></td>
                        <td class="small"><a href="<?= PROOT; ?>Lpos/view/<?= (int)$r['c0d']; ?>" class="text-decoration-none" style="color:#7A8BA1;font-weight:600;"><?= htmlspecialchars($r['lpo_no']); ?></a>
                            <div class="text-muted" style="font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$r['lpo_type']))); ?></div>
                        </td>
                        <td class="small"><?= htmlspecialchars($r['requested_by_name']); ?>
                            <?php if (!empty($r['project_no'])): ?><div class="text-muted" style="font-size:.62rem;"><?= htmlspecialchars($r['project_no']); ?></div><?php endif; ?>
                        </td>
                        <td class="text-end small" style="font-weight:600;color:#334155;"><?= htmlspecialchars($r['currency']); ?> <?= number_format((float)$r['amount']); ?></td>
                        <td><span class="badge" style="background:<?= $mc[0]; ?>;color:<?= $mc[1]; ?>;border:1px solid <?= $mc[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($mc[2]); ?></span></td>
                        <td class="small">
                            <?php if (!empty($r['dest_provider'])): ?>
                                <strong><?= htmlspecialchars($r['dest_provider']); ?></strong> · <code><?= htmlspecialchars((string)$acctMasked); ?></code>
                                <div class="text-muted" style="font-size:.62rem;"><?= htmlspecialchars($r['dest_holder']); ?><?= $r['dest_status'] === 'PENDING' ? ' · <span style="color:#8B6914;">pending FM</span>' : ''; ?></div>
                            <?php else: ?>
                                <span class="text-muted small">— physical —</span>
                            <?php endif; ?>
                        </td>
                        <td class="small text-muted" style="max-width:220px;color:#64748B;"><?= htmlspecialchars(mb_strimwidth((string)$r['purpose'], 0, 80, '…')); ?></td>
                        <td class="small text-muted" style="font-size:.62rem;"><?= !empty($r['scheduled_disburse_date']) ? htmlspecialchars(date('d M Y', strtotime($r['scheduled_disburse_date']))) : '—'; ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($rows)): ?>
                    <tr><td colspan="8" class="text-center text-muted py-4" style="font-size:.72rem;">No BOOKED cash LPOs in the pool right now. Approvals still in PM Check or Accountant Prepare will show up here once cleared.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
(function () {
    var chks   = function () { return Array.from(document.querySelectorAll('.row_chk:checked')); };
    var btn    = document.getElementById('btn_build');
    var $sum   = document.getElementById('pick_summary');

    function refresh() {
        var picked = chks();
        if (!picked.length) {
            btn.disabled = true; btn.style.opacity = '.5';
            $sum.textContent = 'Nothing selected';
            return;
        }
        var tot = 0;
        picked.forEach(function (c) { tot += parseFloat(c.closest('tr').dataset.amount || 0); });
        $sum.textContent = picked.length + ' picked · TZS ' + tot.toLocaleString();
        btn.disabled = false; btn.style.opacity = '1';
    }

    document.getElementById('chk_all').addEventListener('change', function () {
        document.querySelectorAll('.row_chk').forEach(function (c) { c.checked = this.checked; }.bind(this));
        refresh();
    });
    document.querySelectorAll('.row_chk').forEach(function (c) { c.addEventListener('change', refresh); });

    btn.addEventListener('click', function () {
        var picked = chks();
        if (!picked.length) return;
        var ids = picked.map(function (c) { return c.closest('tr').dataset.lpoId; });
        $.confirm({
            title: 'Create + submit payment schedule?',
            columnClass: 'col-md-6',
            content:
                '<div class="small mb-3">You\'ve picked <strong>' + ids.length + '</strong> LPO' + (ids.length === 1 ? '' : 's') + '. On submit, the batch goes into FM → Exec approval (or Exec only if you\'re FM).</div>' +
                '<form id="ps_form">' +
                    '<label class="form-label small">Scheduled disbursement date</label>' +
                    '<input type="date" name="scheduled_date" class="form-control form-control-sm" value="' + new Date(Date.now() + 86400000).toISOString().slice(0,10) + '">' +
                    '<label class="form-label small mt-2">Notes (optional)</label>' +
                    '<textarea name="notes" rows="2" class="form-control form-control-sm" placeholder="Anything FM / Exec should know before approving"></textarea>' +
                '</form>',
            type: 'green',
            buttons: {
                yes: { text: 'Create + submit', btnClass: 'btn-success', action: function () {
                    var f = document.getElementById('ps_form');
                    var payload = new URLSearchParams();
                    ids.forEach(function (id) { payload.append('lpo_ids[]', id); });
                    payload.append('scheduled_date', f.scheduled_date.value);
                    payload.append('notes',          f.notes.value);
                    fetch('<?= PROOT; ?>PaymentSchedules/createAj', {
                        method: 'POST',
                        headers: {'Content-Type':'application/x-www-form-urlencoded'},
                        body: payload.toString()
                    }).then(function(r){return r.json();}).then(function(j) {
                        if (j && j.ok) {
                            rsToast(j.msg || 'Schedule submitted.', 'success');
                            setTimeout(function () { window.location.href = '<?= PROOT; ?>PaymentSchedules/view/' + j.id; }, 600);
                        } else {
                            $.alert({title:'Could not create', content:(j && j.msg) || 'Server error', type:'red'});
                        }
                    }).catch(function () { $.alert({title:'Network error', type:'red'}); });
                }},
                cancel: function () {}
            }
        });
    });
})();
</script>

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