<?php $this->start('body');
    $rows  = $this->data['rows']  ?? [];
    $rung  = (string)($this->data['rung']  ?? '');
    $title = (string)($this->data['title'] ?? 'Payment Requests');
    $rungIcon = ['PC_CONFIRM'=>'fa-user-check','PM_REVIEW'=>'fa-user-tie','FM_SCHEDULE'=>'fa-calendar-plus','ACCT_RECORD'=>'fa-file-invoice-dollar'][$rung] ?? 'fa-money-check-alt';
    $isFm = ($rung === 'FM_SCHEDULE');
?>
<div class="d-flex align-items-center justify-content-between mb-3">
    <div>
        <h5 class="mb-0" style="font-weight:600;"><i class="fas <?= $rungIcon; ?> me-2 text-muted"></i>Payment Requests &middot; <?= htmlspecialchars($title); ?></h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;"><?= count($rows); ?> request<?= count($rows) === 1 ? '' : 's'; ?> at this rung</div>
    </div>
    <?php if ($isFm): ?>
        <div class="d-flex align-items-center gap-2">
            <span id="pr_batch_summary" class="text-muted small" style="font-size:.72rem;">0 selected</span>
            <button type="button" id="btn_batch_prs" class="btn btn-sm" disabled style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;opacity:.5;">
                <i class="fas fa-layer-group me-1"></i>Batch to Schedule
            </button>
        </div>
    <?php endif; ?>
</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>
                    <?php if ($isFm): ?><th style="width:36px;"><input type="checkbox" id="pr_pick_all" class="form-check-input"></th><?php endif; ?>
                    <th>PR #</th>
                    <th>LPO</th>
                    <th>Project</th>
                    <th>Payee</th>
                    <th class="text-end">Requested</th>
                    <?php if ($rung === 'ACCT_RECORD'): ?><th>Invoice</th><?php endif; ?>
                    <th>Raised on</th>
                    <th class="text-end"></th>
                </tr>
            </thead>
            <tbody id="pr_queue_body">
                <?php foreach ($rows as $r): ?>
                    <tr data-pr-id="<?= (int)$r['c0d']; ?>" data-currency="<?= htmlspecialchars((string)$r['currency']); ?>" data-amount="<?= (float)$r['requested_amount']; ?>">
                        <?php if ($isFm): ?><td><input type="checkbox" class="form-check-input pr_pick"></td><?php endif; ?>
                        <td><a href="<?= PROOT; ?>PaymentRequests/view/<?= (int)$r['c0d']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars($r['pr_no']); ?></strong></a></td>
                        <td class="small"><?= htmlspecialchars((string)$r['lpo_no']); ?></td>
                        <td class="small text-muted"><?= htmlspecialchars((string)($r['project_no'] ?? '—')); ?></td>
                        <td class="small"><?= htmlspecialchars((string)($r['payee_name'] ?? '')); ?></td>
                        <td class="text-end" style="font-weight:600;color:#334155;"><?= htmlspecialchars((string)$r['currency']); ?> <?= number_format((float)$r['requested_amount']); ?></td>
                        <?php if ($rung === 'ACCT_RECORD'): ?>
                            <td class="small text-muted">
                                <?= !empty($r['supplier_invoice_no']) ? htmlspecialchars((string)$r['supplier_invoice_no']) : '<em>—</em>'; ?>
                            </td>
                        <?php endif; ?>
                        <td class="small text-muted"><?= htmlspecialchars((string)$r['raised_on']); ?><div style="font-size:.6rem;"><?= htmlspecialchars((string)$r['raised_by_name']); ?></div></td>
                        <td class="text-end"><a href="<?= PROOT; ?>PaymentRequests/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)):
                    $span = $rung === 'ACCT_RECORD' ? 8 : 7;
                    if ($isFm) $span++;
                ?>
                    <tr><td colspan="<?= $span; ?>" class="text-center text-muted py-4">
                        Nothing to action right now &mdash; check back later.
                    </td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php if ($isFm && !empty($rows)): ?>
<script>
(function () {
    var PROOT = '<?= PROOT; ?>';
    var pickAll   = document.getElementById('pr_pick_all');
    var summaryEl = document.getElementById('pr_batch_summary');
    var batchBtn  = document.getElementById('btn_batch_prs');
    var body      = document.getElementById('pr_queue_body');

    function fmt(n) { return (parseFloat(n||0)).toLocaleString(undefined, {maximumFractionDigits:0}); }

    function refreshSummary() {
        var picked = body.querySelectorAll('.pr_pick:checked');
        var count = picked.length;
        var totals = {}; // currency -> sum
        picked.forEach(function (cb) {
            var tr = cb.closest('tr');
            var ccy = tr.getAttribute('data-currency');
            var amt = parseFloat(tr.getAttribute('data-amount') || 0);
            totals[ccy] = (totals[ccy] || 0) + amt;
        });
        var parts = Object.keys(totals).map(function (k) { return k + ' ' + fmt(totals[k]); });
        summaryEl.textContent = count + ' selected' + (parts.length ? ' &middot; ' + parts.join(', ') : '');
        summaryEl.innerHTML   = count + ' selected' + (parts.length ? ' &middot; ' + parts.join(', ') : '');
        batchBtn.disabled = (count === 0);
        batchBtn.style.opacity = (count === 0) ? '.5' : '1';

        // Warn on mixed currency (batch requires same currency)
        if (Object.keys(totals).length > 1) {
            batchBtn.disabled = true;
            batchBtn.style.opacity = '.5';
            summaryEl.innerHTML += ' <span style="color:#C48579;">(mixed currency — can\'t batch)</span>';
        }
    }

    if (pickAll) pickAll.addEventListener('change', function () {
        body.querySelectorAll('.pr_pick').forEach(function (cb) { cb.checked = pickAll.checked; });
        refreshSummary();
    });
    body.addEventListener('change', function (e) {
        if (e.target.classList.contains('pr_pick')) refreshSummary();
    });

    batchBtn.addEventListener('click', function () {
        var picked = body.querySelectorAll('.pr_pick:checked');
        var ids = [];
        picked.forEach(function (cb) { ids.push(parseInt(cb.closest('tr').getAttribute('data-pr-id'), 10)); });
        if (ids.length === 0) return;

        var today = new Date().toISOString().slice(0,10);
        $.confirm({
            title: 'Batch ' + ids.length + ' Payment Request' + (ids.length === 1 ? '' : 's'),
            columnClass: 'col-md-6',
            content:
                '<div class="small mb-2 text-muted">Creates a Payment Schedule directly in <strong>READY_TO_EXECUTE</strong> — each selected PR already walked its own PC → PM → FM chain, so no further approval needed. Accountant will record one disbursement to close all.</div>' +
                '<div class="row g-2 mb-2">' +
                '  <div class="col-6"><label class="form-label small">Scheduled date</label><input type="date" id="ps_date" class="form-control form-control-sm" value="' + today + '"></div>' +
                '  <div class="col-6"><label class="form-label small">Notes</label><input type="text" id="ps_notes" class="form-control form-control-sm" placeholder="e.g. Friday cheque run"></div>' +
                '</div>',
            type: 'green',
            buttons: {
                yes: { text: 'Create schedule', btnClass: 'btn-success', action: function () {
                    var payload = {
                        pr_ids: JSON.stringify(ids),
                        scheduled_date: document.getElementById('ps_date').value || '',
                        notes: document.getElementById('ps_notes').value || ''
                    };
                    $.post(PROOT + 'PaymentRequests/batchToScheduleAj', payload, function (r) {
                        if (r && r.ok) {
                            rsToast('Schedule ' + r.schedule_no + ' created with ' + r.added + ' PR(s).', 'success');
                            setTimeout(function () { window.location.href = PROOT + 'PaymentSchedules/view/' + r.id; }, 700);
                        } else $.alert({title:'Batch failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json').fail(function () { $.alert({title:'Network error', type:'red'}); });
                }},
                cancel: function () {}
            }
        });
    });
})();
</script>
<?php endif; ?>

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