<?php $this->start('body');
    $a       = $this->data['a'];
    $steps   = $this->data['steps']   ?? [];
    $hist    = $this->data['history'] ?? [];
    $entity  = $this->data['entity']  ?? [];
    $mayAct  = !empty($this->data['may_act']);
    $reqSlots = $this->data['required_slots'] ?? [];
    $slotOpts = $this->data['slot_options']   ?? [];
    $staged   = $this->data['staged_payload'] ?? ['assignments' => []];
    $curSid = (int)($a['current_step_id'] ?? 0);
    $curNo  = 0; foreach ($steps as $s) if ((int)$s['c0d']===$curSid) $curNo = (int)$s['step_no'];
    $statusClass = ['IN_PROGRESS'=>'bg-info text-white','APPROVED'=>'bg-success','DECLINED'=>'bg-danger','CANCELLED'=>'bg-secondary'][$a['status']] ?? 'bg-light text-muted';
    // Human labels for slot names
    $slotLabel = [
        'ACCOUNTANT'           => 'Accountant',
        'PROCUREMENT'          => 'Procurement',
        'PROJECT_MANAGER'      => 'Project Manager',
        'PROJECTS_COORDINATOR' => 'Projects Coordinator',
        'FINANCE_MANAGER'      => 'Finance Manager',
        'EXECUTIVE'            => 'Executive',
        'FIELD_SUPERVISOR'     => 'Field Supervisor',
        'STORES'               => 'Stores',
        'CRM'                  => 'CRM',
    ];
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <div>
        <h5 class="mb-0" style="font-weight:600;"><?= htmlspecialchars($a['chain_title']); ?></h5>
        <div class="text-muted" style="font-size:.72rem;">
            <?= htmlspecialchars($a['ref_label']); ?> ·
            <span class="badge <?= $statusClass; ?>" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$a['status']))); ?></span>
        </div>
    </div>
    <?php if (!empty($a['return_url'])): ?>
        <a href="<?= PROOT . htmlspecialchars($a['return_url']); ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Back to entity</a>
    <?php endif; ?>
</div>

<!-- Step ladder ---------------------------------------------------------- -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-body p-3">
        <div class="d-flex align-items-center flex-wrap gap-2">
            <?php foreach ($steps as $i => $s):
                $n  = (int)$s['step_no'];
                $st = ($a['status'] === 'APPROVED') ? 'done'
                    : (($a['status'] === 'IN_PROGRESS' && $n < $curNo) ? 'done'
                    : (($a['status'] === 'IN_PROGRESS' && $n === $curNo) ? 'now' : 'todo'));
                $ico  = ['done'=>'fa-check-circle','now'=>'fa-hourglass-half','todo'=>'fa-circle'][$st];
                $col  = ['done'=>'#22c55e','now'=>'#f59e0b','todo'=>'#cbd5e1'][$st];
            ?>
                <div class="d-flex align-items-center">
                    <div class="d-flex align-items-center gap-2 px-2 py-1 rounded" style="border:1px solid <?= $col; ?>33;background:<?= $col; ?>0d;">
                        <i class="fas <?= $ico; ?>" style="color:<?= $col; ?>;"></i>
                        <div style="line-height:1.05;">
                            <div style="font-weight:600;font-size:.78rem;"><?= htmlspecialchars($s['step_label']); ?></div>
                            <div class="text-muted" style="font-size:.62rem;text-transform:uppercase;letter-spacing:.4px;"><?= htmlspecialchars($s['role_required']); ?></div>
                        </div>
                    </div>
                    <?php if ($i < count($steps) - 1): ?><i class="fas fa-chevron-right text-muted mx-1"></i><?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- Slice 8Z-l · Payment Schedule context (grouped by method — FM/Exec batch approval view) ─── -->
<?php $sc2 = $this->data['schedule_context'] ?? []; if (!empty($sc2['schedule'])):
    $sch = $sc2['schedule']; $grps = $sc2['groups'] ?? [];
    $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'],
    ];
    $collapseId = 'schBatch_' . (int)$sch['c0d'];
?>
    <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;">
                <i class="fas fa-money-check-alt me-1 text-muted"></i>Payment schedule <a href="<?= PROOT; ?>PaymentSchedules/view/<?= (int)$sch['c0d']; ?>" style="color:#7A8BA1;"><?= htmlspecialchars($sch['schedule_no']); ?></a>
                <span class="text-muted ms-2" style="font-weight:400;font-size:.65rem;">
                    <?= htmlspecialchars($sch['currency']); ?> <?= number_format((float)$sch['total_amount']); ?> · <?= (int)$sch['item_count']; ?> LPO<?= (int)$sch['item_count'] === 1 ? '' : 's' ?>
                    <?php if (!empty($sch['scheduled_date'])): ?> · scheduled <?= htmlspecialchars(date('d M Y', strtotime($sch['scheduled_date']))); ?><?php endif; ?>
                </span>
            </div>
            <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#<?= $collapseId; ?>" aria-expanded="false" aria-controls="<?= $collapseId; ?>">
                <i class="fas fa-chevron-down me-1"></i>Show items
            </button>
        </div>
        <div class="card-body p-3">
            <?php if (!empty($sch['notes'])): ?>
                <div class="alert py-2 mb-3 small" style="background:#EEF2F6;border:1px solid #7A8BA1;color:#334155;font-size:.7rem;">
                    <i class="fas fa-comment-dots me-1"></i><?= nl2br(htmlspecialchars($sch['notes'])); ?>
                </div>
            <?php endif; ?>

            <?php // Slice 8Z-n · Source account + FM's balance snapshot (visible to Exec + all subsequent approvers)
            if (!empty($sch['source_account_id'])):
                if (!class_exists('CompanyBankAccounts')) require_once ROOT . '/app/models/CompanyBankAccounts.php';
                $srcAcct = (new CompanyBankAccounts())->byId((int)$sch['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:#EAF2E8;border:1px solid #3F5C43;color:#3F5C43;font-size:.72rem;">
                    <div><i class="fas fa-vault me-1"></i><strong>Funded from:</strong> <?= htmlspecialchars($srcAcct['account_name']); ?> · <?= htmlspecialchars($srcAcct['provider_name'] ?: '—'); ?> · <code style="color:#3F5C43;"><?= htmlspecialchars($srcMask); ?></code> · <?= htmlspecialchars($srcAcct['currency']); ?></div>
                    <?php if (!empty($sch['fm_balance_snapshot'])): ?>
                        <div class="text-muted small" style="color:#5B4F3C !important;font-size:.65rem;">
                            <strong>FM balance snapshot:</strong> <?= htmlspecialchars($srcAcct['currency']); ?> <?= number_format((float)$sch['fm_balance_snapshot']); ?>
                            <?php if (!empty($sch['fm_balance_snapshot_at'])): ?><span class="text-muted"> · at <?= htmlspecialchars(date('d M · H:i', strtotime($sch['fm_balance_snapshot_at']))); ?></span><?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php   endif;
            endif; ?>

            <!-- Method breakdown (always visible — the "at a glance" view) -->
            <div class="d-flex align-items-center gap-3 flex-wrap mb-2">
                <div class="small text-muted" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Breakdown:</div>
                <?php foreach ($grps 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 class="ms-auto small text-muted"><em>Created by <?= htmlspecialchars($sch['created_by_name']); ?></em></div>
            </div>

            <!-- Collapsible item detail -->
            <div class="collapse mt-2" id="<?= $collapseId; ?>">
                <?php foreach ($grps as $g):
                    $mc = $methodChip[$g['method']] ?? ['#F1F5F9','#334155',$g['method']];
                ?>
                    <div class="small mb-1" 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']; ?>)
                    </div>
                    <div class="table-responsive mb-3" style="border:1px solid #E2E8F0;border-radius:4px;">
                        <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>
                                </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></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']); ?></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>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
<?php endif; ?>

<!-- Slice 8Z-j Batch 4 · Cash-out context (LPO + Project + Team + linked Client PO) ─── -->
<?php $lc = $this->data['lpo_context'] ?? []; if (!empty($lc['lpo'])):
    $lpo = $lc['lpo']; $cpo = $lc['client_po'] ?? []; $pctOfPo = $lc['pct_of_po'] ?? null;
    $cpoItems     = $lc['client_po_items'] ?? [];
    $cpoOverheads = $lc['client_po_overheads'] ?? [];
    $lpoTypeLabels = [
        'PRODUCT_DISCOVERY' => 'Product Discovery',
        'PETTY_CASH'        => 'Petty Cash',
        'IMPREST'           => 'Imprest Draw',
        'CONTINGENCY'       => 'Contingency',
        'STAFF_ADVANCE'     => 'Staff Advance',
        'DISPOSAL_REFUND'   => 'Disposal Refund',
        'OPERATIONAL_FLOAT' => 'Operational Float',
        'WORKS_CONTINGENCY' => 'Works Contingency',
        'SUPPLIER'          => 'Supplier LPO',
    ];
    $lpoTypeLabel = $lpoTypeLabels[$lpo['lpo_type']] ?? $lpo['lpo_type'];
    $originChip = [
        'TENDER_BDM'    => ['#EEF2F6','#7A8BA1','BDM tender'],
        'TENDER_PUBLIC' => ['#FEF3E7','#8B6914','Public tender'],
        'DIRECT_AWARD'  => ['#EAF2E8','#3F5C43','Direct award'],
        'MIGRATED'      => ['#F5EAE1','#C48579','Migrated'],
    ];
    $originSel = $originChip[$lpo['origin']] ?? ['#F1F5F9','#334155',$lpo['origin']];
    $ovhCatChip = [
        'TRANSPORT'    => ['#EEF2F6','#7A8BA1','Transport'],
        'HSE'          => ['#FEF3E7','#8B6914','HSE'],
        'INSURANCE'    => ['#E8EEF3','#7A8BA1','Insurance'],
        'PACKAGING'    => ['#EEF2F6','#7A8BA1','Packaging'],
        'WAREHOUSING'  => ['#EEF2F6','#7A8BA1','Warehousing'],
        'INSTALLATION' => ['#EAF2E8','#3F5C43','Installation'],
        'OTHER'        => ['#F1F5F9','#334155','Other'],
    ];
    $collapseId = 'poDetails_' . (int)$lpo['c0d'];
?>
    <!-- ── Cash-out request summary ─────────────────────────────────── -->
    <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-hand-holding-usd me-1 text-muted"></i>Cash-out request
            <span class="text-muted ms-2" style="font-weight:400;font-size:.65rem;">Context for your decision</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:.65rem;font-weight:600;text-transform:capitalize;">LPO</div>
                    <div><a href="<?= PROOT; ?>Lpos/view/<?= (int)$lpo['c0d']; ?>" class="text-decoration-none" style="color:#7A8BA1;font-weight:600;"><?= htmlspecialchars($lpo['lpo_no']); ?></a></div>
                    <div class="text-muted small" style="font-size:.62rem;"><?= htmlspecialchars($lpoTypeLabel); ?></div>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small" style="font-size:.65rem;font-weight:600;text-transform:capitalize;">Amount</div>
                    <div style="font-weight:700;font-size:1.05rem;color:#334155;"><?= htmlspecialchars($lpo['currency']); ?> <?= number_format((float)$lpo['amount']); ?></div>
                    <?php if ($pctOfPo !== null): ?>
                        <div class="text-muted small" style="font-size:.62rem;"><?= number_format($pctOfPo, 2); ?>% of Client PO total</div>
                    <?php endif; ?>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small" style="font-size:.65rem;font-weight:600;text-transform:capitalize;">Requested by</div>
                    <div><?= htmlspecialchars($lpo['requested_by_name'] ?: '—'); ?></div>
                    <div class="text-muted small" style="font-size:.62rem;"><?= htmlspecialchars(date('d M Y', strtotime((string)$lpo['requested_on']))); ?></div>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small" style="font-size:.65rem;font-weight:600;text-transform:capitalize;">Purpose</div>
                    <div class="small" style="color:#334155;"><?= nl2br(htmlspecialchars((string)$lpo['purpose'])); ?></div>
                </div>
            </div>
        </div>
    </div>

    <!-- ── Project details + Assigned team (side-by-side) ───────────── -->
    <?php if (!empty($lpo['project_no'])): ?>
    <div class="row g-3 mb-3">
        <div class="col-md-6">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header py-2 small" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-weight:600;color:#334155;">
                    <i class="fas fa-project-diagram me-1 text-muted"></i>Project
                </div>
                <div class="card-body p-3">
                    <div class="row g-2">
                        <div class="col-6">
                            <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Project #</div>
                            <div><a href="<?= PROOT; ?>Projects/view/<?= (int)$lpo['project_id']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars($lpo['project_no']); ?></strong></a></div>
                        </div>
                        <div class="col-6">
                            <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Type</div>
                            <div style="text-transform:capitalize;"><?= htmlspecialchars($lpo['project_type']); ?></div>
                        </div>
                        <div class="col-12">
                            <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Name</div>
                            <div class="small"><?= htmlspecialchars($lpo['project_name']); ?></div>
                        </div>
                        <div class="col-6">
                            <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Customer</div>
                            <div class="small"><?= htmlspecialchars($lpo['project_customer']); ?></div>
                        </div>
                        <div class="col-6">
                            <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Contract value</div>
                            <div class="small" style="font-weight:600;color:#334155;"><?= htmlspecialchars($lpo['project_currency']); ?> <?= number_format((float)$lpo['contract_value']); ?></div>
                        </div>
                        <div class="col-6">
                            <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Origin</div>
                            <span class="badge" style="background:<?= $originSel[0]; ?>;color:<?= $originSel[1]; ?>;border:1px solid <?= $originSel[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($originSel[2]); ?></span>
                        </div>
                        <div class="col-6">
                            <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">CRM status</div>
                            <div class="small" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$lpo['crm_status']))); ?></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header py-2 small" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-weight:600;color:#334155;">
                    <i class="fas fa-users me-1 text-muted"></i>Assigned team
                </div>
                <div class="card-body p-3">
                    <?php
                        $team = [
                            ['role' => 'Project Manager',    'name' => $lpo['project_manager_name'], 'id' => (int)$lpo['project_manager_id'], 'icon' => 'fa-user-tie',       'color' => '#3F5C43'],
                            ['role' => 'Projects Coordinator','name' => $lpo['pc_name'],              'id' => (int)$lpo['pc_id'],              'icon' => 'fa-user-cog',       'color' => '#7A8BA1'],
                            ['role' => 'Procurement',        'name' => $lpo['procurement_name'],     'id' => (int)$lpo['procurement_id'],     'icon' => 'fa-truck',          'color' => '#8B6914'],
                            ['role' => 'Accountant',         'name' => $lpo['accountant_name'],      'id' => (int)$lpo['accountant_id'],      'icon' => 'fa-calculator',     'color' => '#5B4F3C'],
                            ['role' => 'Field Supervisor',   'name' => $lpo['fs_name'],              'id' => (int)$lpo['fs_id'],              'icon' => 'fa-hard-hat',       'color' => '#C48579'],
                        ];
                    ?>
                    <div class="row g-2">
                        <?php foreach ($team as $t): ?>
                            <div class="col-md-6">
                                <div class="d-flex align-items-start gap-2">
                                    <i class="fas <?= $t['icon']; ?> mt-1" style="color:<?= $t['color']; ?>;font-size:.85rem;width:16px;"></i>
                                    <div style="line-height:1.2;">
                                        <div class="text-muted" style="font-size:.6rem;text-transform:capitalize;font-weight:600;"><?= htmlspecialchars($t['role']); ?></div>
                                        <div class="small" style="color:#334155;"><?= $t['id'] > 0 ? htmlspecialchars($t['name'] ?: '—') : '<em class="text-muted">Unassigned</em>'; ?></div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- ── Source Client PO (collapsible: details + items + overheads) ── -->
    <?php if (!empty($cpo)): ?>
    <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;">
                <i class="fas fa-file-contract me-1 text-muted"></i>Source Client PO
                <span class="text-muted ms-2" style="font-weight:400;font-size:.65rem;">The PO this cash request funds</span>
            </div>
            <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#<?= $collapseId; ?>" aria-expanded="false" aria-controls="<?= $collapseId; ?>">
                <i class="fas fa-chevron-down me-1"></i>Show line items + overheads
            </button>
        </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:.65rem;font-weight:600;text-transform:capitalize;">PO #</div>
                    <div><strong style="color:#7A8BA1;"><?= htmlspecialchars($cpo['client_po_no']); ?></strong></div>
                    <?php if (!empty($cpo['customer_po_ref'])): ?>
                        <div class="text-muted small" style="font-size:.62rem;">Their ref: <?= htmlspecialchars($cpo['customer_po_ref']); ?></div>
                    <?php endif; ?>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small" style="font-size:.65rem;font-weight:600;text-transform:capitalize;">Customer</div>
                    <div><?= htmlspecialchars($cpo['customer_name']); ?></div>
                    <div class="text-muted small" style="font-size:.62rem;"><?= htmlspecialchars(date('d M Y', strtotime((string)$cpo['po_date']))); ?></div>
                </div>
                <div class="col-md-2">
                    <div class="text-muted small" style="font-size:.65rem;font-weight:600;text-transform:capitalize;">PO total</div>
                    <div style="font-weight:600;color:#334155;"><?= htmlspecialchars($cpo['currency']); ?> <?= number_format((float)$cpo['total']); ?></div>
                    <div class="text-muted small" style="font-size:.62rem;">incl. VAT @ <?= number_format((float)$cpo['vat_rate'], 2); ?>%</div>
                </div>
                <div class="col-md-2">
                    <div class="text-muted small" style="font-size:.65rem;font-weight:600;text-transform:capitalize;">Ceiling (COG)</div>
                    <div><?= htmlspecialchars($cpo['currency']); ?> <?= number_format((float)$cpo['subtotal_cog']); ?></div>
                    <div class="text-muted small" style="font-size:.62rem;">Planned spend</div>
                </div>
                <div class="col-md-2">
                    <div class="text-muted small" style="font-size:.65rem;font-weight:600;text-transform:capitalize;">Status</div>
                    <span class="badge" style="background:#EEF2F6;color:#7A8BA1;border:1px solid #7A8BA1;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars(strtolower($cpo['status'])); ?></span>
                    <div class="text-muted small" style="font-size:.62rem;"><?= (int)$cpo['item_count']; ?> item<?= (int)$cpo['item_count'] === 1 ? '' : 's'; ?></div>
                </div>
                <?php if (!empty($cpo['incoterm']) || !empty($cpo['delivery_deadline']) || !empty($cpo['primary_delivery_location'])): ?>
                    <div class="col-12">
                        <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Delivery</div>
                        <div class="small text-muted">
                            <?php if (!empty($cpo['incoterm'])): ?><strong><?= htmlspecialchars($cpo['incoterm']); ?></strong> · <?php endif; ?>
                            <?php if (!empty($cpo['delivery_deadline'])): ?>by <?= htmlspecialchars(date('d M Y', strtotime($cpo['delivery_deadline']))); ?> · <?php endif; ?>
                            <?php if (!empty($cpo['primary_delivery_location'])): ?><?= htmlspecialchars(mb_strimwidth($cpo['primary_delivery_location'], 0, 120, '…')); ?><?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Collapsible: line items + overheads -->
            <div class="collapse mt-3" id="<?= $collapseId; ?>">
                <!-- Line items -->
                <div class="small mb-1" style="font-weight:600;color:#334155;"><i class="fas fa-list me-1 text-muted"></i>Line items (<?= count($cpoItems); ?>)</div>
                <div class="table-responsive mb-3" style="border:1px solid #E2E8F0;border-radius:4px;">
                    <table class="table table-sm mb-0 align-middle">
                        <thead class="table-light">
                            <tr>
                                <th style="width:36px;">#</th>
                                <th>Description</th>
                                <th class="text-end" style="width:70px;">Qty</th>
                                <th style="width:60px;">Unit</th>
                                <th class="text-end" style="width:100px;">Sell</th>
                                <th class="text-end" style="width:100px;">Cog</th>
                                <th class="text-end" style="width:80px;">Margin</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($cpoItems as $it):
                                $ls   = (float)$it['line_total_sell'];
                                $lc2  = (float)$it['line_total_cog'];
                                $lmgn = $ls > 0 ? (($ls - $lc2) / $ls) * 100 : 0;
                            ?>
                                <tr>
                                    <td class="small text-muted"><?= (int)$it['item_no']; ?></td>
                                    <td class="small"><?= htmlspecialchars($it['description']); ?>
                                        <?php if (!empty($it['brand'])): ?><div class="text-muted" style="font-size:.6rem;"><i class="fas fa-tag me-1" style="color:#94A3B8;"></i><?= htmlspecialchars($it['brand']); ?></div><?php endif; ?>
                                    </td>
                                    <td class="text-end small"><?= number_format((float)$it['qty'], (fmod((float)$it['qty'],1)==0?0:2)); ?></td>
                                    <td class="text-muted small"><?= htmlspecialchars($it['unit']); ?></td>
                                    <td class="text-end small"><?= number_format((float)$it['unit_price_sell']); ?></td>
                                    <td class="text-end small text-muted"><?= number_format((float)$it['unit_price_cog']); ?></td>
                                    <td class="text-end small" style="font-weight:600;color:<?= $lmgn<20?'#C48579':($lmgn<25?'#8B6914':'#3F5C43'); ?>;"><?= number_format($lmgn, 1); ?>%</td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (empty($cpoItems)): ?>
                                <tr><td colspan="7" class="text-center text-muted py-3" style="font-size:.72rem;">No items on this PO.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Overheads -->
                <div class="small mb-1" style="font-weight:600;color:#334155;"><i class="fas fa-layer-group me-1 text-muted"></i>Overheads (<?= count($cpoOverheads); ?>)</div>
                <?php if (!empty($cpoOverheads)): ?>
                    <div class="table-responsive" style="border:1px solid #E2E8F0;border-radius:4px;">
                        <table class="table table-sm mb-0 align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th style="width:120px;">Category</th>
                                    <th>Label</th>
                                    <th class="text-end" style="width:130px;">Estimate</th>
                                    <th class="text-end" style="width:130px;">Actual</th>
                                    <th class="text-end" style="width:110px;">Δ</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                    $totEst = 0.0; $totAct = 0.0;
                                    foreach ($cpoOverheads as $o):
                                        $cat = $ovhCatChip[$o['category']] ?? ['#F1F5F9','#334155', $o['category']];
                                        $est = (float)$o['amount'];
                                        $act = $o['amount_actual'] === null ? null : (float)$o['amount_actual'];
                                        $delta = $act === null ? null : round($act - $est, 2);
                                        $totEst += $est; if ($act !== null) $totAct += $act;
                                ?>
                                    <tr>
                                        <td><span class="badge" style="background:<?= $cat[0]; ?>;color:<?= $cat[1]; ?>;border:1px solid <?= $cat[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($cat[2]); ?></span></td>
                                        <td class="small"><?= htmlspecialchars($o['label']); ?></td>
                                        <td class="text-end small" style="font-weight:600;color:#334155;"><?= number_format($est); ?></td>
                                        <td class="text-end small"><?= $act === null ? '<span class="text-muted">—</span>' : number_format($act); ?></td>
                                        <td class="text-end small">
                                            <?php if ($delta === null): ?>
                                                <span class="text-muted">—</span>
                                            <?php else: ?>
                                                <span style="color:<?= $delta > 0 ? '#C48579' : ($delta < 0 ? '#3F5C43' : '#334155'); ?>;font-weight:600;"><?= ($delta > 0 ? '+' : '') . number_format($delta); ?></span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                            <tfoot style="background:#F8FAFC;">
                                <tr>
                                    <td colspan="2" class="small text-muted" style="font-weight:600;">Total</td>
                                    <td class="text-end small" style="font-weight:600;color:#334155;"><?= htmlspecialchars($cpo['currency']); ?> <?= number_format($totEst); ?></td>
                                    <td class="text-end small" style="font-weight:600;color:#334155;"><?= htmlspecialchars($cpo['currency']); ?> <?= number_format($totAct); ?></td>
                                    <td class="text-end small">
                                        <?php $totDelta = $totAct - $totEst; ?>
                                        <span style="color:<?= $totDelta > 0 ? '#C48579' : ($totDelta < 0 ? '#3F5C43' : '#334155'); ?>;font-weight:600;"><?= ($totDelta > 0 ? '+' : '') . number_format($totDelta); ?></span>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                <?php else: ?>
                    <div class="text-muted small py-2" style="font-size:.7rem;">No overheads captured on this PO.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>
<?php endif; ?>

<!-- Entity summary (project-onboarding for now) -------------------------- -->
<?php if (!empty($entity)): ?>
    <div class="card border-0 shadow-sm mb-3">
        <div class="card-header bg-white"><strong>Project</strong></div>
        <div class="card-body p-3">
            <div class="row g-3">
                <div class="col-md-4"><div class="text-muted small">Project #</div><div><a href="<?= PROOT; ?>Projects/view/<?= (int)$entity['project_id']; ?>"><strong><?= htmlspecialchars($entity['project_no']); ?></strong></a></div></div>
                <div class="col-md-4"><div class="text-muted small">Name</div><div><?= htmlspecialchars($entity['project_name']); ?></div></div>
                <div class="col-md-4"><div class="text-muted small">Customer</div><div><?= htmlspecialchars($entity['project_customer']); ?></div></div>
                <div class="col-md-4"><div class="text-muted small">Type</div><div style="text-transform:capitalize;"><?= htmlspecialchars($entity['project_type']); ?></div></div>
                <div class="col-md-4"><div class="text-muted small">Origin</div><div style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$entity['origin']))); ?></div></div>
                <div class="col-md-4"><div class="text-muted small">Contract</div><div><strong><?= htmlspecialchars($entity['p_currency']); ?> <?= number_format((float)$entity['p_contract']); ?></strong></div></div>
            </div>
        </div>
    </div>
<?php endif; ?>

<!-- Staged assignments (from earlier steps) ----------------------------- -->
<?php if (!empty($staged['assignments'])): ?>
    <div class="card border-0 shadow-sm mb-3">
        <div class="card-header bg-white"><strong>Assignments so far</strong></div>
        <div class="card-body p-3">
            <div class="row g-2">
                <?php foreach ($staged['assignments'] as $slot => $u): ?>
                    <div class="col-md-4">
                        <div class="text-muted small" style="text-transform:capitalize;"><?= htmlspecialchars($slotLabel[$slot] ?? strtolower(str_replace('_',' ',$slot))); ?></div>
                        <div><strong><?= htmlspecialchars($u['user_name'] ?? ('User #' . (int)($u['user_id'] ?? 0))); ?></strong></div>
                        <div class="text-muted small">by <?= htmlspecialchars($u['assigned_by_name'] ?? ''); ?> · <?= htmlspecialchars($u['assigned_at'] ?? ''); ?></div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
<?php endif; ?>

<!-- Slice 8Z-k · Disburse plan chip (visible from Accountant Prepare onwards) ─── -->
<?php if (!empty($lc['lpo']) && !empty($lc['lpo']['disburse_method'])):
    $dm = (string)$lc['lpo']['disburse_method'];
    $dmChip = [
        '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'],
    ];
    $dmSel = $dmChip[$dm] ?? ['#F1F5F9','#334155',$dm];
?>
    <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-hand-holding-usd me-1 text-muted"></i>Disburse plan (set by Accountant)
        </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;">Method</div>
                    <span class="badge" style="background:<?= $dmSel[0]; ?>;color:<?= $dmSel[1]; ?>;border:1px solid <?= $dmSel[1]; ?>;font-size:.65rem;text-transform:capitalize;"><?= htmlspecialchars($dmSel[2]); ?></span>
                </div>
                <div class="col-md-4">
                    <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Destination</div>
                    <?php if (!empty($lc['lpo']['disburse_account_id'])):
                        // load account inline (small — one row)
                        if (!class_exists('PayeeAccounts')) require_once ROOT . '/app/models/PayeeAccounts.php';
                        $acct = (new PayeeAccounts())->byId((int)$lc['lpo']['disburse_account_id']);
                    ?>
                        <div class="small"><strong><?= htmlspecialchars($acct['provider_name'] ?? '—'); ?></strong> · <code><?= htmlspecialchars(PayeeAccounts::mask((string)($acct['account_number'] ?? ''))); ?></code></div>
                        <div class="text-muted" style="font-size:.62rem;"><?= htmlspecialchars($acct['account_holder_name'] ?? ''); ?><?php if (($acct['status'] ?? '') === 'PENDING'): ?> · <span style="color:#8B6914;">pending FM approval</span><?php endif; ?></div>
                    <?php else: ?>
                        <div class="text-muted small"><em>Physical / no account tied</em></div>
                    <?php endif; ?>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Scheduled date</div>
                    <div class="small"><?= !empty($lc['lpo']['scheduled_disburse_date']) ? htmlspecialchars(date('d M Y', strtotime((string)$lc['lpo']['scheduled_disburse_date']))) : '<span class="text-muted">—</span>'; ?></div>
                </div>
                <div class="col-md-2">
                    <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Override?</div>
                    <?php if (!empty($lc['lpo']['override_reason'])): ?>
                        <span class="badge" style="background:#F5EAE1;color:#C48579;border:1px solid #C48579;font-size:.62rem;">Yes</span>
                    <?php else: ?>
                        <span class="text-muted small">No</span>
                    <?php endif; ?>
                </div>
                <?php if (!empty($lc['lpo']['override_reason']) || !empty($lc['lpo']['accountant_prep_notes'])): ?>
                    <div class="col-12">
                        <?php if (!empty($lc['lpo']['override_reason'])): ?>
                            <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Override reason</div>
                            <div class="small mb-2" style="color:#334155;"><?= nl2br(htmlspecialchars((string)$lc['lpo']['override_reason'])); ?></div>
                        <?php endif; ?>
                        <?php if (!empty($lc['lpo']['accountant_prep_notes'])): ?>
                            <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Accountant prep notes</div>
                            <div class="small" style="color:#334155;"><?= nl2br(htmlspecialchars((string)$lc['lpo']['accountant_prep_notes'])); ?></div>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
<?php endif; ?>

<!-- Slice 8Z-k · Requester's stated preference (for Accountant + subsequent approvers) ─── -->
<?php if (!empty($lc['lpo']) && (!empty($lc['lpo']['preferred_method']) || !empty($lc['lpo']['preferred_account_id']))):
    $pm = (string)($lc['lpo']['preferred_method'] ?? '');
    $pmChip = [
        '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'],
    ];
    $pmSel = $pm !== '' ? ($pmChip[$pm] ?? ['#F1F5F9','#334155',$pm]) : null;
    $prefAcct = null;
    if (!empty($lc['lpo']['preferred_account_id'])) {
        if (!class_exists('PayeeAccounts')) require_once ROOT . '/app/models/PayeeAccounts.php';
        $prefAcct = (new PayeeAccounts())->byId((int)$lc['lpo']['preferred_account_id']);
    }
?>
    <div class="alert py-2 mb-3 small" style="background:#F8FAFC;border:1px dashed #7A8BA1;color:#334155;font-size:.7rem;">
        <i class="fas fa-user-tag me-1"></i><strong>Requester's preference:</strong>
        <?php if ($pmSel): ?><span class="badge ms-1" style="background:<?= $pmSel[0]; ?>;color:<?= $pmSel[1]; ?>;border:1px solid <?= $pmSel[1]; ?>;font-size:.6rem;text-transform:capitalize;"><?= htmlspecialchars($pmSel[2]); ?></span><?php endif; ?>
        <?php if ($prefAcct): ?>
            <span class="ms-1">&rarr; <strong><?= htmlspecialchars($prefAcct['provider_name']); ?></strong> · <code><?= htmlspecialchars(PayeeAccounts::mask((string)$prefAcct['account_number'])); ?></code> · <?= htmlspecialchars($prefAcct['account_holder_name']); ?>
                <?php if ($prefAcct['status'] === 'PENDING'): ?><span class="text-muted" style="font-size:.62rem;"> (pending FM approval — ad-hoc use requires reason)</span><?php endif; ?>
            </span>
        <?php elseif ($pm === ''): ?>
            <span class="text-muted">left to Accountant discretion</span>
        <?php endif; ?>
    </div>
<?php endif; ?>

<!-- Slice 8Z-n · Note from previous approver (surfaced above the action bar for the current approver) ─── -->
<?php $priorNote = $this->data['prior_note'] ?? []; if ($mayAct && !empty($priorNote)): ?>
    <div class="alert py-2 mb-3 small" style="background:#FEF3E7;border:1px solid #8B6914;color:#5B4F3C;font-size:.72rem;">
        <div class="d-flex align-items-start gap-2">
            <i class="fas fa-quote-left mt-1" style="color:#8B6914;"></i>
            <div style="flex:1;">
                <div style="font-weight:600;font-size:.65rem;text-transform:capitalize;">Note from previous approver · <?= htmlspecialchars($priorNote['from_step_label'] ?? '—'); ?></div>
                <div class="mt-1"><?= nl2br(htmlspecialchars((string)$priorNote['comment'])); ?></div>
                <div class="text-muted mt-1" style="font-size:.6rem;color:#8B6914 !important;">
                    &mdash; <?= htmlspecialchars((string)($priorNote['actor_display'] ?? $priorNote['decided_by_name'] ?? '')); ?>
                    <?php if (!empty($priorNote['decided_by_group'])): ?> · <span style="text-transform:capitalize;"><?= htmlspecialchars(strtolower($priorNote['decided_by_group'])); ?></span><?php endif; ?>
                    · <?= htmlspecialchars(date('d M · H:i', strtotime((string)$priorNote['decided_on']))); ?>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

<!-- Slice 8Z-k · Accountant Prepare form (replaces generic action bar at this step) ─── -->
<?php $onAcctPrep = !empty($this->data['on_acct_prep']); $acctPrep = $this->data['accountant_prep'] ?? []; ?>
<?php if ($onAcctPrep && !empty($lc['lpo']) && !empty($acctPrep)):
    $prefMethod = (string)($lc['lpo']['preferred_method'] ?? '');
    $prefAcctId = (int)($lc['lpo']['preferred_account_id'] ?? 0);
    $lpoAmount = (float)$lc['lpo']['amount'];
?>
    <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-clipboard-check me-1 text-muted"></i>Prepare disbursement
            <span class="text-muted ms-2" style="font-weight:400;font-size:.65rem;">Confirm the disburse plan · advances the chain to FM on save</span>
        </div>
        <div class="card-body p-3">
            <form id="acct_prep_form" onsubmit="return false;">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label small" style="font-weight:600;color:#334155;">Method *</label>
                        <select name="disburse_method" id="ap_method" class="form-select form-select-sm">
                            <?php foreach (['MOBILE_MONEY'=>'Mobile money','BANK_TRANSFER'=>'Bank transfer','PETTY_CASH'=>'Petty cash','CASH_HANDOVER'=>'Cash handover (last resort)','CHEQUE'=>'Cheque'] as $k => $lbl): ?>
                                <option value="<?= $k; ?>" <?= $prefMethod === $k ? 'selected' : ''; ?>><?= htmlspecialchars($lbl); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <div class="text-muted mt-1" style="font-size:.62rem;">
                            Guidance: petty cash ≤ <?= number_format((float)$acctPrep['petty_max']); ?> · mobile money ≤ <?= number_format((float)$acctPrep['mobile_max']); ?> · above → bank
                        </div>
                    </div>
                    <div class="col-md-5">
                        <label class="form-label small" style="font-weight:600;color:#334155;">Destination account</label>
                        <select name="disburse_account_id" id="ap_account" class="form-select form-select-sm">
                            <option value="">— none (petty cash / handover) —</option>
                            <?php foreach ($acctPrep['accounts'] as $a2):
                                if ($a2['status'] === 'DISABLED') continue;
                                $mask = strlen((string)$a2['account_number']) <= 4 ? $a2['account_number'] : str_repeat('•', max(3, strlen($a2['account_number']) - 4)) . substr($a2['account_number'], -4);
                                $lbl = $a2['method'] . ' · ' . ($a2['provider_name'] ?: '—') . ' · ' . $mask . ' · ' . $a2['account_holder_name'] . ($a2['status'] === 'PENDING' ? '  [pending FM]' : '');
                            ?>
                                <option value="<?= (int)$a2['c0d']; ?>" data-method="<?= htmlspecialchars($a2['method']); ?>" data-status="<?= htmlspecialchars($a2['status']); ?>" <?= $prefAcctId === (int)$a2['c0d'] ? 'selected' : ''; ?>><?= htmlspecialchars($lbl); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label small" style="font-weight:600;color:#334155;">Scheduled date</label>
                        <input type="date" name="scheduled_disburse_date" class="form-control form-control-sm" value="<?= htmlspecialchars(date('Y-m-d', strtotime('+1 day'))); ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small" style="font-weight:600;color:#334155;">Override reason <span class="text-muted" style="font-weight:400;">(required if changing requester's preference or ad-hoc pending account)</span></label>
                        <textarea name="override_reason" id="ap_override" rows="2" class="form-control form-control-sm" placeholder="Why the change? (Audit trail)"></textarea>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small" style="font-weight:600;color:#334155;">Prep notes <span class="text-muted" style="font-weight:400;">(optional)</span></label>
                        <textarea name="accountant_prep_notes" rows="2" class="form-control form-control-sm" placeholder="Anything FM / Exec should know before approving"></textarea>
                    </div>
                </div>
                <div class="mb-2 mt-3"><label class="form-label small">Comment (required for Send back / Decline)</label>
                    <textarea id="rsCmt" class="form-control form-control-sm" rows="2" placeholder="Optional for Approve · required for Send back / Decline"></textarea>
                </div>
                <div class="text-end mt-3">
                    <button type="button" class="btn btn-sm btn-outline-danger me-1" onclick="rsDecide('declineAj')"><i class="fas fa-times-circle me-1"></i> Decline</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary me-1" onclick="rsDecide('sendBackAj')"><i class="fas fa-undo me-1"></i> Send back</button>
                    <button type="button" id="btn_acct_prep" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
                        <i class="fas fa-check me-1"></i>Save prep + advance to FM
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
    (function () {
        var APPROVAL_ID = <?= (int)$a['c0d']; ?>;
        var PREF_METHOD = <?= json_encode($prefMethod); ?>;
        var PREF_ACCT   = <?= (int)$prefAcctId; ?>;

        document.getElementById('btn_acct_prep').addEventListener('click', function () {
            var f = document.getElementById('acct_prep_form');
            var payload = {
                approval_id:             APPROVAL_ID,
                disburse_method:         f.disburse_method.value,
                disburse_account_id:     f.disburse_account_id.value,
                scheduled_disburse_date: f.scheduled_disburse_date.value,
                accountant_prep_notes:   f.accountant_prep_notes.value,
                override_reason:         f.override_reason.value
            };

            // Client-side hint: warn if overriding the requester's method/account without a reason
            var overridingMethod = PREF_METHOD && payload.disburse_method !== PREF_METHOD;
            var overridingAcct   = PREF_ACCT > 0 && payload.disburse_account_id && parseInt(payload.disburse_account_id) !== PREF_ACCT;
            if ((overridingMethod || overridingAcct) && !payload.override_reason.trim()) {
                $.alert({title:'Override reason required', content:'You are changing the requester\'s preferred method or destination. Fill "Override reason" (audit trail).', type:'orange'});
                return;
            }

            // Warn if picking a PENDING account
            var sel = document.getElementById('ap_account');
            var opt = sel.options[sel.selectedIndex];
            if (opt && opt.dataset.status === 'PENDING' && !payload.override_reason.trim()) {
                $.alert({title:'Ad-hoc account use', content:'This account is PENDING FM approval. Ad-hoc use requires a reason for the audit trail.', type:'orange'});
                return;
            }

            $.confirm({
                title: 'Save prep and advance to FM?',
                content: '<div class="small">Saves the disburse plan on the LPO and hands the approval to Finance Manager next.</div>',
                type: 'green',
                buttons: {
                    yes: { text: 'Save + advance', btnClass: 'btn-success', action: function () {
                        $.post('<?= PROOT; ?>FinChains/accountantPrepAj', payload, function (r) {
                            if (r && r.ok) {
                                if (typeof rsToast === 'function') rsToast('Prepared · FM notified.', 'success');
                                setTimeout(function () { location.reload(); }, 500);
                            } else {
                                $.alert({title:'Could not save', content:(r && r.msg) || 'Server error', type:'red'});
                            }
                        }, 'json').fail(function () { $.alert({title:'Network error', type:'red'}); });
                    }},
                    cancel: function () {}
                }
            });
        });
    })();
    </script>
<?php elseif ($mayAct && $a['entity_type'] === 'payment_schedule' && ($a['current_step_key'] ?? '') === 'FM_APPROVE' && !empty($sc2['proposal_groups'])):
    // Slice 8Z-m · FM proposal-review form (source account + per-line edit + FIFO cap + exclude)
    $proposalGroups = $sc2['proposal_groups'];
    $sourceAccounts = $sc2['source_accounts'] ?? [];
    $sch2 = $sc2['schedule'];
    $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="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-hand-holding-usd me-1 text-muted"></i>Fund + review + approve
            <span class="text-muted ms-2" style="font-weight:400;font-size:.65rem;">Pick source account · adjust amounts if needed · Approve to advance to Exec</span>
        </div>
        <div class="card-body p-3">
            <!-- Source account picker (required) + FM balance snapshot (optional, advisory) -->
            <div class="row g-3 mb-3">
                <div class="col-md-8">
                    <label class="form-label small" style="font-weight:600;color:#334155;">Source account <span class="text-danger">*</span> <span class="text-muted" style="font-weight:400;font-size:.62rem;">Where the money leaves from (currency filtered to <?= htmlspecialchars($sch2['currency']); ?>)</span></label>
                    <select id="ps_source_account" class="form-select form-select-sm">
                        <option value="">— pick a source account —</option>
                        <?php foreach ($sourceAccounts as $sa):
                            $mask = strlen((string)$sa['account_number']) > 4
                                    ? str_repeat('•', max(3, strlen($sa['account_number']) - 4)) . substr($sa['account_number'], -4)
                                    : $sa['account_number'];
                        ?>
                            <option value="<?= (int)$sa['c0d']; ?>" <?= (int)($sch2['source_account_id'] ?? 0) === (int)$sa['c0d'] ? 'selected' : ''; ?>>
                                <?= htmlspecialchars($sa['account_name']); ?> · <?= htmlspecialchars($sa['provider_name'] ?: '—'); ?> · <?= htmlspecialchars($mask); ?>
                                <?php if ($sa['balance_hint'] !== null): ?> · hint <?= htmlspecialchars($sa['currency']); ?> <?= number_format((float)$sa['balance_hint']); ?><?php endif; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (empty($sourceAccounts)): ?>
                        <div class="text-muted small mt-1" style="font-size:.62rem;color:#C48579;">
                            No active <?= htmlspecialchars($sch2['currency']); ?> source accounts. Add one in <a href="<?= PROOT; ?>CompanyBankAccounts" style="color:#7A9E7E;">Company Bank Accounts</a> before approving.
                        </div>
                    <?php endif; ?>
                </div>
                <div class="col-md-4">
                    <label class="form-label small" style="font-weight:600;color:#334155;">Balance at approval <span class="text-muted" style="font-weight:400;font-size:.62rem;">(<?= htmlspecialchars($sch2['currency']); ?> · advisory)</span></label>
                    <input type="number" step="0.01" min="0" id="ps_balance_snapshot" class="form-control form-control-sm" placeholder="e.g. 12000000" value="<?= htmlspecialchars((string)($sch2['fm_balance_snapshot'] ?? '')); ?>">
                    <div class="text-muted mt-1" style="font-size:.6rem;">What you saw on the bank portal. Recorded for the audit trail; not enforced.</div>
                </div>
            </div>

            <!-- Groups: per-line editable amounts + FIFO cap + exclude -->
            <?php foreach ($proposalGroups as $g):
                $mc = $methodChip[$g['method']] ?? ['#F1F5F9','#334155',$g['method']];
                $groupKey = $g['payee_type'] . ':' . $g['payee_id'] . ':' . $g['method'];
            ?>
                <div class="card border mb-3" style="border-color:#E2E8F0;" data-group-key="<?= htmlspecialchars($groupKey); ?>">
                    <div class="card-header py-2 d-flex align-items-center justify-content-between" style="background:#F8FAFC;">
                        <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>
                            <?= htmlspecialchars($g['payee_name']); ?> · <?= (int)$g['count']; ?> LPO<?= (int)$g['count'] === 1 ? '' : 's' ?>
                            <span class="text-muted ms-2 grp-total" style="font-weight:400;font-size:.65rem;"><?= htmlspecialchars($sch2['currency']); ?> <?= number_format((float)$g['total']); ?></span>
                        </div>
                        <div class="d-flex align-items-center gap-2">
                            <div class="input-group input-group-sm" style="max-width:210px;">
                                <span class="input-group-text" style="font-size:.62rem;">Group cap</span>
                                <input type="number" step="0.01" min="0" class="form-control form-control-sm grp-cap-input" placeholder="e.g. 4000000">
                                <button type="button" class="btn btn-sm btn-outline-secondary btn_apply_cap"
                                        data-payee-type="<?= htmlspecialchars($g['payee_type']); ?>"
                                        data-payee-id="<?= (int)$g['payee_id']; ?>"
                                        data-method="<?= htmlspecialchars($g['method']); ?>"
                                        title="FIFO allocate: fill oldest LPOs first up to the cap, exclude the rest.">
                                    Apply
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-sm mb-0 align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th style="width:110px;">LPO</th>
                                    <th style="width:80px;">Age</th>
                                    <th>Purpose</th>
                                    <th class="text-end" style="width:120px;">LPO total</th>
                                    <th class="text-end" style="width:120px;">Remaining</th>
                                    <th class="text-end" style="width:140px;">Pay this run</th>
                                    <th style="width:70px;" class="text-end">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($g['items'] as $it):
                                    $age = !empty($it['lpo_created_on']) ? floor((time() - strtotime($it['lpo_created_on'])) / 86400) : 0;
                                ?>
                                    <tr data-lpo-id="<?= (int)$it['lpo_id']; ?>" data-item-current="<?= (float)$it['amount']; ?>" data-lpo-remaining="<?= (float)$it['lpo_remaining']; ?>">
                                        <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></td>
                                        <td class="small text-muted" style="font-size:.62rem;"><?= (int)$age; ?>d</td>
                                        <td class="small text-muted" style="max-width:280px;color:#64748B;"><?= htmlspecialchars(mb_strimwidth((string)$it['purpose'], 0, 80, '…')); ?></td>
                                        <td class="text-end small"><?= number_format((float)$it['lpo_total']); ?></td>
                                        <td class="text-end small"><?= number_format((float)$it['lpo_remaining']); ?></td>
                                        <td class="text-end">
                                            <input type="number" step="0.01" min="0" class="form-control form-control-sm text-end line-amt-input" value="<?= (float)$it['amount']; ?>" style="max-width:130px;display:inline-block;">
                                        </td>
                                        <td class="text-end">
                                            <button type="button" class="btn btn-sm btn-link p-0 me-2 btn_save_line" title="Save amount"><i class="fas fa-save" style="color:#7A9E7E;"></i></button>
                                            <button type="button" class="btn btn-sm btn-link p-0 text-danger btn_exclude" title="Exclude from schedule"><i class="fas fa-times"></i></button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endforeach; ?>

            <div class="alert py-2 mb-3 small" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#64748B;font-size:.65rem;">
                <i class="fas fa-info-circle me-1"></i>
                Any amount you don't touch = full pay. Reducing an amount partial-pays; the LPO stays BOOKED with the remainder available for the next schedule. Excluding removes the LPO from this batch.
            </div>

            <div class="mb-2">
                <label class="form-label small">Comment</label>
                <textarea id="rsCmt" class="form-control form-control-sm" rows="2" placeholder="Optional for Approve · required for Send back / Decline"></textarea>
            </div>
            <div class="text-end mt-3">
                <button type="button" class="btn btn-sm btn-outline-danger me-1" onclick="rsDecide('declineAj')"><i class="fas fa-times-circle me-1"></i> Decline</button>
                <button type="button" class="btn btn-sm btn-outline-secondary me-1" onclick="rsDecide('sendBackAj')"><i class="fas fa-undo me-1"></i> Send back</button>
                <button type="button" id="btn_ps_approve" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
                    <i class="fas fa-check me-1"></i>Fund + Approve
                </button>
            </div>
        </div>
    </div>

    <script>
    (function () {
        var APPROVAL_ID = <?= (int)$a['c0d']; ?>;
        var SCHEDULE_ID = <?= (int)$sch2['c0d']; ?>;

        function askComment(title, callback) {
            $.confirm({
                title: title,
                content: '<label class="form-label small">Reason (audit trail) <span class="text-danger">*</span></label>' +
                         '<textarea id="ln_comment" class="form-control form-control-sm" rows="2" placeholder="Why?"></textarea>',
                type: 'orange',
                buttons: {
                    yes: { text: 'Save', btnClass: 'btn-warning', action: function () {
                        var c = (document.getElementById('ln_comment').value || '').trim();
                        if (!c) { $.alert({title:'Reason required', type:'orange'}); return false; }
                        callback(c);
                    }},
                    cancel: function () {}
                }
            });
        }

        // Save an individual line amount
        document.querySelectorAll('.btn_save_line').forEach(function (btn) {
            btn.addEventListener('click', function () {
                var tr = this.closest('tr');
                var lid = tr.dataset.lpoId;
                var input = tr.querySelector('.line-amt-input');
                var newAmt = parseFloat(input.value || 0);
                var currentAmt = parseFloat(tr.dataset.itemCurrent);
                if (newAmt <= 0)                    { $.alert({title:'Amount must be > 0', content:'Use the × button to exclude instead.', type:'orange'}); return; }
                if (newAmt > parseFloat(tr.dataset.lpoRemaining) + 0.01) { $.alert({title:'Exceeds LPO remaining', type:'red'}); return; }
                var reduced = newAmt < currentAmt - 0.005;
                function post(comment) {
                    $.post('<?= PROOT; ?>PaymentSchedules/updateItemAmountAj', {
                        schedule_id: SCHEDULE_ID, lpo_id: lid, amount: newAmt, comment: comment || ''
                    }, function (r) {
                        if (r && r.ok) { rsToast('Saved.', 'success'); setTimeout(function(){location.reload();}, 400); }
                        else $.alert({title:'Could not save', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }
                if (reduced) askComment('Reduce this payment?', post);
                else post('');
            });
        });

        // Exclude line
        document.querySelectorAll('.btn_exclude').forEach(function (btn) {
            btn.addEventListener('click', function () {
                var tr = this.closest('tr');
                var lid = tr.dataset.lpoId;
                askComment('Exclude LPO from schedule?', function (comment) {
                    $.post('<?= PROOT; ?>PaymentSchedules/excludeItemAj', {
                        schedule_id: SCHEDULE_ID, lpo_id: lid, comment: comment
                    }, function (r) {
                        if (r && r.ok) { rsToast('Excluded.', 'success'); setTimeout(function(){location.reload();}, 400); }
                        else $.alert({title:'Could not exclude', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                });
            });
        });

        // Apply group cap (FIFO)
        document.querySelectorAll('.btn_apply_cap').forEach(function (btn) {
            btn.addEventListener('click', function () {
                var card = this.closest('.card');
                var capInput = card.querySelector('.grp-cap-input');
                var cap = parseFloat(capInput.value || 0);
                if (!(cap > 0)) { $.alert({title:'Enter a cap amount > 0', type:'orange'}); return; }
                var self = this;
                askComment('Apply group cap (FIFO)?', function (comment) {
                    $.post('<?= PROOT; ?>PaymentSchedules/applyGroupCapAj', {
                        schedule_id: SCHEDULE_ID,
                        payee_type: self.dataset.payeeType, payee_id: self.dataset.payeeId,
                        method: self.dataset.method, cap: cap, comment: comment
                    }, function (r) {
                        if (r && r.ok) { rsToast('Cap applied.', 'success'); setTimeout(function(){location.reload();}, 500); }
                        else $.alert({title:'Could not apply cap', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                });
            });
        });

        // Fund + Approve
        document.getElementById('btn_ps_approve').addEventListener('click', function () {
            var src = document.getElementById('ps_source_account').value;
            if (!src) { $.alert({title:'Source account required', content:'Pick which company account funds this schedule.', type:'orange'}); return; }
            var cmt = document.getElementById('rsCmt').value || '';
            $.confirm({
                title: 'Fund + approve schedule?',
                content: 'This locks in the source account and hands the schedule to Exec for final authorisation.',
                type: 'green',
                buttons: {
                    yes: { text: 'Approve', btnClass: 'btn-success', action: function () {
                        var snap = document.getElementById('ps_balance_snapshot').value || '';
                        $.post('<?= PROOT; ?>FinChains/paymentScheduleApproveAj', {
                            approval_id: APPROVAL_ID, source_account_id: src, comment: cmt, fm_balance_snapshot: snap
                        }, function (r) {
                            if (r && r.ok) { rsToast('Approved · Exec notified.', 'success'); setTimeout(function(){location.reload();}, 500); }
                            else $.alert({title:'Could not approve', content:(r && r.msg) || 'Server error', type:'red'});
                        }, 'json').fail(function () { $.alert({title:'Network error', type:'red'}); });
                    }},
                    cancel: function () {}
                }
            });
        });
    })();
    </script>
<?php elseif ($mayAct): ?>
    <div class="card border-0 shadow-sm mb-3">
        <div class="card-body p-3">
            <?php if (!empty($reqSlots)): ?>
                <div class="alert alert-warning py-2 small mb-3">
                    <i class="fas fa-user-tag me-1"></i>
                    This step requires you to nominate <?= count($reqSlots); ?> user<?= count($reqSlots) === 1 ? '' : 's' ?> before approving.
                </div>
                <div class="row g-3 mb-3">
                    <?php foreach ($reqSlots as $slot):
                        $users = $slotOpts[$slot] ?? [];
                    ?>
                        <div class="col-md-6">
                            <label class="form-label" style="text-transform:capitalize;">
                                <?= htmlspecialchars($slotLabel[$slot] ?? strtolower(str_replace('_',' ',$slot))); ?>
                                <span class="text-danger">*</span>
                            </label>
                            <select class="form-select rs-slot-select" data-slot="<?= htmlspecialchars($slot); ?>">
                                <option value="">— Pick a user —</option>
                                <?php foreach ($users as $u): ?>
                                    <option value="<?= (int)$u['c0d']; ?>" data-name="<?= htmlspecialchars($u['full_name']); ?>">
                                        <?= htmlspecialchars($u['full_name']); ?> (<?= htmlspecialchars($u['user_group_name']); ?>)
                                    </option>
                                <?php endforeach; ?>
                                <?php if (empty($users)): ?><option value="" disabled>No active user in this role</option><?php endif; ?>
                            </select>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <div class="mb-2"><label class="form-label">Comment (required for Send back / Decline)</label>
                <textarea id="rsCmt" class="form-control" rows="2" placeholder="Optional for Approve · required for Send back / Decline"></textarea>
            </div>
            <div class="text-end">
                <button type="button" class="btn btn-sm btn-outline-danger me-1"    onclick="rsDecide('declineAj')"><i class="fas fa-times-circle me-1"></i> Decline</button>
                <?php if (UserGroups::can('FinChains','returnToOriginatorAj')): ?>
                    <button type="button" class="btn btn-sm btn-outline-warning me-1" onclick="rsDecide('returnToOriginatorAj')" title="Cancel this approval and hand it back to the submitter (they can edit and resubmit)."><i class="fas fa-user-edit me-1"></i> Return to submitter</button>
                <?php endif; ?>
                <?php if ($curNo > 1): ?>
                    <button type="button" class="btn btn-sm btn-outline-secondary me-1" onclick="rsDecide('sendBackAj')"><i class="fas fa-undo me-1"></i> Send back</button>
                <?php endif; ?>
                <button type="button" class="btn btn-sm btn-primary" style="background:<?= BRAND_COLOR; ?>;border-color:<?= BRAND_COLOR; ?>;" onclick="rsDecide('approveAj')">
                    <i class="fas fa-check me-1"></i> Approve
                </button>
            </div>
        </div>
    </div>
<?php elseif ($a['status'] === 'IN_PROGRESS'): ?>
    <div class="alert alert-secondary py-2 small">You are not the current-step role (<code><?= htmlspecialchars($a['current_step_role'] ?? ''); ?></code>) — you can view but not act.</div>
<?php endif; ?>

<!-- History -------------------------------------------------------------- -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white"><strong>History</strong></div>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr><th>When</th><th>Decision</th><th>From</th><th>To</th><th>Actor</th><th>Comment</th></tr>
            </thead>
            <tbody>
                <?php foreach ($hist as $h):
                    $decClass = ['SUBMIT'=>'bg-info text-white','APPROVE'=>'bg-success','SEND_BACK'=>'bg-warning text-dark','DECLINE'=>'bg-danger','CANCEL'=>'bg-secondary'][$h['decision']] ?? 'bg-light text-muted';
                ?>
                    <tr>
                        <td class="text-muted small"><?= htmlspecialchars($h['decided_on']); ?></td>
                        <td><span class="badge <?= $decClass; ?>" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$h['decision']))); ?></span></td>
                        <td class="text-muted small"><?= htmlspecialchars($h['from_step_label'] ?? '—'); ?></td>
                        <td class="text-muted small"><?= htmlspecialchars($h['to_step_label'] ?? '—'); ?></td>
                        <td><?= htmlspecialchars($h['actor_display'] ?? ''); ?> <span class="text-muted small">(<?= htmlspecialchars($h['decided_by_group']); ?>)</span></td>
                        <td class="text-muted"><?= htmlspecialchars($h['comment']); ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($hist)): ?><tr><td colspan="6" class="text-center text-muted py-3">No history yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
function rsDecide(action) {
    const cmt = document.getElementById('rsCmt').value.trim();
    if ((action === 'sendBackAj' || action === 'declineAj' || action === 'returnToOriginatorAj') && !cmt) {
        $.alert({title: 'Comment required', content: 'Please enter a comment before ' + action.replace('Aj','') + '.', type: 'orange'});
        return;
    }

    // Collect slot assignments (only meaningful for approveAj; server ignores otherwise)
    const parts = ['approval_id=<?= (int)$a['c0d']; ?>', 'comment=' + encodeURIComponent(cmt)];
    if (action === 'approveAj') {
        const selects = document.querySelectorAll('.rs-slot-select');
        for (const sel of selects) {
            const slot = sel.getAttribute('data-slot');
            const uid  = sel.value;
            if (!uid) { $.alert({title: 'Pick a user', content: 'Nominate a user for ' + slot.toLowerCase().replace('_',' ') + ' before approving.', type: 'orange'}); return; }
            const uname = sel.options[sel.selectedIndex].getAttribute('data-name') || '';
            parts.push('assignments[' + encodeURIComponent(slot) + '][user_id]='   + encodeURIComponent(uid));
            parts.push('assignments[' + encodeURIComponent(slot) + '][user_name]=' + encodeURIComponent(uname));
        }
    }

    const verbMap = {
        approveAj:              { verb: 'approve',    type: 'green',  btn: 'btn-success', label: 'Approve' },
        sendBackAj:             { verb: 'send back',  type: 'orange', btn: 'btn-warning', label: 'Send back' },
        declineAj:              { verb: 'decline',    type: 'red',    btn: 'btn-danger',  label: 'Decline' },
        returnToOriginatorAj:   { verb: 'return to the submitter (they will need to edit and resubmit)', type: 'orange', btn: 'btn-warning', label: 'Return' }
    };
    const cfg = verbMap[action] || { verb: action, type: 'blue', btn: 'btn-primary', label: 'Confirm' };

    $.confirm({
        title: 'Confirm decision',
        content: 'Are you sure you want to ' + cfg.verb + ' this?',
        type: cfg.type,
        buttons: {
            yes: { text: cfg.label, btnClass: cfg.btn, action: function () {
                fetch('<?= PROOT; ?>FinChains/' + action, {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: parts.join('&')
                }).then(r => r.json()).then(j => {
                    if (j.ok) {
                        if (typeof rsToast === 'function') rsToast(j.msg || 'Done.', 'success');
                        setTimeout(function () { location.reload(); }, 400);
                    } else {
                        $.alert({title: 'Failed', content: j.msg || 'Server error', type: 'red'});
                    }
                }).catch(() => $.alert({title: 'Network error', content: 'Try again.', type: 'red'}));
            }},
            cancel: function () {}
        }
    });
}
</script>

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