<?php $this->start('body');
    $lpo   = $this->data['lpo']        ?? [];
    $r     = $this->data['retirement'] ?? [];
    $lines = $this->data['lines']      ?? [];
    $coa   = $this->data['coa']        ?? [];
    $receipts   = $this->data['receipts']  ?? [];
    $lineAtts   = $this->data['line_atts'] ?? [];
    $isDiscovery = (bool)($this->data['is_discovery'] ?? false);
    $findings    = $this->data['findings'] ?? [];
    $locked      = !in_array((string)$r['status'], ['DRAFT','REJECTED'], true);
    $currency    = (string)($lpo['currency'] ?? 'TZS');
    $lpoAmt      = (float)($lpo['amount'] ?? 0);

    // Slice 8Z-q · receipt confirmation gate
    $receiptConfirmed = !empty($lpo['receipt_confirmed_at']);
    $retirementDue    = (string)($lpo['retirement_due_date'] ?? '');
    $daysToDue        = null;
    if ($retirementDue !== '' && $retirementDue !== '0000-00-00') {
        $daysToDue = (int)floor((strtotime($retirementDue) - strtotime(date('Y-m-d'))) / 86400);
    }

    $recTypeChip = [
        'NORMAL'      => ['#EEF2F6','#334155','Normal'],
        'EFD_VAT'     => ['#EAF2E8','#3F5C43','EFD VAT'],
        'EFD_NON_VAT' => ['#FEF3E7','#8B6914','EFD Non-VAT'],
    ];
    $recChip = [
        'SHORTLIST' => ['#EAF2E8','#3F5C43','Shortlist'],
        'MAYBE'     => ['#FEF3E7','#8B6914','Maybe'],
        'REJECT'    => ['#F5EAE1','#C48579','Reject'],
    ];
    $shortlistCount = 0; foreach ($findings as $f) if ($f['recommendation'] === 'SHORTLIST') $shortlistCount++;
    $statusChip = [
        'DRAFT'     => ['#F1F5F9','#334155','Draft'],
        'SUBMITTED' => ['#EEF2F6','#7A8BA1','Submitted'],
        'APPROVED'  => ['#EAF2E8','#3F5C43','Approved'],
        'REJECTED'  => ['#F5EAE1','#C48579','Bounced back'],
    ];
    $sc = $statusChip[$r['status']] ?? ['#F1F5F9','#334155',$r['status']];

    // Index receipts for line dropdown
    $recById = []; foreach ($receipts as $rc) { $recById[(int)$rc['c0d']] = $rc; }
?>

<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-file-invoice-dollar me-2 text-muted"></i>Retire &middot; <?= htmlspecialchars($lpo['lpo_no']); ?></h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            <?= htmlspecialchars(($lpo['lpo_type'] === 'PETTY_CASH') ? 'Petty Cash' : ucfirst(strtolower(str_replace('_',' ', (string)$lpo['lpo_type'])))); ?>
            &middot; Advance: <strong><?= $currency; ?> <?= number_format($lpoAmt); ?></strong>
            &middot; <?= htmlspecialchars((string)$lpo['purpose']); ?>
        </div>
    </div>
    <div>
        <span class="badge me-2" style="background:<?= $sc[0]; ?>;color:<?= $sc[1]; ?>;border:1px solid <?= $sc[1]; ?>;font-size:.65rem;text-transform:capitalize;"><?= htmlspecialchars($sc[2]); ?></span>
        <a href="<?= PROOT; ?>Lpos/view/<?= (int)$lpo['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back to LPO</a>
    </div>
</div>

<?php if (!$receiptConfirmed && !$locked): ?>
    <div class="alert py-2 small mb-3" style="background:#FEF3E7;border:1px solid #8B6914;color:#8B6914;font-size:.72rem;">
        <i class="fas fa-hand-holding-usd me-1"></i>
        <strong>Receipt not yet confirmed.</strong>
        You cannot submit this retirement until you confirm the cash actually arrived on the
        <a href="<?= PROOT; ?>Lpos/view/<?= (int)$lpo['c0d']; ?>" style="color:#8B6914;text-decoration:underline;">LPO page</a>.
        (Auto-confirms after 5 days.)
    </div>
<?php elseif ($receiptConfirmed && !$locked && $daysToDue !== null): ?>
    <div class="alert py-2 small mb-3" style="background:<?= $daysToDue < 0 ? '#F5EAE1' : ($daysToDue <= 3 ? '#FEF3E7' : '#EAF2E8'); ?>;border:1px solid <?= $daysToDue < 0 ? '#C48579' : ($daysToDue <= 3 ? '#8B6914' : '#3F5C43'); ?>;color:<?= $daysToDue < 0 ? '#C48579' : ($daysToDue <= 3 ? '#8B6914' : '#3F5C43'); ?>;font-size:.72rem;">
        <i class="fas fa-clock me-1"></i>
        <?php if ($daysToDue < 0): ?>
            <strong>Overdue by <?= abs($daysToDue); ?> day<?= abs($daysToDue) === 1 ? '' : 's'; ?></strong> &middot; Retirement was due <?= htmlspecialchars($retirementDue); ?>.
        <?php elseif ($daysToDue === 0): ?>
            <strong>Due today.</strong>
        <?php else: ?>
            Retirement due in <strong><?= $daysToDue; ?> day<?= $daysToDue === 1 ? '' : 's'; ?></strong> (<?= htmlspecialchars($retirementDue); ?>).
        <?php endif; ?>
    </div>
<?php endif; ?>

<?php if ($locked): ?>
    <div class="alert py-2 small mb-3" style="background:#EEF2F6;border:1px solid #7A8BA1;color:#334155;font-size:.72rem;">
        <i class="fas fa-lock me-1"></i>Locked &middot; this retirement is <strong><?= htmlspecialchars($r['status']); ?></strong>.
        <?= !empty($r['reviewer_notes']) ? ' Reviewer notes: <em>' . htmlspecialchars($r['reviewer_notes']) . '</em>' : ''; ?>
    </div>
<?php endif; ?>

<div class="row g-3">
    <!-- Left · receipts + spend lines -->
    <div class="col-lg-8">

        <!-- Receipts (cross-cutting) -->
        <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-receipt me-1 text-muted"></i>Receipts
                    <span class="text-muted ms-2" style="font-weight:400;font-size:.65rem;"><?= count($receipts); ?> captured</span>
                </div>
                <?php if (!$locked): ?>
                    <button type="button" class="btn btn-sm" id="btn_add_receipt" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
                        <i class="fas fa-plus me-1"></i>Add receipt
                    </button>
                <?php endif; ?>
            </div>
            <div class="table-responsive">
                <table class="table table-sm mb-0 align-middle">
                    <thead class="table-light">
                        <tr>
                            <th style="width:36px;">#</th>
                            <th>Subject</th>
                            <th style="width:100px;">Type</th>
                            <th class="text-end" style="width:120px;">Gross</th>
                            <th class="text-end" style="width:100px;">VAT</th>
                            <th style="width:110px;">EFD ref</th>
                            <th style="width:80px;">File</th>
                            <?php if (!$locked): ?><th style="width:60px;"></th><?php endif; ?>
                        </tr>
                    </thead>
                    <tbody id="receipts_tbody">
                        <?php foreach ($receipts as $i => $rc):
                            $tc = $recTypeChip[$rc['receipt_type']] ?? $recTypeChip['NORMAL'];
                        ?>
                            <tr data-receipt-id="<?= (int)$rc['c0d']; ?>">
                                <td class="text-muted small"><?= $i + 1; ?></td>
                                <td class="small">
                                    <strong><?= htmlspecialchars($rc['subject']); ?></strong>
                                    <?php if (!empty($rc['supplier_name'])): ?><div class="text-muted" style="font-size:.62rem;"><?= htmlspecialchars($rc['supplier_name']); ?><?php if (!empty($rc['supplier_tin'])): ?> &middot; TIN <?= htmlspecialchars($rc['supplier_tin']); ?><?php endif; ?></div><?php endif; ?>
                                </td>
                                <td><span class="badge" style="background:<?= $tc[0]; ?>;color:<?= $tc[1]; ?>;border:1px solid <?= $tc[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($tc[2]); ?></span></td>
                                <td class="text-end small" style="font-weight:600;color:#334155;"><?= number_format((float)$rc['gross_amount']); ?></td>
                                <td class="text-end small text-muted"><?= $rc['vat_amount'] !== null ? number_format((float)$rc['vat_amount']) : '—'; ?></td>
                                <td class="small text-muted">
                                    <?= !empty($rc['efd_receipt_no']) ? htmlspecialchars($rc['efd_receipt_no']) : '—'; ?>
                                    <?php if (!empty($rc['efd_date'])): ?><div style="font-size:.62rem;"><?= htmlspecialchars($rc['efd_date']); ?></div><?php endif; ?>
                                </td>
                                <td class="small">
                                    <?php if (!empty($rc['attachment_path'])): ?>
                                        <a href="<?= PROOT; ?>Retirements/receiptFileDownload/<?= (int)$rc['c0d']; ?>" target="_blank" class="text-decoration-none" title="<?= htmlspecialchars((string)$rc['attachment_original_name']); ?>"><i class="fas fa-paperclip" style="color:#7A8BA1;"></i></a>
                                    <?php else: ?>
                                        <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>
                                <?php if (!$locked): ?>
                                    <td class="text-end">
                                        <button type="button" class="btn btn-sm btn-link p-0 me-1 btn_edit_receipt" title="Edit"><i class="fas fa-pen" style="color:#7A8BA1;"></i></button>
                                        <button type="button" class="btn btn-sm btn-link p-0 btn_del_receipt text-danger" title="Remove"><i class="fas fa-times"></i></button>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($receipts)): ?>
                            <tr><td colspan="<?= $locked ? 7 : 8; ?>" class="text-center text-muted py-3" style="font-size:.72rem;">
                                No receipts captured yet<?= $locked ? '.' : ' &mdash; click <strong>Add receipt</strong>. One receipt can back multiple spend lines.'; ?>
                            </td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <?php if (!$locked): ?>
                <div class="card-footer py-2 small text-muted" style="background:#F8FAFC;font-size:.62rem;">
                    <i class="fas fa-info-circle me-1" style="color:#7A8BA1;"></i>
                    EFD VAT receipts require an EFD receipt number and VAT is auto-split to Input VAT (COA 1220) on posting. Link each spend line to its receipt in the table below.
                </div>
            <?php endif; ?>
        </div>

        <!-- Spend lines -->
        <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-list me-1 text-muted"></i>Spend lines</div>
                <?php if (!$locked): ?>
                    <button type="button" class="btn btn-sm" id="btn_add_line" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
                        <i class="fas fa-plus me-1"></i>Add line
                    </button>
                <?php endif; ?>
            </div>
            <div class="table-responsive">
                <table class="table table-sm mb-0 align-middle" id="lines_table">
                    <thead class="table-light">
                        <tr>
                            <th style="width:36px;">#</th>
                            <th>Description</th>
                            <th class="text-end" style="width:120px;">Amount</th>
                            <th style="width:140px;">Account</th>
                            <th style="width:150px;">Receipt</th>
                            <th style="width:120px;">Photos</th>
                            <?php if (!$locked): ?><th style="width:36px;"></th><?php endif; ?>
                        </tr>
                    </thead>
                    <tbody id="lines_tbody">
                        <?php foreach ($lines as $ln):
                            $lnAtts = $lineAtts[(int)$ln['c0d']] ?? [];
                            $lnRc   = !empty($ln['receipt_id']) && isset($recById[(int)$ln['receipt_id']]) ? $recById[(int)$ln['receipt_id']] : null;
                        ?>
                            <tr data-line-id="<?= (int)$ln['c0d']; ?>">
                                <td class="text-muted small"><?= (int)$ln['line_no']; ?></td>
                                <td class="small">
                                    <?= htmlspecialchars($ln['description']); ?>
                                    <?php if (!empty($ln['notes'])): ?><div class="text-muted" style="font-size:.62rem;"><?= htmlspecialchars($ln['notes']); ?></div><?php endif; ?>
                                </td>
                                <td class="text-end small" style="font-weight:600;color:#334155;"><?= number_format((float)$ln['amount']); ?></td>
                                <td class="small text-muted"><?php
                                    if (!empty($ln['coa_account_id'])) {
                                        foreach ($coa as $c) if ((int)$c['c0d'] === (int)$ln['coa_account_id']) { echo htmlspecialchars($c['account_code'] . ' · ' . $c['account_name']); break; }
                                    } else echo '<em>—</em>';
                                ?></td>
                                <td class="small">
                                    <?php if (!$locked): ?>
                                        <select class="form-select form-select-sm line_receipt_select" style="font-size:.7rem;padding:.15rem .4rem;">
                                            <option value="">— None —</option>
                                            <?php foreach ($receipts as $rc): ?>
                                                <option value="<?= (int)$rc['c0d']; ?>" <?= ((int)($ln['receipt_id'] ?? 0) === (int)$rc['c0d']) ? 'selected' : ''; ?>>
                                                    <?= htmlspecialchars(mb_strimwidth((string)$rc['subject'], 0, 26, '…')); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    <?php else: ?>
                                        <?php if ($lnRc): ?>
                                            <span class="text-muted"><?= htmlspecialchars(mb_strimwidth((string)$lnRc['subject'], 0, 22, '…')); ?></span>
                                        <?php else: ?>
                                            <span class="text-muted">—</span>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </td>
                                <td class="small">
                                    <?php foreach ($lnAtts as $a): ?>
                                        <a href="<?= PROOT; ?>Retirements/lineAttachmentDownload/<?= (int)$a['c0d']; ?>" target="_blank" title="<?= htmlspecialchars((string)$a['original_name']); ?>" style="display:inline-block;margin-right:2px;">
                                            <i class="fas fa-image" style="color:#7A8BA1;font-size:.85rem;"></i>
                                        </a>
                                    <?php endforeach; ?>
                                    <?php if (!$locked && count($lnAtts) < 4): ?>
                                        <button type="button" class="btn btn-sm btn-link p-0 btn_add_line_att" title="Add photo (max 4)" style="font-size:.7rem;">
                                            <i class="fas fa-plus-circle" style="color:#7A9E7E;"></i>
                                        </button>
                                    <?php endif; ?>
                                    <?php if (!$locked && !empty($lnAtts)): ?>
                                        <button type="button" class="btn btn-sm btn-link p-0 btn_manage_line_att ms-1" title="Manage photos" style="font-size:.7rem;">
                                            <i class="fas fa-cog" style="color:#7A8BA1;"></i>
                                        </button>
                                    <?php endif; ?>
                                </td>
                                <?php if (!$locked): ?>
                                    <td class="text-end">
                                        <button type="button" class="btn btn-sm btn-link text-danger p-0 btn_del_line" title="Remove"><i class="fas fa-times"></i></button>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($lines)): ?>
                            <tr id="empty_row"><td colspan="<?= $locked ? 6 : 7; ?>" class="text-center text-muted py-4" style="font-size:.72rem;">No spend lines yet<?= $locked ? '.' : ' &mdash; click <strong>Add line</strong> to record what the cash was spent on.'; ?></td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <?php if ($isDiscovery): ?>
        <!-- Product Discovery · findings capture (Batch 4) -->
        <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-binoculars me-1 text-muted"></i>Discovery findings
                    <span class="text-muted ms-2" style="font-weight:400;font-size:.65rem;">
                        <?= count($findings); ?> profiled &middot; <?= $shortlistCount; ?> shortlisted for RFQ
                    </span>
                </div>
                <?php if (!$locked): ?>
                    <button type="button" class="btn btn-sm" id="btn_add_finding" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
                        <i class="fas fa-plus me-1"></i>Add supplier
                    </button>
                <?php endif; ?>
            </div>
            <div class="table-responsive">
                <table class="table table-sm mb-0 align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>Supplier</th>
                            <th>Contact</th>
                            <th class="text-end" style="width:130px;">Quote</th>
                            <th class="text-center" style="width:70px;">Sample</th>
                            <th style="width:110px;">Verdict</th>
                            <?php if (!$locked): ?><th style="width:70px;" class="text-end"></th><?php endif; ?>
                        </tr>
                    </thead>
                    <tbody id="findings_tbody">
                        <?php foreach ($findings as $f):
                            $fc = $recChip[$f['recommendation']] ?? $recChip['MAYBE'];
                        ?>
                            <tr data-finding-id="<?= (int)$f['c0d']; ?>">
                                <td class="small">
                                    <strong><?= htmlspecialchars($f['supplier_name']); ?></strong>
                                    <?php if (!empty($f['country'])): ?><div class="text-muted" style="font-size:.62rem;"><?= htmlspecialchars($f['country']); ?></div><?php endif; ?>
                                    <?php if (!empty($f['capability_notes'])): ?><div class="text-muted" style="font-size:.62rem;"><?= htmlspecialchars(mb_strimwidth($f['capability_notes'], 0, 70, '…')); ?></div><?php endif; ?>
                                </td>
                                <td class="small text-muted">
                                    <?= htmlspecialchars($f['contact_name']); ?>
                                    <?php if (!empty($f['phone']) || !empty($f['email'])): ?><div style="font-size:.62rem;"><?= htmlspecialchars(trim($f['phone'] . ' · ' . $f['email'], ' ·')); ?></div><?php endif; ?>
                                </td>
                                <td class="text-end small">
                                    <?php if ((int)$f['quote_received'] === 1 && !empty($f['quote_amount'])): ?>
                                        <span style="font-weight:600;color:#334155;"><?= htmlspecialchars($f['quote_currency'] ?: $currency); ?> <?= number_format((float)$f['quote_amount']); ?></span>
                                        <?php if (!empty($f['quote_lead_time_days'])): ?><div class="text-muted" style="font-size:.62rem;"><?= (int)$f['quote_lead_time_days']; ?>d lead</div><?php endif; ?>
                                    <?php else: ?>
                                        <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <?php if ((int)$f['sample_received'] === 1): ?>
                                        <i class="fas fa-check" style="color:#3F5C43;"></i>
                                    <?php else: ?>
                                        <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>
                                <td><span class="badge" style="background:<?= $fc[0]; ?>;color:<?= $fc[1]; ?>;border:1px solid <?= $fc[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($fc[2]); ?></span></td>
                                <?php if (!$locked): ?>
                                    <td class="text-end">
                                        <button type="button" class="btn btn-sm btn-link p-0 me-2 btn_edit_finding" title="Edit"><i class="fas fa-pen" style="color:#7A8BA1;"></i></button>
                                        <button type="button" class="btn btn-sm btn-link p-0 btn_del_finding text-danger" title="Remove"><i class="fas fa-times"></i></button>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($findings)): ?>
                            <tr><td colspan="<?= $locked ? 5 : 6; ?>" class="text-center text-muted py-3" style="font-size:.72rem;">
                                No supplier profiles captured yet<?= $locked ? '.' : ' &mdash; click <strong>Add supplier</strong> to record what you discovered.'; ?>
                            </td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <?php if (!$locked): ?>
                <div class="card-footer py-2 small text-muted" style="background:#F8FAFC;font-size:.62rem;">
                    <i class="fas fa-lightbulb me-1" style="color:#8B6914;"></i>
                    Suppliers marked <strong>Shortlist</strong> will be pre-loaded into the RFQ workspace for this Client PO once you send it out.
                </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>

    <!-- Right · balance + submit -->
    <div class="col-lg-4">
        <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-balance-scale me-1 text-muted"></i>Reconcile
            </div>
            <div class="card-body p-3">
                <div class="d-flex justify-content-between mb-1 small"><span class="text-muted">Advance issued</span><span style="font-weight:600;color:#334155;"><?= $currency; ?> <?= number_format($lpoAmt); ?></span></div>
                <div class="d-flex justify-content-between mb-1 small"><span class="text-muted">Total spent</span><span id="tot_spent" style="font-weight:600;color:#334155;"><?= $currency; ?> <?= number_format((float)$r['total_spent']); ?></span></div>
                <div class="d-flex align-items-center mb-1">
                    <label class="text-muted small me-2" style="min-width:110px;font-size:.72rem;">Cash returned</label>
                    <input type="number" step="0.01" min="0" id="cash_returned" class="form-control form-control-sm text-end"
                           value="<?= (float)$r['cash_returned']; ?>" <?= $locked ? 'disabled' : ''; ?>>
                </div>
                <hr class="my-2">
                <div class="d-flex justify-content-between small">
                    <span class="text-muted">Variance</span>
                    <span id="variance_chip" class="badge" style="font-size:.65rem;">
                        <?= $currency; ?> <?= number_format((float)$r['variance']); ?>
                    </span>
                </div>
                <div class="text-muted mt-2" style="font-size:.62rem;">
                    Variance must be <strong>zero</strong> to submit. Add missing spend lines or increase cash returned to balance.
                </div>
            </div>
        </div>

        <?php if (!$locked): ?>
            <div class="card border-0 shadow-sm">
                <div class="card-body p-3 text-end">
                    <?php if (!$receiptConfirmed): ?>
                        <button type="button" class="btn btn-sm" disabled style="background:#E2E8F0;border-color:#E2E8F0;color:#94A3B8;font-weight:600;cursor:not-allowed;" title="Confirm receipt on the LPO first.">
                            <i class="fas fa-lock me-1"></i>Submit blocked &middot; receipt not confirmed
                        </button>
                    <?php else: ?>
                        <button type="button" id="btn_submit" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
                            <i class="fas fa-paper-plane me-1"></i>Submit for Accountant review
                        </button>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
(function () {
    var RETIREMENT_ID = <?= (int)$r['c0d']; ?>;
    var LOCKED        = <?= $locked ? 'true' : 'false'; ?>;
    var CURRENCY      = <?= json_encode($currency); ?>;
    var PROOT         = '<?= PROOT; ?>';

    function fmt(n) { n = parseFloat(n||0); return n.toLocaleString(undefined, {maximumFractionDigits: 0}); }
    function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]); }); }

    function paintTotals(t) {
        if (!t) return;
        document.getElementById('tot_spent').textContent = CURRENCY + ' ' + fmt(t.total_spent);
        var chip = document.getElementById('variance_chip');
        chip.textContent = CURRENCY + ' ' + fmt(t.variance);
        var bal = Math.abs(parseFloat(t.variance||0)) < 0.005;
        chip.style.background = bal ? '#EAF2E8' : '#F5EAE1';
        chip.style.color      = bal ? '#3F5C43' : '#C48579';
        chip.style.border     = '1px solid ' + (bal ? '#3F5C43' : '#C48579');
    }

    if (!LOCKED) {
        // Cash returned live-update
        document.getElementById('cash_returned').addEventListener('change', function () {
            var v = parseFloat(this.value || 0);
            $.post(PROOT + 'Retirements/saveHeaderAj', { retirement_id: RETIREMENT_ID, cash_returned: v }, function (r) {
                if (r && r.ok) paintTotals(r.totals);
                else $.alert({title:'Could not save', content:(r && r.msg) || 'Server error', type:'red'});
            }, 'json');
        });

        // Line receipt link change
        document.getElementById('lines_tbody').addEventListener('change', function (e) {
            var sel = e.target.closest('.line_receipt_select'); if (!sel) return;
            var tr = sel.closest('tr'); if (!tr) return;
            $.post(PROOT + 'Retirements/setLineReceiptAj', { line_id: tr.getAttribute('data-line-id'), receipt_id: sel.value }, function (r) {
                if (r && r.ok) rsToast('Linked.', 'success');
                else $.alert({title:'Could not link', content:(r && r.msg) || 'Server error', type:'red'});
            }, 'json');
        });

        // ── Add line dialog ──────────────────────────────────────────────
        document.getElementById('btn_add_line').addEventListener('click', function () {
            var coaOpts = '<option value="0">— None —</option>';
            <?php foreach ($coa as $c): ?>
            coaOpts += '<option value="<?= (int)$c['c0d']; ?>"><?= htmlspecialchars(addslashes($c['account_code'] . ' · ' . $c['account_name'])); ?></option>';
            <?php endforeach; ?>
            $.confirm({
                title: 'Add spend line',
                columnClass: 'col-md-6',
                content:
                    '<form id="add_line_form" enctype="multipart/form-data">' +
                    '  <div class="mb-2"><label class="form-label small">Description *</label><input type="text" name="description" class="form-control form-control-sm" required></div>' +
                    '  <div class="row g-2 mb-2">' +
                    '    <div class="col-6"><label class="form-label small">Amount *</label><input type="number" step="0.01" min="0" name="amount" class="form-control form-control-sm" required></div>' +
                    '    <div class="col-6"><label class="form-label small">Expense account</label><select name="coa_account_id" class="form-select form-select-sm">' + coaOpts + '</select></div>' +
                    '  </div>' +
                    '  <div class="mb-2"><label class="form-label small">Notes</label><input type="text" name="notes" class="form-control form-control-sm"></div>' +
                    '  <div class="text-muted small" style="font-size:.62rem;">Link to a receipt and add photos from the row after saving.</div>' +
                    '</form>',
                buttons: {
                    save: { text: 'Add line', btnClass: 'btn-success', action: function () {
                        var form = document.getElementById('add_line_form');
                        var fd = new FormData(form);
                        fd.append('retirement_id', RETIREMENT_ID);
                        var desc = (fd.get('description')||'').toString().trim();
                        var amt  = parseFloat(fd.get('amount')||0);
                        if (!desc)     { $.alert({title:'Description required',type:'orange'}); return false; }
                        if (!(amt>0))  { $.alert({title:'Amount must be > 0',type:'orange'}); return false; }
                        $.ajax({
                            url: PROOT + 'Retirements/addLineAj',
                            method: 'POST', data: fd, processData: false, contentType: false, dataType: 'json'
                        }).done(function (r) {
                            if (r && r.ok) { rsToast('Line added.', 'success'); setTimeout(function(){ location.reload(); }, 400); }
                            else $.alert({title:'Could not add', content:(r && r.msg) || 'Server error', type:'red'});
                        }).fail(function () { $.alert({title:'Network error', type:'red'}); });
                        return false;
                    }},
                    cancel: function () {}
                }
            });
        });

        // Delete line
        document.getElementById('lines_tbody').addEventListener('click', function (e) {
            var btn = e.target.closest('.btn_del_line');
            var addAtt = e.target.closest('.btn_add_line_att');
            var manageAtt = e.target.closest('.btn_manage_line_att');
            if (btn) {
                var tr = btn.closest('tr'); if (!tr) return;
                var lid = tr.getAttribute('data-line-id');
                $.confirm({
                    title: 'Remove line?', content: 'This spend line will be deleted.', type: 'red',
                    buttons: {
                        yes: { text: 'Remove', btnClass: 'btn-danger', action: function () {
                            $.post(PROOT + 'Retirements/removeLineAj', { line_id: lid }, function (r) {
                                if (r && r.ok) { rsToast('Removed.', 'success'); setTimeout(function(){ location.reload(); }, 300); }
                                else $.alert({title:'Could not remove', content:(r && r.msg) || 'Server error', type:'red'});
                            }, 'json');
                        }},
                        cancel: function () {}
                    }
                });
                return;
            }
            if (addAtt) {
                var tr2 = addAtt.closest('tr'); if (!tr2) return;
                openLineAttachDialog(tr2.getAttribute('data-line-id'));
                return;
            }
            if (manageAtt) {
                var tr3 = manageAtt.closest('tr'); if (!tr3) return;
                window.location.hash = 'line-' + tr3.getAttribute('data-line-id'); // just anchor jump for now
                // (Reuse same add dialog; per-item removal happens on the download page via row rebuild)
            }
        });

        function openLineAttachDialog(lineId) {
            $.confirm({
                title: 'Upload photo / proof',
                columnClass: 'col-md-5',
                content: '<form id="att_form" enctype="multipart/form-data">' +
                    '<input type="file" name="attachment" class="form-control form-control-sm" accept="image/*,.pdf" required>' +
                    '<div class="text-muted small mt-2" style="font-size:.62rem;">Max 4 attachments per line &middot; up to 10 MB each.</div>' +
                    '</form>',
                buttons: {
                    save: { text: 'Upload', btnClass: 'btn-success', action: function () {
                        var form = document.getElementById('att_form');
                        var fd = new FormData(form);
                        fd.append('line_id', lineId);
                        if (!fd.get('attachment') || !fd.get('attachment').name) { $.alert({title:'Pick a file first',type:'orange'}); return false; }
                        $.ajax({
                            url: PROOT + 'Retirements/addLineAttachmentAj',
                            method: 'POST', data: fd, processData: false, contentType: false, dataType: 'json'
                        }).done(function (r) {
                            if (r && r.ok) { rsToast('Uploaded.', 'success'); setTimeout(function(){ location.reload(); }, 400); }
                            else $.alert({title:'Could not upload', content:(r && r.msg) || 'Server error', type:'red'});
                        }).fail(function () { $.alert({title:'Network error', type:'red'}); });
                        return false;
                    }},
                    cancel: function () {}
                }
            });
        }

        // ── Receipts CRUD ────────────────────────────────────────────────
        function receiptFormHtml(rc) {
            rc = rc || {};
            var t = rc.receipt_type || 'NORMAL';
            var isVat = (t === 'EFD_VAT');
            var showEfd = (t !== 'NORMAL');
            return '<form id="rc_form" enctype="multipart/form-data">' +
                '<div class="row g-2 mb-2">' +
                  '<div class="col-4"><label class="form-label small">Type *</label><select name="receipt_type" id="rc_type" class="form-select form-select-sm">' +
                    '<option value="NORMAL"' + (t==='NORMAL'?' selected':'') + '>Normal</option>' +
                    '<option value="EFD_VAT"' + (t==='EFD_VAT'?' selected':'') + '>EFD VAT</option>' +
                    '<option value="EFD_NON_VAT"' + (t==='EFD_NON_VAT'?' selected':'') + '>EFD Non-VAT</option>' +
                  '</select></div>' +
                  '<div class="col-8"><label class="form-label small">Subject *</label><input name="subject" class="form-control form-control-sm" value="' + esc(rc.subject||'') + '" placeholder="e.g. SIM cards + top-up + fuel receipt" required></div>' +
                '</div>' +
                '<div class="row g-2 mb-2">' +
                  '<div class="col-8"><label class="form-label small">Supplier</label><input name="supplier_name" class="form-control form-control-sm" value="' + esc(rc.supplier_name||'') + '"></div>' +
                  '<div class="col-4"><label class="form-label small">Supplier TIN</label><input name="supplier_tin" class="form-control form-control-sm" value="' + esc(rc.supplier_tin||'') + '"></div>' +
                '</div>' +
                '<div class="row g-2 mb-2" id="rc_efd_row" style="display:' + (showEfd?'flex':'none') + ';">' +
                  '<div class="col-6"><label class="form-label small">EFD receipt no ' + (showEfd?'*':'') + '</label><input name="efd_receipt_no" class="form-control form-control-sm" value="' + esc(rc.efd_receipt_no||'') + '"></div>' +
                  '<div class="col-6"><label class="form-label small">EFD date</label><input name="efd_date" type="date" class="form-control form-control-sm" value="' + esc(rc.efd_date||'') + '"></div>' +
                '</div>' +
                '<div class="row g-2 mb-2">' +
                  '<div class="col-6"><label class="form-label small">Gross amount *</label><input name="gross_amount" type="number" step="0.01" min="0" class="form-control form-control-sm" value="' + (rc.gross_amount||'') + '" required></div>' +
                  '<div class="col-6" id="rc_vat_col" style="display:' + (isVat?'block':'none') + ';"><label class="form-label small">VAT amount</label><input name="vat_amount" type="number" step="0.01" min="0" class="form-control form-control-sm" value="' + (rc.vat_amount||'') + '"></div>' +
                '</div>' +
                '<div class="mb-2"><label class="form-label small">Notes</label><input name="notes" class="form-control form-control-sm" value="' + esc(rc.notes||'') + '"></div>' +
                '<div class="mb-2"><label class="form-label small">Receipt file (optional)</label><input type="file" name="attachment" class="form-control form-control-sm" accept=".pdf,image/*"></div>' +
                '</form>';
        }

        function wireReceiptTypeToggle() {
            var sel = document.getElementById('rc_type'); if (!sel) return;
            sel.addEventListener('change', function () {
                var t = sel.value;
                document.getElementById('rc_efd_row').style.display = (t !== 'NORMAL') ? 'flex' : 'none';
                document.getElementById('rc_vat_col').style.display = (t === 'EFD_VAT') ? 'block' : 'none';
            });
        }

        function submitReceipt(url, extra) {
            var form = document.getElementById('rc_form');
            var fd = new FormData(form);
            var subj = (fd.get('subject')||'').toString().trim();
            var gross = parseFloat(fd.get('gross_amount')||0);
            if (!subj)      { $.alert({title:'Subject required',type:'orange'}); return false; }
            if (!(gross>0)) { $.alert({title:'Gross amount must be > 0',type:'orange'}); return false; }
            var t = fd.get('receipt_type');
            if (t !== 'NORMAL' && !(fd.get('efd_receipt_no')||'').toString().trim()) { $.alert({title:'EFD receipt no required for ' + t, type:'orange'}); return false; }
            fd.append('retirement_id', RETIREMENT_ID);
            for (var k in (extra||{})) fd.append(k, extra[k]);
            $.ajax({
                url: url, method: 'POST', data: fd, processData: false, contentType: false, dataType: 'json'
            }).done(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'});
            }).fail(function () { $.alert({title:'Network error', type:'red'}); });
            return false;
        }

        document.getElementById('btn_add_receipt').addEventListener('click', function () {
            $.confirm({
                title: 'Add receipt',
                columnClass: 'col-md-7',
                content: receiptFormHtml(),
                onOpen: wireReceiptTypeToggle,
                buttons: {
                    save: { text: 'Add', btnClass: 'btn-success', action: function () { return submitReceipt(PROOT + 'Retirements/addReceiptAj'); }},
                    cancel: function () {}
                }
            });
        });

        // Receipts row actions (edit/delete)
        var RECEIPTS_JSON = <?= json_encode(array_values(array_map(function ($rc) {
            return [
                'c0d'            => (int)$rc['c0d'],
                'receipt_type'   => (string)$rc['receipt_type'],
                'subject'        => (string)$rc['subject'],
                'supplier_name'  => (string)($rc['supplier_name'] ?? ''),
                'supplier_tin'   => (string)($rc['supplier_tin'] ?? ''),
                'efd_receipt_no' => (string)($rc['efd_receipt_no'] ?? ''),
                'efd_date'       => (string)($rc['efd_date'] ?? ''),
                'gross_amount'   => (float)$rc['gross_amount'],
                'vat_amount'     => $rc['vat_amount'] !== null ? (float)$rc['vat_amount'] : null,
                'notes'          => (string)($rc['notes'] ?? ''),
            ];
        }, $receipts))); ?>;
        var RCMAP = {}; RECEIPTS_JSON.forEach(function (r) { RCMAP[r.c0d] = r; });

        document.getElementById('receipts_tbody').addEventListener('click', function (e) {
            var editBtn = e.target.closest('.btn_edit_receipt');
            var delBtn  = e.target.closest('.btn_del_receipt');
            if (!editBtn && !delBtn) return;
            var tr = (editBtn || delBtn).closest('tr'); if (!tr) return;
            var rid = tr.getAttribute('data-receipt-id');
            if (delBtn) {
                $.confirm({
                    title: 'Remove receipt?', type: 'red',
                    content: 'This receipt will be removed. Any spend lines linked to it will be unlinked (but not deleted).',
                    buttons: {
                        yes: { text: 'Remove', btnClass: 'btn-danger', action: function () {
                            $.post(PROOT + 'Retirements/removeReceiptAj', { receipt_id: rid }, function (r) {
                                if (r && r.ok) { rsToast('Removed.', 'success'); setTimeout(function(){location.reload();}, 300); }
                                else $.alert({title:'Could not remove', content:(r && r.msg) || 'Server error', type:'red'});
                            }, 'json');
                        }},
                        cancel: function () {}
                    }
                });
                return;
            }
            var current = RCMAP[rid] || {};
            $.confirm({
                title: 'Edit receipt',
                columnClass: 'col-md-7',
                content: receiptFormHtml(current),
                onOpen: wireReceiptTypeToggle,
                buttons: {
                    save: { text: 'Save', btnClass: 'btn-primary', action: function () {
                        return submitReceipt(PROOT + 'Retirements/updateReceiptAj', { receipt_id: rid });
                    }},
                    cancel: function () {}
                }
            });
        });

        // Submit for review
        var subBtn = document.getElementById('btn_submit');
        if (subBtn) subBtn.addEventListener('click', function () {
            $.confirm({
                title: 'Submit for Accountant review?',
                content: 'Once submitted, the retirement is locked until Accountant approves or bounces back.',
                type: 'green',
                buttons: {
                    yes: { text: 'Submit', btnClass: 'btn-success', action: function () {
                        $.post(PROOT + 'Retirements/submitAj', { retirement_id: RETIREMENT_ID }, function (r) {
                            if (r && r.ok) { rsToast(r.msg || 'Submitted.', 'success'); setTimeout(function(){ window.location.href = PROOT + 'Retirements/view/' + RETIREMENT_ID; }, 500); }
                            else $.alert({title:'Could not submit', content:(r && r.msg) || 'Server error', type:'red'});
                        }, 'json');
                    }},
                    cancel: function () {}
                }
            });
        });
    }

    paintTotals({ total_spent: <?= (float)$r['total_spent']; ?>, variance: <?= (float)$r['variance']; ?> });

    <?php if ($isDiscovery && !$locked): ?>
    // ── Batch 4 · findings CRUD ────────────────────────────────────────
    function findingFormHtml(f) {
        f = f || {};
        var opt = function (v, cur) { return '<option value="' + v + '"' + (cur===v?' selected':'') + '>' + v.charAt(0)+v.slice(1).toLowerCase() + '</option>'; };
        return '<form id="fnd_form">' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-8"><label class="form-label small">Supplier name *</label><input name="supplier_name" class="form-control form-control-sm" value="' + (f.supplier_name||'') + '" required></div>' +
              '<div class="col-4"><label class="form-label small">Country</label><input name="country" class="form-control form-control-sm" value="' + (f.country||'') + '"></div>' +
            '</div>' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-4"><label class="form-label small">Contact name</label><input name="contact_name" class="form-control form-control-sm" value="' + (f.contact_name||'') + '"></div>' +
              '<div class="col-4"><label class="form-label small">Phone</label><input name="phone" class="form-control form-control-sm" value="' + (f.phone||'') + '"></div>' +
              '<div class="col-4"><label class="form-label small">Email</label><input name="email" type="email" class="form-control form-control-sm" value="' + (f.email||'') + '"></div>' +
            '</div>' +
            '<div class="mb-2"><label class="form-label small">TIN</label><input name="tin" class="form-control form-control-sm" value="' + (f.tin||'') + '"></div>' +
            '<div class="mb-2"><label class="form-label small">Capability notes</label><textarea name="capability_notes" rows="2" class="form-control form-control-sm">' + (f.capability_notes||'') + '</textarea></div>' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-3"><label class="form-label small">Quote received</label><select name="quote_received" class="form-select form-select-sm"><option value="0"' + (parseInt(f.quote_received||0)===0?' selected':'') + '>No</option><option value="1"' + (parseInt(f.quote_received||0)===1?' selected':'') + '>Yes</option></select></div>' +
              '<div class="col-3"><label class="form-label small">Amount</label><input name="quote_amount" type="number" step="0.01" min="0" class="form-control form-control-sm" value="' + (f.quote_amount||'') + '"></div>' +
              '<div class="col-3"><label class="form-label small">Currency</label><input name="quote_currency" class="form-control form-control-sm" value="' + (f.quote_currency||'<?= $currency; ?>') + '"></div>' +
              '<div class="col-3"><label class="form-label small">Lead time (days)</label><input name="quote_lead_time_days" type="number" min="0" class="form-control form-control-sm" value="' + (f.quote_lead_time_days||'') + '"></div>' +
            '</div>' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-3"><label class="form-label small">Sample received</label><select name="sample_received" class="form-select form-select-sm"><option value="0"' + (parseInt(f.sample_received||0)===0?' selected':'') + '>No</option><option value="1"' + (parseInt(f.sample_received||0)===1?' selected':'') + '>Yes</option></select></div>' +
              '<div class="col-3"><label class="form-label small">Verdict</label><select name="recommendation" class="form-select form-select-sm">' + opt('SHORTLIST', f.recommendation||'MAYBE') + opt('MAYBE', f.recommendation||'MAYBE') + opt('REJECT', f.recommendation||'MAYBE') + '</select></div>' +
              '<div class="col-6"><label class="form-label small">Rationale</label><input name="rationale" class="form-control form-control-sm" value="' + (f.rationale||'') + '" placeholder="Why shortlist / maybe / reject?"></div>' +
            '</div>' +
            '</form>';
    }

    function submitFinding(url, extraFields) {
        var fd = document.getElementById('fnd_form');
        if (!fd.supplier_name.value.trim()) { $.alert({title:'Supplier name required',type:'orange'}); return false; }
        var payload = {
            retirement_id: RETIREMENT_ID,
            supplier_name: fd.supplier_name.value, country: fd.country.value,
            contact_name: fd.contact_name.value, phone: fd.phone.value, email: fd.email.value, tin: fd.tin.value,
            capability_notes: fd.capability_notes.value,
            quote_received: fd.quote_received.value, quote_amount: fd.quote_amount.value,
            quote_currency: fd.quote_currency.value, quote_lead_time_days: fd.quote_lead_time_days.value,
            sample_received: fd.sample_received.value,
            recommendation: fd.recommendation.value, rationale: fd.rationale.value
        };
        Object.assign(payload, extraFields || {});
        $.post(url, payload, 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');
        return false;
    }

    document.getElementById('btn_add_finding').addEventListener('click', function () {
        $.confirm({
            title: 'Add supplier finding',
            columnClass: 'col-md-8',
            content: findingFormHtml(),
            buttons: {
                save: { text: 'Add', btnClass: 'btn-success', action: function () { return submitFinding(PROOT + 'Retirements/addFindingAj'); }},
                cancel: function () {}
            }
        });
    });

    document.getElementById('findings_tbody').addEventListener('click', function (e) {
        var editBtn = e.target.closest('.btn_edit_finding');
        var delBtn  = e.target.closest('.btn_del_finding');
        if (!editBtn && !delBtn) return;
        var tr = (editBtn || delBtn).closest('tr'); if (!tr) return;
        var fid = tr.getAttribute('data-finding-id');
        if (delBtn) {
            $.confirm({
                title: 'Remove supplier?', type: 'red',
                content: 'This supplier profile will be deleted.',
                buttons: {
                    yes: { text: 'Remove', btnClass: 'btn-danger', action: function () {
                        $.post(PROOT + 'Retirements/removeFindingAj', { finding_id: fid }, function (r) {
                            if (r && r.ok) { rsToast('Removed.', 'success'); setTimeout(function(){location.reload();}, 300); }
                            else $.alert({title:'Could not remove', content:(r && r.msg) || 'Server error', type:'red'});
                        }, 'json');
                    }},
                    cancel: function () {}
                }
            });
            return;
        }
        var current = {
            supplier_name: (tr.querySelector('td:first-child strong')||{}).textContent || '',
            country: (tr.querySelector('td:first-child .text-muted')||{}).textContent || '',
            recommendation: (tr.querySelector('.badge')||{}).textContent.trim().toUpperCase(),
        };
        var mapVerdict = { SHORTLIST:'SHORTLIST', MAYBE:'MAYBE', REJECT:'REJECT' };
        current.recommendation = mapVerdict[current.recommendation] || 'MAYBE';
        $.confirm({
            title: 'Edit supplier finding',
            columnClass: 'col-md-8',
            content: findingFormHtml(current),
            buttons: {
                save: { text: 'Save', btnClass: 'btn-primary', action: function () {
                    return submitFinding(PROOT + 'Retirements/updateFindingAj', { finding_id: fid });
                }},
                cancel: function () {}
            }
        });
    });
    <?php endif; ?>
})();
</script>

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