<?php $this->start('body');
    $req        = $this->data['req'];
    $prj        = $this->data['project']    ?? [];
    $lines      = $this->data['lines']      ?? [];
    $byCat      = $this->data['by_category']?? [];
    $categories = $this->data['categories'] ?? [];
    $approval   = $this->data['approval']   ?? [];
    $history    = $this->data['history']    ?? [];
    $steps      = $this->data['steps']      ?? [];
    $canEdit    = !empty($this->data['can_edit']);
    $canSubmit  = !empty($this->data['can_submit']);
    $canCancel  = !empty($this->data['can_cancel']);
    $canIssue   = !empty($this->data['can_issue']);
    $canStartRet     = !empty($this->data['can_start_retirement']);
    $canEditExp      = !empty($this->data['can_edit_expenses']);
    $canSubmitRet    = !empty($this->data['can_submit_retirement']);
    $canApproveRet   = !empty($this->data['can_approve_retire']);
    $canClose        = !empty($this->data['can_close']);
    $expenses        = $this->data['expenses'] ?? [];
    $expByCat        = $this->data['expense_by_category'] ?? [];
    $banks           = $this->data['banks'] ?? [];
    $je              = $this->data['je']    ?? null;

    $statusPill = [
        'DRAFT'     => ['#f59e0b', 'Draft'],
        'SUBMITTED' => ['#0ea5e9', 'Submitted'],
        'APPROVED'  => ['#22c55e', 'Approved · awaiting issue'],
        'ISSUED'    => ['#7A9E7E', 'Issued'],
        'RETIRING'  => ['#a78bfa', 'Retiring'],
        'RETIRED'   => ['#7A8BA1', 'Retired'],
        'CLOSED'    => ['#94a3b8', 'Closed'],
        'DECLINED'  => ['#dc2626', 'Declined'],
        'CANCELLED' => ['#94a3b8', 'Cancelled'],
    ];
    $sp = $statusPill[$req['status']] ?? ['#94a3b8', $req['status']];

    $catLabel = [
        'FUEL'=>'Fuel','TRANSPORT'=>'Transport','MEALS'=>'Meals',
        'ACCOMMODATION'=>'Accommodation','MATERIALS'=>'Materials','LABOUR'=>'Labour','MISC'=>'Misc',
    ];
    $catColor = [
        'FUEL'=>'#dc2626','TRANSPORT'=>'#f59e0b','MEALS'=>'#a78bfa',
        'ACCOMMODATION'=>'#7A9E7E','MATERIALS'=>'#0ea5e9','LABOUR'=>'#D4A574','MISC'=>'#94a3b8',
    ];
?>
<div class="d-flex align-items-center justify-content-between mb-3">
    <div>
        <h5 class="mb-0" style="font-weight:600;">
            <i class="fas fa-hand-holding-usd me-1 text-muted"></i>
            <code style="font-size:.85rem;color:#334155;background:#F1F5F9;padding:2px 6px;border-radius:3px;"><?= htmlspecialchars($req['req_no']); ?></code>
            · <?= htmlspecialchars($req['title']); ?>
            <span class="badge ms-2" style="background:<?= $sp[0]; ?>;color:#fff;"><?= htmlspecialchars($sp[1]); ?></span>
        </h5>
        <div class="text-muted" style="font-size:.72rem;">
            Project <?= htmlspecialchars($prj['project_no'] ?? '?'); ?> · <?= htmlspecialchars($prj['project_name'] ?? ''); ?>
            <?php if (!empty($req['context_ref'])): ?> · context: <?= htmlspecialchars($req['context_ref']); ?><?php endif; ?>
        </div>
    </div>
    <div class="d-flex gap-2">
        <a href="<?= PROOT; ?>ServiceRequisitions/create/<?= (int)$req['project_id']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-list me-1"></i> On this project</a>
        <a href="<?= PROOT; ?>ServiceRequisitions/myQueue" class="btn btn-sm btn-outline-secondary"><i class="fas fa-inbox me-1"></i> Queue</a>
    </div>
</div>

<!-- Purpose card -->
<?php if (!empty($req['purpose'])): ?>
<div class="alert py-2 mb-3" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#334155;font-size:.86rem;">
    <strong>Purpose:</strong> <?= htmlspecialchars($req['purpose']); ?>
</div>
<?php endif; ?>

<!-- Totals bar -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-body p-3 d-flex align-items-center justify-content-between">
        <div>
            <div style="text-transform:uppercase;letter-spacing:.4px;font-size:.66rem;color:#64748B;">Requested total</div>
            <div style="color:#334155;font-size:1.2rem;font-weight:700;"><?= htmlspecialchars($req['currency']); ?> <?= number_format((float)$req['total_amount']); ?></div>
        </div>
        <?php if ($req['status'] === 'ISSUED' || $req['status'] === 'RETIRING' || $req['status'] === 'RETIRED' || $req['status'] === 'CLOSED'): ?>
        <div>
            <div style="text-transform:uppercase;letter-spacing:.4px;font-size:.66rem;color:#64748B;">Issued</div>
            <div style="color:#166534;font-size:1.2rem;font-weight:700;"><?= htmlspecialchars($req['currency']); ?> <?= number_format((float)$req['issue_amount']); ?></div>
            <div class="text-muted small">ref <?= htmlspecialchars($req['issue_reference']); ?> · <?= htmlspecialchars($req['issued_on']); ?></div>
        </div>
        <?php endif; ?>
        <div>
            <div style="text-transform:uppercase;letter-spacing:.4px;font-size:.66rem;color:#64748B;">Requester</div>
            <div class="text-muted small"><?= htmlspecialchars($req['created_by_name']); ?></div>
            <div class="text-muted small"><?= htmlspecialchars($req['created_on']); ?></div>
        </div>
    </div>
</div>

<!-- Actions bar -->
<div class="d-flex gap-2 mb-3">
    <?php if ($canSubmit): ?>
        <button type="button" class="btn btn-sm btn-primary" onclick="srAct('submit')" style="background:#7A9E7E;border-color:#7A9E7E;">
            <i class="fas fa-paper-plane me-1"></i> Submit for approval
        </button>
    <?php endif; ?>
    <?php if ($canCancel): ?>
        <button type="button" class="btn btn-sm btn-outline-danger" onclick="srAct('cancel')"><i class="fas fa-times me-1"></i> Cancel</button>
    <?php endif; ?>
    <?php if ($canIssue): ?>
        <button type="button" class="btn btn-sm btn-success" onclick="srIssuePrompt()"><i class="fas fa-hand-holding-usd me-1"></i> Issue cash</button>
    <?php endif; ?>
    <?php if ($canStartRet): ?>
        <button type="button" class="btn btn-sm btn-primary" onclick="srStartRet()" style="background:#a78bfa;border-color:#a78bfa;">
            <i class="fas fa-receipt me-1"></i> Start retirement
        </button>
    <?php endif; ?>
    <?php if ($canSubmitRet): ?>
        <button type="button" class="btn btn-sm btn-primary" onclick="srSubmitRet()" style="background:#7A9E7E;border-color:#7A9E7E;">
            <i class="fas fa-paper-plane me-1"></i> Submit retirement
        </button>
    <?php endif; ?>
    <?php if ($canApproveRet): ?>
        <button type="button" class="btn btn-sm btn-success" onclick="srApproveRet()"><i class="fas fa-check me-1"></i> Approve retirement</button>
        <button type="button" class="btn btn-sm btn-outline-warning" onclick="srSendBackRet()"><i class="fas fa-undo me-1"></i> Send back</button>
    <?php endif; ?>
    <?php if ($canClose): ?>
        <button type="button" class="btn btn-sm btn-primary" onclick="srClosePrompt()" style="background:#334155;border-color:#334155;">
            <i class="fas fa-file-invoice-dollar me-1"></i> Close · post to GL
        </button>
    <?php endif; ?>
</div>

<?php if ($je): ?>
<!-- JE reference (visible once posted) -->
<div class="alert py-2 mb-3" style="background:#F8FAFC;border:1px solid #334155;color:#334155;font-size:.86rem;">
    <i class="fas fa-file-invoice-dollar me-1"></i>
    <strong>Posted to GL as <code style="background:#E2E8F0;padding:1px 6px;border-radius:3px;"><?= htmlspecialchars($je['je_no']); ?></code></strong>
    on <?= htmlspecialchars($je['entry_date']); ?> · Dr <?= number_format((float)$je['total_debit']); ?> / Cr <?= number_format((float)$je['total_credit']); ?>
    <?php if (!empty($req['closed_by_name'])): ?>· closed by <?= htmlspecialchars($req['closed_by_name']); ?><?php endif; ?>
    <?php if (!empty($req['closed_on'])): ?>· <?= htmlspecialchars($req['closed_on']); ?><?php endif; ?>
</div>
<?php endif; ?>

<!-- Retirement banner (status-driven context) -->
<?php if ($req['status'] === 'ISSUED'): ?>
    <div class="alert py-2 mb-3" style="background:#F0FDF4;border:1px solid #7A9E7E;color:#166534;font-size:.86rem;">
        <i class="fas fa-check-circle me-1"></i>
        Cash issued <strong><?= number_format((float)$req['issue_amount']); ?></strong> (ref <?= htmlspecialchars($req['issue_reference']); ?>) — spend on site, then click <strong>Start retirement</strong> to record actuals.
    </div>
<?php elseif ($req['status'] === 'RETIRING' && empty($req['retirement_submitted_on'])): ?>
    <div class="alert py-2 mb-3" style="background:#F5F3FF;border:1px solid #a78bfa;color:#5b21b6;font-size:.86rem;">
        <i class="fas fa-receipt me-1"></i>
        Retirement in progress · record every spend below · variance vs planned auto-computes. Submit when done.
    </div>
<?php elseif ($req['status'] === 'RETIRING' && !empty($req['retirement_submitted_on'])): ?>
    <div class="alert py-2 mb-3" style="background:#EFF6FF;border:1px solid #0ea5e9;color:#0c4a6e;font-size:.86rem;">
        <i class="fas fa-hourglass-half me-1"></i>
        Retirement submitted <?= htmlspecialchars($req['retirement_submitted_on']); ?> — awaiting Accountant review.
    </div>
<?php elseif ($req['status'] === 'RETIRED'): ?>
    <?php $var = (float)$req['variance_amount']; $varTag = $var > 0 ? 'Unspent returned' : ($var < 0 ? 'Overspend absorbed' : 'Exact'); ?>
    <div class="alert py-2 mb-3" style="background:#F8FAFC;border:1px solid #94a3b8;color:#334155;font-size:.86rem;">
        <i class="fas fa-flag-checkered me-1"></i>
        Retired <?= htmlspecialchars($req['retired_on']); ?> by <?= htmlspecialchars($req['retirement_approved_by_name']); ?>.
        Retired <strong><?= number_format((float)$req['retired_amount']); ?></strong> of <?= number_format((float)$req['issue_amount']); ?> issued ·
        variance <strong><?= number_format(abs($var)); ?></strong> (<?= $varTag; ?>).
        <?php if (!empty($req['retirement_notes'])): ?><div class="mt-1 small">Notes: <em><?= htmlspecialchars($req['retirement_notes']); ?></em></div><?php endif; ?>
    </div>
<?php endif; ?>

<!-- Expenses section (only when at/past retirement) -->
<?php if (in_array($req['status'], ['RETIRING','RETIRED'], true)): ?>

<?php if ($canEditExp): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Add expense</strong> <span class="text-muted small ms-2">Receipt reference optional but recommended</span></div>
    <div class="card-body p-3" style="background:#F8FAFC;">
        <div class="row g-2 align-items-end">
            <div class="col-md-2">
                <label class="form-label" style="font-size:.78rem;">Category</label>
                <select id="exp_cat" class="form-select form-select-sm">
                    <?php foreach ($categories as $c): ?>
                        <option value="<?= $c; ?>"><?= htmlspecialchars($catLabel[$c] ?? $c); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label" style="font-size:.78rem;">Description</label>
                <input id="exp_desc" class="form-control form-control-sm" placeholder="What was spent on">
            </div>
            <div class="col-md-2">
                <label class="form-label" style="font-size:.78rem;">Amount</label>
                <input id="exp_amt" type="number" step="0.01" min="0" class="form-control form-control-sm">
            </div>
            <div class="col-md-2">
                <label class="form-label" style="font-size:.78rem;">Receipt ref</label>
                <input id="exp_ref" class="form-control form-control-sm" placeholder="EFD / voucher no">
            </div>
            <div class="col-md-1">
                <label class="form-label" style="font-size:.78rem;">Date</label>
                <input id="exp_date" type="date" class="form-control form-control-sm">
            </div>
            <div class="col-md-1 text-end">
                <button type="button" class="btn btn-sm btn-primary" onclick="srAddExpense()"><i class="fas fa-plus"></i></button>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex justify-content-between">
        <strong>Expenses by category</strong>
        <span class="text-muted small">
            Planned <strong><?= number_format((float)$req['total_amount']); ?></strong> ·
            Issued <strong><?= number_format((float)$req['issue_amount']); ?></strong> ·
            Retired <strong style="color:#0ea5e9;"><?= number_format((float)$req['retired_amount']); ?></strong> ·
            Variance <strong style="color:<?= ((float)$req['variance_amount'] < 0) ? '#dc2626' : '#166534'; ?>;"><?= number_format((float)$req['variance_amount']); ?></strong>
        </span>
    </div>
    <div class="card-body p-0">
        <?php $anyExp = !empty($expenses); if (!$anyExp): ?>
            <div class="p-3 text-center text-muted small">No expenses recorded yet.</div>
        <?php else: ?>
            <table class="table table-sm mb-0 align-middle">
                <thead class="table-light">
                    <tr>
                        <th style="width:130px;">Category</th>
                        <th>Description</th>
                        <th style="width:110px;">Receipt</th>
                        <th style="width:110px;" class="text-end">Amount</th>
                        <?php if ($canEditExp): ?><th style="width:50px;" class="text-end"></th><?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($categories as $cat):
                        $bucket = $expByCat[$cat] ?? ['expenses'=>[], 'spent'=>0, 'planned'=>0, 'variance'=>0];
                        if (empty($bucket['expenses']) && (float)$bucket['planned'] <= 0) continue;
                        $col = $catColor[$cat] ?? '#94a3b8';
                    ?>
                        <?php $first = true; foreach ($bucket['expenses'] as $exp): ?>
                            <tr>
                                <td><?php if ($first): ?><span class="badge" style="background:<?= $col; ?>;color:#fff;"><?= htmlspecialchars($catLabel[$cat] ?? $cat); ?></span><?php endif; ?></td>
                                <td>
                                    <?= htmlspecialchars($exp['description']); ?>
                                    <?php if (!empty($exp['notes'])): ?><div class="text-muted small"><?= htmlspecialchars($exp['notes']); ?></div><?php endif; ?>
                                </td>
                                <td class="small">
                                    <?php if ($exp['receipt_ref']): ?>
                                        <code style="font-size:.7rem;"><?= htmlspecialchars($exp['receipt_ref']); ?></code>
                                        <?php if (!empty($exp['receipt_date'])): ?><div class="text-muted"><?= htmlspecialchars($exp['receipt_date']); ?></div><?php endif; ?>
                                    <?php else: ?>
                                        <span class="text-muted small">no receipt</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-end"><?= number_format((float)$exp['amount']); ?></td>
                                <?php if ($canEditExp): ?>
                                    <td class="text-end"><button type="button" class="btn btn-sm btn-outline-danger" onclick="srDelExpense(<?= (int)$exp['c0d']; ?>)"><i class="fas fa-trash"></i></button></td>
                                <?php endif; ?>
                            </tr>
                        <?php $first = false; endforeach; ?>
                        <?php if (!empty($bucket['expenses'])):
                            $var = (float)$bucket['variance'];
                            $varBg = $var < 0 ? '#FEE2E2' : '#DCFCE7';
                            $varTx = $var < 0 ? '#7f1d1d' : '#166534';
                        ?>
                        <tr style="background:#F8FAFC;">
                            <td colspan="3" class="text-end small text-muted">
                                Planned <?= number_format((float)$bucket['planned']); ?>
                                · Spent <strong><?= number_format((float)$bucket['spent']); ?></strong>
                                · Variance <span class="badge" style="background:<?= $varBg; ?>;color:<?= $varTx; ?>;"><?= number_format(abs($var)); ?> <?= $var >= 0 ? 'under' : 'over'; ?></span>
                            </td>
                            <td class="text-end"><strong><?= number_format((float)$bucket['spent']); ?></strong></td>
                            <?php if ($canEditExp): ?><td></td><?php endif; ?>
                        </tr>
                        <?php endif; ?>
                    <?php endforeach; ?>
                    <tr style="background:#E2E8F0;">
                        <td colspan="3" class="text-end"><strong>Total retired</strong></td>
                        <td class="text-end"><strong style="font-size:1rem;color:#334155;"><?= number_format((float)$req['retired_amount']); ?></strong></td>
                        <?php if ($canEditExp): ?><td></td><?php endif; ?>
                    </tr>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</div>

<?php endif; /* end expenses section */ ?>

<!-- Add line -->
<?php if ($canEdit): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Add line</strong></div>
    <div class="card-body p-3" style="background:#F8FAFC;">
        <div class="row g-2 align-items-end">
            <div class="col-md-2">
                <label class="form-label" style="font-size:.78rem;">Category</label>
                <select id="ln_cat" class="form-select form-select-sm">
                    <?php foreach ($categories as $c): ?>
                        <option value="<?= $c; ?>"><?= htmlspecialchars($catLabel[$c] ?? $c); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label" style="font-size:.78rem;">Description</label>
                <input id="ln_desc" class="form-control form-control-sm">
            </div>
            <div class="col-md-1">
                <label class="form-label" style="font-size:.78rem;">Qty</label>
                <input id="ln_qty" type="number" step="0.01" min="0" value="1" class="form-control form-control-sm">
            </div>
            <div class="col-md-1">
                <label class="form-label" style="font-size:.78rem;">Unit</label>
                <input id="ln_unit" class="form-control form-control-sm" placeholder="L / kg …">
            </div>
            <div class="col-md-2">
                <label class="form-label" style="font-size:.78rem;">Unit cost</label>
                <input id="ln_uc" type="number" step="0.01" min="0" value="0" class="form-control form-control-sm">
            </div>
            <div class="col-md-1 text-end">
                <button type="button" class="btn btn-sm btn-primary" onclick="srAddLine()"><i class="fas fa-plus"></i></button>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Lines table grouped by category -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Lines by category</strong></div>
    <div class="card-body p-0">
        <?php $anyLines = false; foreach ($byCat as $c => $bucket) if (!empty($bucket['lines'])) { $anyLines = true; break; } ?>
        <?php if (!$anyLines): ?>
            <div class="p-3 text-center text-muted small">No lines yet.</div>
        <?php else: ?>
            <table class="table table-sm mb-0 align-middle">
                <thead class="table-light">
                    <tr>
                        <th style="width:130px;">Category</th>
                        <th>Description</th>
                        <th style="width:60px;">Qty</th>
                        <th style="width:60px;">Unit</th>
                        <th style="width:100px;" class="text-end">Unit cost</th>
                        <th style="width:120px;" class="text-end">Line total</th>
                        <?php if ($canEdit): ?><th style="width:50px;" class="text-end"></th><?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($categories as $cat):
                        $bucket = $byCat[$cat] ?? ['lines'=>[], 'total'=>0];
                        if (empty($bucket['lines'])) continue;
                        $col = $catColor[$cat] ?? '#94a3b8';
                    ?>
                        <?php $first = true; foreach ($bucket['lines'] as $ln): ?>
                            <tr>
                                <td>
                                    <?php if ($first): ?>
                                        <span class="badge" style="background:<?= $col; ?>;color:#fff;"><?= htmlspecialchars($catLabel[$cat] ?? $cat); ?></span>
                                    <?php endif; ?>
                                </td>
                                <td><?= htmlspecialchars($ln['description']); ?><?php if (!empty($ln['notes'])): ?><div class="text-muted small"><?= htmlspecialchars($ln['notes']); ?></div><?php endif; ?></td>
                                <td class="small"><?= number_format((float)$ln['qty'], 2); ?></td>
                                <td class="small"><?= htmlspecialchars($ln['unit']); ?></td>
                                <td class="text-end small"><?= number_format((float)$ln['unit_cost'], 2); ?></td>
                                <td class="text-end"><strong><?= number_format((float)$ln['total']); ?></strong></td>
                                <?php if ($canEdit): ?>
                                    <td class="text-end"><button type="button" class="btn btn-sm btn-outline-danger" onclick="srDelLine(<?= (int)$ln['c0d']; ?>)"><i class="fas fa-trash"></i></button></td>
                                <?php endif; ?>
                            </tr>
                        <?php $first = false; endforeach; ?>
                        <tr style="background:#F8FAFC;">
                            <td colspan="5" class="text-end small text-muted">Subtotal · <?= htmlspecialchars($catLabel[$cat] ?? $cat); ?></td>
                            <td class="text-end"><strong><?= number_format((float)$bucket['total']); ?></strong></td>
                            <?php if ($canEdit): ?><td></td><?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                    <tr style="background:#E2E8F0;">
                        <td colspan="5" class="text-end"><strong>Total</strong></td>
                        <td class="text-end"><strong style="font-size:1rem;color:#334155;"><?= number_format((float)$req['total_amount']); ?></strong></td>
                        <?php if ($canEdit): ?><td></td><?php endif; ?>
                    </tr>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</div>

<!-- Chain history -->
<?php if (!empty($approval)): ?>
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white"><strong>Approval chain</strong>
        <?php if ($approval['status'] !== 'IN_PROGRESS'): ?>
            <span class="badge ms-2" style="background:<?= ($approval['status']==='APPROVED')?'#22c55e':'#dc2626'; ?>;color:#fff;"><?= htmlspecialchars($approval['status']); ?></span>
        <?php endif; ?>
    </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>Step</th><th>Action</th><th>By</th><th>Comment</th></tr>
            </thead>
            <tbody>
                <?php foreach ($history as $h): ?>
                    <tr>
                        <td class="text-muted small"><?= htmlspecialchars($h['decided_on']); ?></td>
                        <td class="small"><?= htmlspecialchars($h['to_step_label'] ?? $h['from_step_label'] ?? '—'); ?></td>
                        <td>
                            <?php
                                $dec = strtoupper((string)$h['decision']);
                                $col = ['SUBMIT'=>'#0ea5e9','APPROVE'=>'#22c55e','SEND_BACK'=>'#f59e0b','DECLINE'=>'#dc2626'][$dec] ?? '#94a3b8';
                            ?>
                            <span class="badge" style="background:<?= $col; ?>;color:#fff;text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$dec))); ?></span>
                        </td>
                        <td class="small"><?= htmlspecialchars($h['actor_display'] ?? ''); ?></td>
                        <td class="text-muted small"><?= htmlspecialchars($h['comment']); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

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

<?php $this->start('section_js'); ?>
<script>
const SR_ID = <?= (int)$req['c0d']; ?>;

function srAddLine() {
    var payload = {
        req_id:      SR_ID,
        category:    $('#ln_cat').val(),
        description: $('#ln_desc').val().trim(),
        qty:         $('#ln_qty').val(),
        unit:        $('#ln_unit').val(),
        unit_cost:   $('#ln_uc').val(),
    };
    if (!payload.description) { rsToast('Description required.', 'error'); return; }
    $.post('<?= PROOT; ?>ServiceRequisitions/addLineAj', payload, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
function srDelLine(id) {
    if (!confirm('Delete this line?')) return;
    $.post('<?= PROOT; ?>ServiceRequisitions/deleteLineAj', { id: id }, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
function srAct(action) {
    var msg = { submit: 'Submit for approval?', cancel: 'Cancel this draft? This cannot be undone.' }[action];
    if (!confirm(msg)) return;
    $.post('<?= PROOT; ?>ServiceRequisitions/' + action + 'Aj', { id: SR_ID }, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
function srStartRet() {
    if (!confirm('Start retirement? You will record actual spends per category, then submit for Accountant approval.')) return;
    $.post('<?= PROOT; ?>ServiceRequisitions/startRetirementAj', { id: SR_ID }, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
function srAddExpense() {
    var payload = {
        req_id:       SR_ID,
        category:     $('#exp_cat').val(),
        description:  $('#exp_desc').val().trim(),
        amount:       $('#exp_amt').val(),
        receipt_ref:  $('#exp_ref').val(),
        receipt_date: $('#exp_date').val(),
    };
    if (!payload.description) { rsToast('Description required.', 'error'); return; }
    if (!(parseFloat(payload.amount) > 0)) { rsToast('Amount must be > 0.', 'error'); return; }
    $.post('<?= PROOT; ?>ServiceRequisitions/addExpenseAj', payload, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
function srDelExpense(id) {
    if (!confirm('Delete this expense?')) return;
    $.post('<?= PROOT; ?>ServiceRequisitions/deleteExpenseAj', { id: id }, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
function srSubmitRet() {
    if (!confirm('Submit retirement for Accountant review? You cannot edit expenses after submitting unless the Accountant sends it back.')) return;
    $.post('<?= PROOT; ?>ServiceRequisitions/submitRetirementAj', { id: SR_ID }, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
function srApproveRet() {
    $.confirm({
        title: 'Approve retirement',
        content: `
            <div class="mb-2 small text-muted">Any variance (over/under-spend) is frozen at approval. Notes describe how it was reconciled.</div>
            <label class="form-label small">Notes (optional)</label>
            <textarea id="ret_notes" rows="2" class="form-control form-control-sm" placeholder="e.g. Unspent 2,000 returned to till; overspend covered from petty cash"></textarea>`,
        type: 'green',
        buttons: {
            approve: { text: 'Approve', btnClass: 'btn-success', action: function () {
                $.post('<?= PROOT; ?>ServiceRequisitions/approveRetirementAj', { id: SR_ID, notes: $('#ret_notes').val() }, 'json')
                    .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
            }},
            cancel: { text: 'Cancel', btnClass: 'btn-light' }
        }
    });
}
function srSendBackRet() {
    var reason = prompt('Send back — why?', '');
    if (!reason || !reason.trim()) { rsToast('Reason required.', 'error'); return; }
    $.post('<?= PROOT; ?>ServiceRequisitions/sendBackRetirementAj', { id: SR_ID, reason: reason.trim() }, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
function srClosePrompt() {
    var banksHtml = '<option value="">— Pick bank account —</option>' +
        (<?= json_encode(array_map(fn($b) => ['id' => (int)$b['c0d'], 'label' => $b['account_name'] . ' · ' . $b['bank_name']], $banks)); ?>
            .map(function (b) { return '<option value="' + b.id + '">' + b.label + '</option>'; }).join(''));
    $.confirm({
        title: 'Close · post to GL',
        content: `
            <div class="mb-2 small text-muted">Posts the retirement expenses as a balanced journal entry.<br>
                <strong>Dr</strong> · one line per category (mapped via CoA)<br>
                <strong>Cr</strong> · Bank & Cash for total retired amount<br>
                Variance was already reconciled at retirement approval — not posted here.</div>
            <label class="form-label small">Bank account to credit</label>
            <select id="cl_bank" class="form-select form-select-sm">` + banksHtml + `</select>`,
        type: 'dark',
        buttons: {
            close: { text: 'Post & close', btnClass: 'btn-dark', action: function () {
                var payload = { id: SR_ID, bank_account_id: $('#cl_bank').val() || 0 };
                $.post('<?= PROOT; ?>ServiceRequisitions/closeAj', payload, 'json')
                    .done(function (r) {
                        if (r && r.ok) { rsToast('Posted (JE #' + r.je_id + ')', 'success'); setTimeout(function () { location.reload(); }, 700); }
                        else rsToast('Failed: ' + (r.msg || 'unknown'), 'error');
                    });
            }},
            cancel: { text: 'Cancel', btnClass: 'btn-light' }
        }
    });
}
function srIssuePrompt() {
    $.confirm({
        title: 'Issue cash',
        content: `
            <div class="mb-2 small text-muted">Confirm the cash release. Amount defaults to the approved total but may be reduced for partial issues.</div>
            <div class="row g-2">
                <div class="col-md-6"><label class="form-label small">Issue reference *</label><input id="iss_ref" class="form-control form-control-sm" placeholder="Voucher / cheque / TT ref"></div>
                <div class="col-md-6"><label class="form-label small">Amount (max <?= number_format((float)$req['total_amount']); ?>)</label><input id="iss_amt" type="number" step="0.01" class="form-control form-control-sm" value="<?= (float)$req['total_amount']; ?>"></div>
                <div class="col-12"><label class="form-label small">Notes</label><input id="iss_nt" class="form-control form-control-sm"></div>
            </div>`,
        type: 'green',
        buttons: {
            issue: { text: 'Issue', btnClass: 'btn-success', action: function () {
                var payload = {
                    id: SR_ID,
                    issue_reference: $('#iss_ref').val().trim(),
                    issue_amount:    $('#iss_amt').val(),
                    issue_notes:     $('#iss_nt').val(),
                };
                if (!payload.issue_reference) { rsToast('Reference required.', 'error'); return false; }
                $.post('<?= PROOT; ?>ServiceRequisitions/issueAj', payload, 'json')
                    .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
            }},
            cancel: { text: 'Cancel', btnClass: 'btn-light' }
        }
    });
}
</script>
<?php $this->end(); ?>
