<?php $this->start('body');
    $s        = $this->data['schedule'] ?? [];
    $items    = $this->data['items'] ?? [];
    $groups   = $this->data['groups'] ?? [];
    $approval = $this->data['approval'] ?? [];
    $steps    = $this->data['steps'] ?? [];
    $canEdit  = !empty($this->data['can_edit']);

    $statusChip = [
        'DRAFT'            => ['#F1F5F9','#334155','Draft'],
        'SUBMITTED'        => ['#EEF2F6','#7A8BA1','Awaiting FM/Exec'],
        'APPROVED'         => ['#EAF2E8','#3F5C43','Approved · awaiting FM prepare'],
        'READY_TO_EXECUTE' => ['#FEF3E7','#8B6914','Ready to execute · Accountant'],
        'DECLINED'         => ['#F5EAE1','#C48579','Declined'],
        'PAID'             => ['#EAF2E8','#3F5C43','Paid'],
        'CANCELLED'        => ['#F1F5F9','#334155','Cancelled'],
    ];
    $sc = $statusChip[$s['status']] ?? ['#F1F5F9','#334155',$s['status']];
    $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'],
        'UNSET'         => ['#F1F5F9','#334155','Method unset'],
    ];
?>

<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-money-check-alt me-2 text-muted"></i><?= htmlspecialchars($s['schedule_no']); ?></h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            <?= htmlspecialchars($s['currency']); ?> <?= number_format((float)$s['total_amount']); ?>
            · <?= (int)$s['item_count']; ?> item<?= (int)$s['item_count'] === 1 ? '' : 's' ?>
            <?php if (!empty($s['scheduled_date'])): ?> · scheduled <?= htmlspecialchars(date('d M Y', strtotime($s['scheduled_date']))); ?><?php endif; ?>
            · created by <?= htmlspecialchars($s['created_by_name']); ?>
        </div>
    </div>
    <?php
        // Slice 8Z-o · Prepare button (FM/Admin, when APPROVED)
        $canPrepare = $s['status'] === 'APPROVED' && UserGroups::can('PaymentSchedules','preparePaymentAj');
        // Slice 8Z-m/o · Record Disbursement — Accountant/FM/Admin, on APPROVED (pinch) or READY_TO_EXECUTE (normal)
        $canRecord = in_array($s['status'], ['APPROVED','READY_TO_EXECUTE'], true) && UserGroups::can('PaymentSchedules','recordDisbursementAj');
    ?>
    <div class="d-flex align-items-center gap-2">
        <span class="badge" style="background:<?= $sc[0]; ?>;color:<?= $sc[1]; ?>;border:1px solid <?= $sc[1]; ?>;font-size:.65rem;text-transform:capitalize;"><?= htmlspecialchars($sc[2]); ?></span>
        <?php if (!empty($approval)): ?>
            <a href="<?= PROOT; ?>FinChains/view/<?= (int)$approval['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-external-link-alt me-1"></i>Open approval</a>
        <?php endif; ?>
        <a href="<?= PROOT; ?>PaymentSchedules" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>All schedules</a>
    </div>
</div>

<?php // Slice 8Z-p · Actions bar — Prepare + Record laid out with room to breathe
if ($canPrepare || $canRecord): ?>
    <div class="card border-0 shadow-sm mb-3">
        <div class="card-body p-3">
            <div class="d-flex align-items-stretch flex-wrap gap-3 justify-content-end">
                <?php if ($canPrepare): ?>
                    <div style="min-width:260px;max-width:340px;flex:1;">
                        <button type="button" id="btn_prepare_pay" class="btn btn-sm w-100" style="background:#8B6914;border-color:#8B6914;color:#fff;font-weight:600;">
                            <i class="fas fa-clipboard-list me-1"></i>Prepare payment
                        </button>
                        <div class="text-muted mt-1" style="font-size:.62rem;line-height:1.3;">
                            <strong>FM step ·</strong> allocate cheque # / batch code / letter ref <em>before</em> execution. Optionally attach signed cheque photo or letter PDF.
                        </div>
                    </div>
                <?php endif; ?>
                <?php if ($canRecord): ?>
                    <div style="min-width:260px;max-width:340px;flex:1;">
                        <button type="button" id="btn_record_disb" class="btn btn-sm w-100" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;" title="<?= $s['status'] === 'APPROVED' ? 'Bypass Prepare (pinch mode) — record refs directly.' : 'Execute the prepared payment · record refs + proof.'; ?>">
                            <i class="fas fa-paper-plane me-1"></i>Record disbursement<?= $s['status'] === 'APPROVED' ? ' <span class="text-muted" style="font-weight:400;font-size:.62rem;">(pinch)</span>' : ''; ?>
                        </button>
                        <div class="text-muted mt-1" style="font-size:.62rem;line-height:1.3;">
                            <strong>Accountant step ·</strong> enter actual bank / M-Pesa txn ID + attach proof <em>after</em> payment cleared. Flips LPOs to PAID + notifies requesters.
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
<?php endif; ?>

<?php if ($canPrepare): ?>
<script>
(function () {
    var SID = <?= (int)$s['c0d']; ?>;

    // Slice 8Z-o · seed the modal with any existing prep (in case FM is re-preparing)
    var CURRENT = {
        instrument:      <?= json_encode((string)($s['disburse_instrument'] ?? '')); ?>,
        instrument_ref:  <?= json_encode((string)($s['disburse_instrument_ref'] ?? '')); ?>,
        planned_date:    <?= json_encode((string)($s['disburse_planned_date'] ?? '')); ?>,
        prep_notes:      <?= json_encode((string)($s['disburse_prep_notes'] ?? '')); ?>
    };

    document.getElementById('btn_prepare_pay').addEventListener('click', function () {
        var instOptions = [
            ['CHEQUE',          'Cheque'],
            ['BANK_BATCH',      'Bank batch (TIPS / EFT file)'],
            ['MOBILE_BATCH',    'Mobile batch (M-Pesa Business)'],
            ['BANK_LETTER',     'Bank instruction letter'],
            ['CASH_WITHDRAWAL', 'Cash withdrawal (physical)'],
            ['MIXED',           'Mixed (multiple methods)']
        ].map(function (o) {
            return '<option value="' + o[0] + '"' + (CURRENT.instrument === o[0] ? ' selected' : '') + '>' + o[1] + '</option>';
        }).join('');

        $.confirm({
            title: 'Prepare payment', columnClass: 'col-md-7', type: 'orange',
            content:
                '<form id="pp_form" enctype="multipart/form-data">' +
                    '<input type="hidden" name="schedule_id" value="' + SID + '">' +
                    '<div class="small mb-2">Allocate the payment instrument you\'ll use. This flips the schedule to <strong>Ready to execute</strong> and nudges Accountant to record the actual refs + proof after execution.</div>' +
                    '<div class="row g-2 mb-2">' +
                        '<div class="col-6"><label class="form-label small">Instrument *</label>' +
                            '<select name="disburse_instrument" class="form-select form-select-sm">' + instOptions + '</select></div>' +
                        '<div class="col-6"><label class="form-label small">Planned release date</label>' +
                            '<input type="date" name="disburse_planned_date" class="form-control form-control-sm" value="' + (CURRENT.planned_date || new Date(Date.now() + 86400000).toISOString().slice(0,10)) + '"></div>' +
                    '</div>' +
                    '<label class="form-label small">Instrument reference *</label>' +
                    '<input type="text" name="disburse_instrument_ref" class="form-control form-control-sm mb-2" value="' + (CURRENT.instrument_ref || '') + '" placeholder="Cheque # · batch code · letter number · withdrawal slip #" required>' +
                    '<label class="form-label small">Notes for cashier</label>' +
                    '<textarea name="disburse_prep_notes" rows="2" class="form-control form-control-sm mb-2" placeholder="Anything the Accountant should know (pickup instructions, contact, signing arrangement, split payouts, etc.)">' + (CURRENT.prep_notes || '') + '</textarea>' +
                    '<label class="form-label small">Attachment <span class="text-muted" style="font-weight:400;">(optional · signed cheque photo, bank letter PDF, screenshot)</span></label>' +
                    '<input type="file" name="prep_proof" class="form-control form-control-sm" accept=".pdf,.jpg,.jpeg,.png,.webp">' +
                    '<div class="text-muted mt-1" style="font-size:.6rem;">PDF / JPG / PNG · max 10 MB. Attach multiple by re-preparing.</div>' +
                '</form>',
            buttons: {
                yes: { text: 'Prepare + nudge Accountant', btnClass: 'btn-warning', action: function () {
                    var form = document.getElementById('pp_form');
                    var ref = form.disburse_instrument_ref.value.trim();
                    if (!ref) {
                        $.alert({title:'Instrument reference required', content:'Cheque #, batch code, or letter number (audit trail).', type:'orange'});
                        return false;
                    }
                    var fd = new FormData(form);
                    $.ajax({
                        url: '<?= PROOT; ?>PaymentSchedules/preparePaymentAj',
                        method: 'POST', data: fd, processData: false, contentType: false, dataType: 'json'
                    }).done(function (r) {
                        if (r && r.ok) { rsToast('Prepared · Accountant nudged' + (r.attached ? ' · attachment saved' : '') + '.', 'success'); setTimeout(function(){location.reload();}, 500); }
                        else $.alert({title:'Could not prepare', content:(r && r.msg) || 'Server error', type:'red'});
                    }).fail(function () { $.alert({title:'Network error', type:'red'}); });
                    return false;
                }},
                cancel: function () {}
            }
        });
    });
})();
</script>
<?php endif; ?>

<?php if ($canRecord): ?>
<script>
(function () {
    var SID = <?= (int)$s['c0d']; ?>;
    var ITEMS = <?= json_encode(array_map(function ($it) {
        return ['lpo_id' => (int)$it['lpo_id'], 'lpo_no' => $it['lpo_no'], 'amount' => (float)$it['amount'], 'method' => $it['method']];
    }, $items)); ?>;

    document.getElementById('btn_record_disb').addEventListener('click', function () {
        var perLineRows = ITEMS.map(function (it) {
            return '<tr>' +
                     '<td class="small"><code>' + it.lpo_no + '</code></td>' +
                     '<td class="small text-muted" style="font-size:.62rem;">' + it.method.toLowerCase().replace('_',' ') + '</td>' +
                     '<td class="text-end small">' + Number(it.amount).toLocaleString() + '</td>' +
                     '<td><input type="text" name="per_line[' + it.lpo_id + ']" class="form-control form-control-sm per-line-ref" data-lpo-id="' + it.lpo_id + '" placeholder="txn ref"></td>' +
                     '<td><input type="file" name="line_proofs[' + it.lpo_id + ']" class="form-control form-control-sm" accept=".pdf,.jpg,.jpeg,.png,.webp"></td>' +
                   '</tr>';
        }).join('');

        $.confirm({
            title: 'Record disbursement',
            columnClass: 'col-md-10',
            content:
                '<form id="rd_form" enctype="multipart/form-data">' +
                    '<input type="hidden" name="schedule_id" value="' + SID + '">' +
                    '<div class="small mb-2">Pick a mode: one <strong>batch reference + batch proof</strong> for the whole run, OR per-line references + per-line proofs (paste each txn ID + upload each screenshot). Applied amounts update each LPO\'s <em>amount_paid</em>; fully-paid LPOs flip to PAID, partial stays BOOKED for another schedule.</div>' +
                    '<div class="row g-2 mb-2">' +
                        '<div class="col-8"><label class="form-label small">Batch reference <span class="text-muted" style="font-weight:400;">(fills lines without per-line ref)</span></label>' +
                            '<input type="text" name="batch_ref" class="form-control form-control-sm" placeholder="e.g. M-Pesa batch ID · TIPS batch ref · Cheque book range"></div>' +
                        '<div class="col-4"><label class="form-label small">Batch proof <span class="text-muted" style="font-weight:400;">(required if batch ref)</span></label>' +
                            '<input type="file" name="batch_proof" class="form-control form-control-sm" accept=".pdf,.jpg,.jpeg,.png,.webp"></div>' +
                    '</div>' +
                    '<div class="table-responsive" style="max-height:340px;"><table class="table table-sm mb-0 align-middle">' +
                        '<thead class="table-light"><tr><th>LPO</th><th>Method</th><th class="text-end">Amount</th><th>Ref (per-line)</th><th>Proof (per-line, optional)</th></tr></thead>' +
                        '<tbody>' + perLineRows + '</tbody>' +
                    '</table></div>' +
                    '<div class="alert py-2 mt-2 mb-0 small" style="background:#EEF2F6;border:1px solid #7A8BA1;color:#334155;font-size:.65rem;">' +
                        '<i class="fas fa-info-circle me-1"></i>PDF / JPG / PNG · max 10 MB per file. Proofs are attached to this schedule for the audit trail.' +
                    '</div>' +
                '</form>',
            type: 'green',
            buttons: {
                yes: { text: 'Mark all paid', btnClass: 'btn-success', action: function () {
                    var form = document.getElementById('rd_form');
                    var batchRef = form.batch_ref.value.trim();
                    var perLineCount = 0;
                    document.querySelectorAll('.per-line-ref').forEach(function (inp) { if ((inp.value||'').trim()) perLineCount++; });
                    if (!batchRef && perLineCount === 0) {
                        $.alert({title:'Reference required', content:'Enter a batch reference (+ batch proof) OR per-line refs (audit trail).', type:'orange'});
                        return false;
                    }
                    if (batchRef && (!form.batch_proof.files || form.batch_proof.files.length === 0)) {
                        $.alert({title:'Batch proof required', content:'Attach the M-Pesa confirmation / bank statement excerpt for the batch reference.', type:'orange'});
                        return false;
                    }
                    var fd = new FormData(form);
                    $.ajax({
                        url: '<?= PROOT; ?>PaymentSchedules/recordDisbursementAj',
                        method: 'POST', data: fd, processData: false, contentType: false, dataType: 'json'
                    }).done(function (j) {
                        if (j && j.ok) { rsToast(j.paid_count + ' items disbursed.', 'success'); setTimeout(function(){location.reload();}, 600); }
                        else $.alert({title:'Failed', content:(j && j.msg) || 'Server error', type:'red'});
                    }).fail(function () { $.alert({title:'Network error', type:'red'}); });
                    return false;
                }},
                cancel: function () {}
            }
        });
    });
})();
</script>
<?php endif; ?>

<?php if (!empty($s['notes'])): ?>
    <div class="alert py-2 mb-3 small" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#334155;font-size:.72rem;">
        <i class="fas fa-comment-dots me-1 text-muted"></i><?= nl2br(htmlspecialchars($s['notes'])); ?>
    </div>
<?php endif; ?>

<?php // Slice 8Z-p · Workflow banner (visible in the disbursement window) ─────
if (in_array($s['status'], ['APPROVED','READY_TO_EXECUTE'], true)):
    // Step highlights per current status
    $step1Done = true; // APPROVED means Exec has authorised
    $step2Done = $s['status'] === 'READY_TO_EXECUTE';
    $step3Done = false;
    $activeStep = $step2Done ? 3 : 2;
?>
    <div class="card border-0 shadow-sm mb-3" style="background:#F8FAFC;border:1px solid #E2E8F0!important;">
        <div class="card-body p-3">
            <div class="small mb-2" style="font-weight:600;color:#334155;font-size:.72rem;">
                <i class="fas fa-route me-1 text-muted"></i>Disbursement workflow · next steps
            </div>
            <div class="d-flex align-items-center flex-wrap gap-2">
                <div class="d-flex align-items-center gap-2 px-3 py-2 rounded" style="background:#EAF2E8;border:1px solid #3F5C43;">
                    <i class="fas fa-check-circle" style="color:#3F5C43;"></i>
                    <div style="line-height:1.05;">
                        <div style="font-weight:600;font-size:.7rem;color:#3F5C43;">Authorised</div>
                        <div class="text-muted" style="font-size:.6rem;">Exec approved</div>
                    </div>
                </div>
                <i class="fas fa-chevron-right text-muted mx-1"></i>
                <?php $s2Bg = $step2Done ? '#EAF2E8' : ($activeStep === 2 ? '#FEF3E7' : '#F1F5F9');
                      $s2Br = $step2Done ? '#3F5C43' : ($activeStep === 2 ? '#8B6914' : '#94A3B8');
                      $s2Ico = $step2Done ? 'fa-check-circle' : ($activeStep === 2 ? 'fa-hourglass-half' : 'fa-circle'); ?>
                <div class="d-flex align-items-center gap-2 px-3 py-2 rounded" style="background:<?= $s2Bg; ?>;border:1px solid <?= $s2Br; ?>;">
                    <i class="fas <?= $s2Ico; ?>" style="color:<?= $s2Br; ?>;"></i>
                    <div style="line-height:1.05;">
                        <div style="font-weight:600;font-size:.7rem;color:<?= $s2Br; ?>;">FM prepares payment</div>
                        <div class="text-muted" style="font-size:.6rem;">Allocate cheque # / batch code / letter ref</div>
                    </div>
                </div>
                <i class="fas fa-chevron-right text-muted mx-1"></i>
                <?php $s3Bg = $activeStep === 3 ? '#FEF3E7' : '#F1F5F9';
                      $s3Br = $activeStep === 3 ? '#8B6914' : '#94A3B8';
                      $s3Ico = $activeStep === 3 ? 'fa-hourglass-half' : 'fa-circle'; ?>
                <div class="d-flex align-items-center gap-2 px-3 py-2 rounded" style="background:<?= $s3Bg; ?>;border:1px solid <?= $s3Br; ?>;">
                    <i class="fas <?= $s3Ico; ?>" style="color:<?= $s3Br; ?>;"></i>
                    <div style="line-height:1.05;">
                        <div style="font-weight:600;font-size:.7rem;color:<?= $s3Br; ?>;">Accountant executes + records</div>
                        <div class="text-muted" style="font-size:.6rem;">Actual bank / M-Pesa ref + proof</div>
                    </div>
                </div>
                <i class="fas fa-chevron-right text-muted mx-1"></i>
                <div class="d-flex align-items-center gap-2 px-3 py-2 rounded" style="background:#F1F5F9;border:1px solid #94A3B8;">
                    <i class="fas fa-circle" style="color:#94A3B8;"></i>
                    <div style="line-height:1.05;">
                        <div style="font-weight:600;font-size:.7rem;color:#94A3B8;">Paid</div>
                        <div class="text-muted" style="font-size:.6rem;">Requesters notified</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

<?php // Slice 8Z-m · show source account (FM-selected at approval)
if (!empty($s['source_account_id'])):
    if (!class_exists('CompanyBankAccounts')) require_once ROOT . '/app/models/CompanyBankAccounts.php';
    $srcAcct = (new CompanyBankAccounts())->byId((int)$s['source_account_id']);
    if (!empty($srcAcct)):
        $srcMask = strlen((string)$srcAcct['account_number']) > 4
                   ? str_repeat('•', max(3, strlen($srcAcct['account_number']) - 4)) . substr($srcAcct['account_number'], -4)
                   : $srcAcct['account_number'];
?>
    <div class="alert py-2 mb-3 small d-flex align-items-center justify-content-between" style="background:#EEF2F6;border:1px solid #7A8BA1;color:#334155;font-size:.72rem;">
        <div><i class="fas fa-vault me-1" style="color:#7A8BA1;"></i><strong>Funded from:</strong> <?= htmlspecialchars($srcAcct['account_name']); ?> · <?= htmlspecialchars($srcAcct['provider_name'] ?: '—'); ?> · <code><?= htmlspecialchars($srcMask); ?></code> · <?= htmlspecialchars($srcAcct['currency']); ?></div>
    </div>
<?php   endif;
endif; ?>

<?php // Slice 8Z-o · FM prep card (instrument allocation for Accountant to execute)
if (!empty($s['disburse_prepared_at'])):
    $instLabels = [
        'CHEQUE'         => ['#F1F5F9','#334155','Cheque'],
        'BANK_BATCH'     => ['#EEF2F6','#7A8BA1','Bank batch'],
        'MOBILE_BATCH'   => ['#FEF3E7','#8B6914','Mobile batch'],
        'BANK_LETTER'    => ['#EEF2F6','#7A8BA1','Bank letter'],
        'CASH_WITHDRAWAL'=> ['#F5EAE1','#C48579','Cash withdrawal'],
        'MIXED'          => ['#F1F5F9','#334155','Mixed'],
    ];
    $ic = $instLabels[$s['disburse_instrument']] ?? ['#F1F5F9','#334155',$s['disburse_instrument']];
?>
    <div class="card border-0 shadow-sm mb-3">
        <div class="card-header py-2 small" style="background:#FEF3E7;border-bottom:1px solid #8B6914;font-weight:600;color:#5B4F3C;">
            <i class="fas fa-clipboard-list me-1" style="color:#8B6914;"></i>Payment instrument prepared by FM
            <span class="text-muted ms-2" style="font-weight:400;font-size:.65rem;color:#5B4F3C;">Accountant executes next</span>
        </div>
        <div class="card-body p-3">
            <div class="row g-3">
                <div class="col-md-3">
                    <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Instrument</div>
                    <span class="badge" style="background:<?= $ic[0]; ?>;color:<?= $ic[1]; ?>;border:1px solid <?= $ic[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($ic[2]); ?></span>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Instrument ref</div>
                    <div class="small"><code><?= htmlspecialchars($s['disburse_instrument_ref']); ?></code></div>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Planned release</div>
                    <div class="small"><?= !empty($s['disburse_planned_date']) ? htmlspecialchars(date('d M Y', strtotime($s['disburse_planned_date']))) : '<span class="text-muted">—</span>'; ?></div>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Prepared by</div>
                    <div class="small"><?= htmlspecialchars($s['disburse_prepared_by_name']); ?></div>
                    <div class="text-muted small" style="font-size:.62rem;"><?= htmlspecialchars(date('d M · H:i', strtotime($s['disburse_prepared_at']))); ?></div>
                </div>
                <?php if (!empty($s['disburse_prep_notes'])): ?>
                    <div class="col-12">
                        <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Notes for cashier</div>
                        <div class="small" style="color:#334155;"><?= nl2br(htmlspecialchars($s['disburse_prep_notes'])); ?></div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
<?php endif; ?>

<?php // Slice 8Z-n · proof-of-payment attachments (visible to all approvers + Accountant)
    $attachments = $this->data['attachments'] ?? [];
    if (!empty($attachments)):
?>
    <div class="card border-0 shadow-sm mb-3">
        <div class="card-header py-2 small" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-weight:600;color:#334155;">
            <i class="fas fa-paperclip me-1 text-muted"></i>Proof of payment (<?= count($attachments); ?>)
        </div>
        <div class="table-responsive">
            <table class="table table-sm mb-0 align-middle">
                <thead class="table-light">
                    <tr>
                        <th style="width:100px;">Scope</th>
                        <th>File</th>
                        <th>LPO</th>
                        <th>Uploaded by</th>
                        <th style="width:140px;">When</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($attachments as $att):
                        $scopeChip = match ($att['scope']) {
                            'PREP'  => ['#FEF3E7','#8B6914','Prep (FM)'],
                            'BATCH' => ['#EAF2E8','#3F5C43','Batch'],
                            'LINE'  => ['#EEF2F6','#7A8BA1','Per-line'],
                            default => ['#F1F5F9','#334155',$att['scope']],
                        };
                    ?>
                        <tr>
                            <td><span class="badge" style="background:<?= $scopeChip[0]; ?>;color:<?= $scopeChip[1]; ?>;border:1px solid <?= $scopeChip[1]; ?>;font-size:.62rem;"><?= htmlspecialchars($scopeChip[2]); ?></span></td>
                            <td class="small"><a href="<?= PROOT; ?>PaymentSchedules/proofDownload/<?= (int)$att['c0d']; ?>" target="_blank" class="text-decoration-none"><i class="fas fa-file-<?= strpos((string)$att['mime'], 'pdf') !== false ? 'pdf' : 'image'; ?> me-1" style="color:#7A8BA1;"></i><?= htmlspecialchars($att['original_name']); ?></a>
                                <div class="text-muted" style="font-size:.62rem;"><?= number_format($att['size_bytes'] / 1024, 1); ?> KB</div>
                            </td>
                            <td class="small text-muted"><?= !empty($att['lpo_no']) ? htmlspecialchars($att['lpo_no']) : '—'; ?></td>
                            <td class="small text-muted"><?= htmlspecialchars($att['uploaded_by_name']); ?></td>
                            <td class="small text-muted" style="font-size:.62rem;"><?= htmlspecialchars(date('d M · H:i', strtotime($att['uploaded_on']))); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
<?php endif; ?>

<!-- Groups (method summary bar) -->
<?php if (!empty($groups)): ?>
<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;">Breakdown by method:</div>
            <?php foreach ($groups as $g):
                $mc = $methodChip[$g['method']] ?? ['#F1F5F9','#334155',$g['method']];
            ?>
                <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)$g['count']; ?> · <strong><?= number_format((float)$g['total']); ?></strong>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Grouped items -->
<?php foreach ($groups as $g):
    $mc = $methodChip[$g['method']] ?? ['#F1F5F9','#334155',$g['method']];
?>
    <div class="card border-0 shadow-sm mb-3">
        <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;">
                <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)$g['count']; ?> payment<?= (int)$g['count'] === 1 ? '' : 's' ?>
            </div>
            <div class="small" style="font-weight:600;color:#334155;"><?= htmlspecialchars($s['currency']); ?> <?= number_format((float)$g['total']); ?></div>
        </div>
        <div class="table-responsive">
            <table class="table table-sm mb-0 align-middle">
                <thead class="table-light">
                    <tr>
                        <th>LPO</th>
                        <th>Payee</th>
                        <th>Destination</th>
                        <th class="text-end" style="width:130px;">Amount</th>
                        <th>Purpose</th>
                        <?php if ($canEdit): ?><th style="width:60px;" class="text-end"></th><?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($g['items'] as $it):
                        $acctMasked = !empty($it['dest_account']) && strlen($it['dest_account']) > 4
                                      ? str_repeat('•', max(3, strlen($it['dest_account']) - 4)) . substr($it['dest_account'], -4)
                                      : $it['dest_account'];
                    ?>
                        <tr>
                            <td class="small"><a href="<?= PROOT; ?>Lpos/view/<?= (int)$it['lpo_id']; ?>" class="text-decoration-none" style="color:#7A8BA1;font-weight:600;"><?= htmlspecialchars($it['lpo_no']); ?></a>
                                <?php if (!empty($it['payment_request_id'])): ?>
                                    <a href="<?= PROOT; ?>PaymentRequests/view/<?= (int)$it['payment_request_id']; ?>" class="text-decoration-none" style="font-size:.6rem;">
                                        <span class="badge" style="background:#FEF3E7;color:#8B6914;border:1px solid #8B6914;font-weight:600;font-size:.55rem;">via PR <?= htmlspecialchars((string)($it['pr_no'] ?? '')); ?></span>
                                    </a>
                                <?php endif; ?>
                                <div class="text-muted" style="font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$it['lpo_type']))); ?></div>
                            </td>
                            <td class="small"><?= htmlspecialchars($it['requested_by_name']); ?>
                                <?php if (!empty($it['project_no'])): ?><div class="text-muted" style="font-size:.62rem;"><?= htmlspecialchars($it['project_no']); ?></div><?php endif; ?>
                            </td>
                            <td class="small">
                                <?php if (!empty($it['dest_provider'])): ?>
                                    <strong><?= htmlspecialchars($it['dest_provider']); ?></strong> · <code><?= htmlspecialchars((string)$acctMasked); ?></code>
                                    <div class="text-muted" style="font-size:.62rem;"><?= htmlspecialchars($it['dest_holder']); ?><?= $it['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="text-end small" style="font-weight:600;color:#334155;"><?= htmlspecialchars($it['currency']); ?> <?= number_format((float)$it['amount']); ?></td>
                            <td class="small text-muted" style="max-width:280px;color:#64748B;"><?= htmlspecialchars(mb_strimwidth((string)$it['purpose'], 0, 100, '…')); ?></td>
                            <?php if ($canEdit): ?>
                                <td class="text-end">
                                    <button type="button" class="btn btn-sm btn-link p-0 text-danger btn_remove" data-lpo-id="<?= (int)$it['lpo_id']; ?>" title="Remove from schedule"><i class="fas fa-times"></i></button>
                                </td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
<?php endforeach; ?>

<?php if (empty($groups)): ?>
    <div class="alert alert-info py-2 small mb-3">No LPOs on this schedule.</div>
<?php endif; ?>

<?php if ($canEdit): ?>
<script>
(function () {
    var SID = <?= (int)$s['c0d']; ?>;
    document.querySelectorAll('.btn_remove').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var lid = this.dataset.lpoId;
            $.confirm({
                title: 'Remove LPO from schedule?',
                content: 'The LPO stays BOOKED and returns to the queue — you can add it to another schedule later.',
                type: 'orange',
                buttons: {
                    yes: { text: 'Remove', btnClass: 'btn-warning', action: function () {
                        $.post('<?= PROOT; ?>PaymentSchedules/removeLpoAj', { schedule_id: SID, lpo_id: lid }, function (r) {
                            if (r && r.ok) { rsToast('Removed.', 'success'); setTimeout(function(){location.reload();}, 400); }
                            else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                        }, 'json');
                    }},
                    cancel: function () {}
                }
            });
        });
    });
})();
</script>
<?php endif; ?>

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