<?php $this->start('body');
    $l        = $this->data['l'];
    $types    = $this->data['types'] ?? [];
    $t        = $types[$l['lpo_type']] ?? ['label'=>$l['lpo_type'],'icon'=>'fas fa-file'];
    $approval = $this->data['approval'] ?? [];
    $steps    = $this->data['steps'] ?? [];
    $history  = $this->data['history'] ?? [];
    $curSid   = (int)($approval['current_step_id'] ?? 0);
    $curNo    = 0; foreach ($steps as $s) if ((int)$s['c0d']===$curSid) $curNo = (int)$s['step_no'];

    // Slice 8Z-d · retirement affordance for internal-cash LPOs.
    $isInternalCash = in_array($l['lpo_type'], Lpos::INTERNAL_CASH_TYPES, true);
    $isDisbursed    = in_array($l['cash_out_status'], ['ISSUED','PAID','RETIRED'], true);
    $retirement     = null;
    if ($isInternalCash && $isDisbursed) {
        $retirement = (new LpoRetirements())->findByLpo((int)$l['c0d']);
    }
    $canRetire = $isInternalCash && $isDisbursed
                 && (int)$l['requested_by'] === (int)($_SESSION['user_id'] ?? 0)
                 && (!$retirement || in_array($retirement['status'], ['DRAFT','REJECTED'], true));

    // Slice 8Z-q · receipt confirmation state (internal-cash only)
    $isRequester       = ((int)$l['requested_by'] === (int)($_SESSION['user_id'] ?? 0));
    $userRoleLower     = strtolower(trim((string)($_SESSION['user_group_name'] ?? '')));
    $isFinancePriv     = in_array($userRoleLower, ['administrator','finance manager','accountant'], true);
    $receiptConfirmed  = !empty($l['receipt_confirmed_at']);
    $canConfirmReceipt = $isInternalCash && !$receiptConfirmed
                         && in_array($l['cash_out_status'], ['PAID','ISSUED'], true)
                         && ($isRequester || $isFinancePriv);
    $retirementDue     = (string)($l['retirement_due_date'] ?? '');
    $daysToDue         = null;
    if ($receiptConfirmed && $retirementDue !== '' && $retirementDue !== '0000-00-00') {
        $daysToDue = (int)floor((strtotime($retirementDue) - strtotime(date('Y-m-d'))) / 86400);
    }

    // Slice 8Z-r · Slice D1 · Supplier LPO payment terms + Issue to supplier
    $isSupplier      = ((string)$l['lpo_type'] === 'SUPPLIER');
    $isProcOrAdmin   = in_array($userRoleLower, ['procurement','administrator'], true);
    $paymentTerms    = $isSupplier ? (new LpoPaymentTerms())->forLpo((int)$l['c0d']) : [];
    $termsLocked     = in_array((string)$l['cash_out_status'], ['ISSUED','PAID','RETIRED','CLOSED','DECLINED'], true);
    $canEditTerms    = $isSupplier && $isProcOrAdmin && !$termsLocked;
    $canIssue        = $isSupplier && $isProcOrAdmin && (string)$l['cash_out_status'] === 'APPROVED';
    $isIssued        = !empty($l['issued_at']);
    $termCoverage    = 0.0; foreach ($paymentTerms as $pt) $termCoverage += (float)$pt['computed_amount'];
    $lpoAmount       = (float)$l['amount'];
    $termCoveragePct = $lpoAmount > 0 ? round(($termCoverage / $lpoAmount) * 100, 1) : 0.0;

    // Slice 8Z-s · Slice D2 · Payment Requests
    $paymentRequests  = $this->data['payment_requests']  ?? [];
    $termAvailability = $this->data['term_availability'] ?? [];
    $canRaisePr       = !empty($this->data['can_raise_pr']);
    $totalClaimed     = 0.0; foreach ($paymentTerms as $pt) $totalClaimed += (float)$pt['claimed_amount'];
    $sc = [
        'DRAFT'     => 'bg-light text-muted',
        'SUBMITTED' => 'bg-info text-white',
        'APPROVED'  => 'bg-success',
        'ISSUED'    => 'bg-primary',
        'PAID'      => 'bg-success',
        'RETIRED'   => 'bg-secondary',
        'CLOSED'    => 'bg-dark',
        'DECLINED'  => 'bg-danger',
    ][$l['cash_out_status']] ?? 'bg-light text-muted';
    $canSubmit = ($l['cash_out_status'] === 'DRAFT');
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <div>
        <h5 class="mb-0" style="font-weight:600;"><i class="<?= $t['icon']; ?> me-2 text-muted"></i>
            <?php if (strpos((string)$l['lpo_no'], 'PENDING-') === 0): ?>
                <span class="badge" style="background:#EDE7DC;color:#5B4F3C;font-size:.7rem;">PENDING</span>
                <span class="text-muted small ms-2" style="font-weight:normal;">real LPO # allocated on Exec approval</span>
            <?php else: ?>
                <?= htmlspecialchars($l['lpo_no']); ?>
            <?php endif; ?>
        </h5>
        <div class="text-muted" style="font-size:.72rem;">
            <?= htmlspecialchars($t['label']); ?> · <?= htmlspecialchars($l['source_module']); ?>
            <?php if (!empty($l['project_no'])): ?> · <a href="<?= PROOT; ?>Projects/view/<?= (int)$l['project_id']; ?>"><?= htmlspecialchars($l['project_no']); ?></a><?php endif; ?>
        </div>
    </div>
    <div class="d-flex align-items-center gap-2">
        <?php if ($receiptConfirmed): ?>
            <?php
                // Retirement countdown / overdue chip (once receipt confirmed)
                $countChip = ['#EAF2E8','#3F5C43','Receipt confirmed'];
                if ($daysToDue !== null) {
                    if ($daysToDue < 0) $countChip = ['#F5EAE1','#C48579','Retirement overdue · ' . abs($daysToDue) . 'd'];
                    elseif ($daysToDue <= 3) $countChip = ['#FEF3E7','#8B6914','Retire in ' . $daysToDue . 'd'];
                    else $countChip = ['#EAF2E8','#3F5C43','Retire in ' . $daysToDue . 'd'];
                }
            ?>
            <span class="badge" style="background:<?= $countChip[0]; ?>;color:<?= $countChip[1]; ?>;border:1px solid <?= $countChip[1]; ?>;font-weight:600;text-transform:capitalize;padding:.4rem .55rem;font-size:.65rem;" title="Confirmed <?= htmlspecialchars((string)$l['receipt_confirmed_at']); ?><?= !empty($l['receipt_confirm_auto']) ? ' (auto)' : ''; ?>">
                <i class="fas fa-check-circle me-1"></i><?= htmlspecialchars($countChip[2]); ?>
            </span>
        <?php endif; ?>
        <?php if ($canConfirmReceipt): ?>
            <button type="button" id="btn_confirm_receipt" class="btn btn-sm" style="background:#8B6914;border-color:#8B6914;color:#fff;font-weight:600;">
                <i class="fas fa-hand-holding-usd me-1"></i>Confirm receipt
            </button>
        <?php endif; ?>
        <?php if ($retirement): ?>
            <?php
                $rsChip = [
                    'DRAFT'     => ['#F1F5F9','#334155','Retirement drafted'],
                    'SUBMITTED' => ['#EEF2F6','#7A8BA1','Retirement submitted'],
                    'APPROVED'  => ['#EAF2E8','#3F5C43','Retirement approved'],
                    'REJECTED'  => ['#F5EAE1','#C48579','Retirement bounced back'],
                ][$retirement['status']] ?? ['#F1F5F9','#334155',$retirement['status']];
            ?>
            <a href="<?= PROOT; ?>Retirements/view/<?= (int)$retirement['c0d']; ?>" class="btn btn-sm text-decoration-none" style="background:<?= $rsChip[0]; ?>;color:<?= $rsChip[1]; ?>;border:1px solid <?= $rsChip[1]; ?>;font-weight:600;">
                <i class="fas fa-file-invoice-dollar me-1"></i><?= htmlspecialchars($rsChip[2]); ?>
            </a>
        <?php endif; ?>
        <?php if ($isSupplier && $isIssued): ?>
            <?php
                $imLbl = ['EMAIL'=>'Email','PORTAL'=>'Portal','WHATSAPP'=>'WhatsApp','COURIER'=>'Courier','IN_PERSON'=>'In-person','OTHER'=>'Other'][$l['issue_method']] ?? (string)$l['issue_method'];
            ?>
            <span class="badge" style="background:#EAF2E8;color:#3F5C43;border:1px solid #3F5C43;font-weight:600;text-transform:capitalize;padding:.4rem .55rem;font-size:.65rem;" title="Issued <?= htmlspecialchars((string)$l['issued_at']); ?><?= !empty($l['issue_ref']) ? ' · ref ' . htmlspecialchars((string)$l['issue_ref']) : ''; ?>">
                <i class="fas fa-paper-plane me-1"></i>Issued &middot; <?= htmlspecialchars($imLbl); ?>
            </span>
        <?php endif; ?>
        <?php if ($canIssue): ?>
            <button type="button" id="btn_issue_supplier" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
                <i class="fas fa-paper-plane me-1"></i>Issue to supplier
            </button>
        <?php endif; ?>
        <?php if ($canRaisePr): ?>
            <button type="button" id="btn_raise_pr" class="btn btn-sm" style="background:#8B6914;border-color:#8B6914;color:#fff;font-weight:600;">
                <i class="fas fa-money-check-alt me-1"></i>Raise Payment Request
            </button>
        <?php endif; ?>
        <?php if ($canRetire): ?>
            <a href="<?= PROOT; ?>Retirements/new/<?= (int)$l['c0d']; ?>" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
                <i class="fas fa-file-invoice-dollar me-1"></i><?= $retirement ? 'Edit retirement' : 'Retire this advance'; ?>
            </a>
        <?php endif; ?>
        <a href="<?= PROOT; ?>Lpos" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Back</a>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-md-3"><div class="card border-0 shadow-sm"><div class="card-body p-2"><div class="text-muted small">Amount</div><div style="font-weight:600;font-size:1.05rem;"><?= htmlspecialchars($l['currency']); ?> <?= number_format((float)$l['amount']); ?></div>
        <?php // Slice 8Z-m · partial pay display
            $paidNow = (float)($l['amount_paid'] ?? 0);
            if ($paidNow > 0 && $paidNow < (float)$l['amount']):
                $remaining = (float)$l['amount'] - $paidNow;
        ?>
            <div class="text-muted small" style="font-size:.6rem;color:#8B6914;">Paid: <?= number_format($paidNow); ?> · Remaining: <strong><?= number_format($remaining); ?></strong></div>
        <?php elseif ($paidNow > 0): ?>
            <div class="text-muted small" style="font-size:.6rem;color:#3F5C43;">Fully paid</div>
        <?php endif; ?>
    </div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm"><div class="card-body p-2"><div class="text-muted small">Payee</div><div style="font-weight:600;"><?= htmlspecialchars($l['payee_name'] ?: '—'); ?></div><div class="text-muted small"><?= htmlspecialchars($l['payee_type']); ?></div></div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm"><div class="card-body p-2"><div class="text-muted small">Requested</div><div style="font-weight:600;"><?= htmlspecialchars($l['requested_by_name']); ?></div><div class="text-muted small"><?= htmlspecialchars($l['requested_on'] ?: ''); ?></div></div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm"><div class="card-body p-2"><div class="text-muted small">Status</div><div><span class="badge <?= $sc; ?>" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$l['cash_out_status']))); ?></span></div></div></div></div>
</div>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Purpose</strong></div>
    <div class="card-body p-3"><?= nl2br(htmlspecialchars($l['purpose'])); ?></div>
</div>

<?php
    // Slice 8Z-k · Disburse block (visible when Accountant has set a plan OR disbursement is done)
    $prefAccount     = $this->data['pref_account'] ?? [];
    $disburseAccount = $this->data['disburse_account'] ?? [];
    $canDisburse     = !empty($this->data['can_disburse']);
    $hasPlan         = !empty($l['disburse_method']) || !empty($l['preferred_method']) || !empty($prefAccount);
    $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'],
    ];
    $mask = function ($s) {
        $s = (string)$s;
        return strlen($s) <= 4 ? $s : str_repeat('•', max(3, strlen($s) - 4)) . substr($s, -4);
    };
?>
<?php if ($hasPlan): ?>
<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-hand-holding-usd me-1 text-muted"></i>Disbursement
        </div>
        <?php if (!empty($l['disbursed_at'])): ?>
            <span class="badge" style="background:#EAF2E8;color:#3F5C43;border:1px solid #3F5C43;font-size:.62rem;">
                <i class="fas fa-check me-1"></i>Disbursed <?= htmlspecialchars(date('d M · H:i', strtotime($l['disbursed_at']))); ?>
            </span>
        <?php elseif ($canDisburse): ?>
            <button type="button" id="btn_mark_disbursed" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
                <i class="fas fa-paper-plane me-1"></i>Mark as disbursed
            </button>
        <?php endif; ?>
    </div>
    <div class="card-body p-3">
        <div class="row g-3">
            <?php if (!empty($l['preferred_method']) || !empty($prefAccount)):
                $pm = (string)($l['preferred_method'] ?? '');
                $pmSel = $pm !== '' ? ($methodChip[$pm] ?? ['#F1F5F9','#334155',$pm]) : null;
            ?>
                <div class="col-md-6">
                    <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Requester preferred</div>
                    <?php if ($pmSel): ?><span class="badge me-1" style="background:<?= $pmSel[0]; ?>;color:<?= $pmSel[1]; ?>;border:1px solid <?= $pmSel[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($pmSel[2]); ?></span><?php endif; ?>
                    <?php if (!empty($prefAccount)): ?>
                        <span class="small"><strong><?= htmlspecialchars($prefAccount['provider_name']); ?></strong> · <code><?= htmlspecialchars($mask($prefAccount['account_number'])); ?></code> · <?= htmlspecialchars($prefAccount['account_holder_name']); ?></span>
                    <?php elseif ($pm === ''): ?>
                        <span class="text-muted small">left to Accountant</span>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
            <?php if (!empty($l['disburse_method'])):
                $dm = (string)$l['disburse_method'];
                $dmSel = $methodChip[$dm] ?? ['#F1F5F9','#334155',$dm];
            ?>
                <div class="col-md-6">
                    <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Accountant confirmed</div>
                    <span class="badge me-1" style="background:<?= $dmSel[0]; ?>;color:<?= $dmSel[1]; ?>;border:1px solid <?= $dmSel[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($dmSel[2]); ?></span>
                    <?php if (!empty($disburseAccount)): ?>
                        <span class="small"><strong><?= htmlspecialchars($disburseAccount['provider_name']); ?></strong> · <code><?= htmlspecialchars($mask($disburseAccount['account_number'])); ?></code> · <?= htmlspecialchars($disburseAccount['account_holder_name']); ?>
                            <?php if ($disburseAccount['status'] === 'PENDING'): ?> <span class="text-muted" style="font-size:.62rem;">(ad-hoc pending FM)</span><?php endif; ?>
                        </span>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
            <?php if (!empty($l['scheduled_disburse_date'])): ?>
                <div class="col-md-3">
                    <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Scheduled</div>
                    <div class="small"><?= htmlspecialchars(date('d M Y', strtotime($l['scheduled_disburse_date']))); ?></div>
                </div>
            <?php endif; ?>
            <?php if (!empty($l['disburse_ref'])): ?>
                <div class="col-md-3">
                    <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Ref / txn ID</div>
                    <div class="small"><code><?= htmlspecialchars($l['disburse_ref']); ?></code></div>
                </div>
            <?php endif; ?>
            <?php if (!empty($l['disbursed_by_name'])): ?>
                <div class="col-md-3">
                    <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Disbursed by</div>
                    <div class="small"><?= htmlspecialchars($l['disbursed_by_name']); ?></div>
                </div>
            <?php endif; ?>
            <?php if (!empty($l['override_reason']) || !empty($l['accountant_prep_notes'])): ?>
                <div class="col-12">
                    <?php if (!empty($l['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"><?= nl2br(htmlspecialchars($l['override_reason'])); ?></div>
                    <?php endif; ?>
                    <?php if (!empty($l['accountant_prep_notes'])): ?>
                        <div class="text-muted small" style="font-size:.62rem;font-weight:600;text-transform:capitalize;">Accountant notes</div>
                        <div class="small"><?= nl2br(htmlspecialchars($l['accountant_prep_notes'])); ?></div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if ($canDisburse): ?>
<script>
(function () {
    var LPO_ID = <?= (int)$l['c0d']; ?>;
    var METHOD = <?= json_encode((string)$l['disburse_method']); ?>;
    var b = document.getElementById('btn_mark_disbursed');
    if (!b) return;
    b.addEventListener('click', function () {
        var refLabel = (METHOD === 'MOBILE_MONEY') ? 'M-Pesa / mobile-money transaction ID'
                     : (METHOD === 'BANK_TRANSFER') ? 'Bank reference / TIPS ID'
                     : (METHOD === 'CHEQUE')       ? 'Cheque number'
                     : 'Reference (optional)';
        $.confirm({
            title: 'Mark this LPO as disbursed?',
            content: '<div class="small mb-2">This flips the LPO to PAID and notifies the requester that cash is on the way.</div>' +
                     '<label class="form-label small">' + refLabel + '</label>' +
                     '<input id="md_ref" class="form-control form-control-sm" placeholder="e.g. QK7HFR9L2X">',
            type: 'green',
            buttons: {
                yes: { text: 'Mark disbursed', btnClass: 'btn-success', action: function () {
                    var ref = document.getElementById('md_ref').value || '';
                    $.post('<?= PROOT; ?>Lpos/markDisbursedAj', { lpo_id: LPO_ID, disburse_ref: ref }, function (r) {
                        if (r && r.ok) { rsToast('Marked disbursed.', 'success'); setTimeout(function(){location.reload();}, 500); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json').fail(function () { $.alert({title:'Network error', type:'red'}); });
                }},
                cancel: function () {}
            }
        });
    });
})();
</script>
<?php endif; ?>

<?php if ($canConfirmReceipt): ?>
<script>
(function () {
    var LPO_ID = <?= (int)$l['c0d']; ?>;
    var b = document.getElementById('btn_confirm_receipt');
    if (!b) return;
    b.addEventListener('click', function () {
        $.confirm({
            title: 'Confirm receipt of cash?',
            content: '<div class="small mb-2">This tells Finance the money actually arrived. The retirement clock starts now — you have <strong>14 days</strong> from confirmation to file your retirement.</div>' +
                     '<label class="form-label small">Optional note</label>' +
                     '<input id="rc_note" class="form-control form-control-sm" placeholder="e.g. Received in cash from Accountant on 2026-08-21">',
            type: 'orange',
            buttons: {
                yes: { text: 'Confirm receipt', btnClass: 'btn-warning', action: function () {
                    var note = document.getElementById('rc_note').value || '';
                    $.post('<?= PROOT; ?>Lpos/confirmReceiptAj', { lpo_id: LPO_ID, note: note }, function (r) {
                        if (r && r.ok) { rsToast('Receipt confirmed. Retirement due ' + r.retirement_due_date + '.', 'success'); setTimeout(function(){location.reload();}, 700); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json').fail(function () { $.alert({title:'Network error', type:'red'}); });
                }},
                cancel: function () {}
            }
        });
    });
})();
</script>
<?php endif; ?>

<?php if (($l['supplier_receipt_type'] ?? 'NORMAL') !== 'NORMAL' || (float)($l['vat_amount'] ?? 0) > 0): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong><i class="fas fa-print me-2 text-muted"></i>Supplier fiscal receipt · VAT capture</strong></div>
    <div class="card-body p-3">
        <div class="row g-3">
            <div class="col-md-3">
                <div class="text-muted small">Receipt type</div>
                <div>
                    <?php
                        $srt = $l['supplier_receipt_type'] ?? 'NORMAL';
                        $srtCls = ['SUPPLIER_EFD_VAT'=>'bg-success','SUPPLIER_EFD_NON_VAT'=>'bg-info text-white','NORMAL'=>'bg-light text-muted'][$srt] ?? 'bg-light text-muted';
                    ?>
                    <span class="badge <?= $srtCls; ?>" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$srt))); ?></span>
                </div>
            </div>
            <div class="col-md-3">
                <div class="text-muted small">Supplier EFD #</div>
                <div style="font-weight:600;"><?= htmlspecialchars($l['supplier_efd_number'] ?: '—'); ?></div>
            </div>
            <div class="col-md-3">
                <div class="text-muted small">Supplier TIN</div>
                <div><code class="text-body"><?= htmlspecialchars($l['supplier_tin'] ?: '—'); ?></code></div>
            </div>
            <div class="col-md-3">
                <div class="text-muted small">EFD date</div>
                <div><?= htmlspecialchars($l['supplier_efd_date'] ?: '—'); ?></div>
            </div>
            <div class="col-md-3">
                <div class="text-muted small">Net (expense)</div>
                <div style="font-weight:600;"><?= htmlspecialchars($l['currency']); ?> <?= number_format((float)$l['net_amount']); ?></div>
            </div>
            <div class="col-md-3">
                <div class="text-muted small">Input VAT (claimable)</div>
                <div style="font-weight:600;color:<?= (float)$l['vat_amount']>0?'#22c55e':''; ?>;"><?= htmlspecialchars($l['currency']); ?> <?= number_format((float)$l['vat_amount']); ?></div>
            </div>
            <div class="col-md-3">
                <div class="text-muted small">VAT treatment</div>
                <div><?= (int)$l['vat_inclusive_flag'] === 1 ? 'Inclusive' : 'Exclusive'; ?></div>
            </div>
            <div class="col-md-3">
                <div class="text-muted small">Total paid</div>
                <div style="font-weight:600;font-size:1.05rem;"><?= htmlspecialchars($l['currency']); ?> <?= number_format((float)$l['amount']); ?></div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<?php
    $lpoItems   = $this->data['lpo_items'] ?? [];
    $grns       = $this->data['grns']      ?? [];
    $canReceive = !empty($this->data['can_receive']);
    $rsCls = ['NOT_RECEIVED'=>'bg-light text-muted','PARTIALLY_RECEIVED'=>'bg-warning text-dark','FULLY_RECEIVED'=>'bg-success','OVER_RECEIVED'=>'bg-danger'][$l['receipt_status'] ?? 'NOT_RECEIVED'] ?? 'bg-light text-muted';
?>

<?php if ($isSupplier): ?>
<?php
    $termChip = [
        'ADVANCE'     => ['#FEF3E7','#8B6914','Advance'],
        'ON_ORDER'    => ['#FEF3E7','#8B6914','On order'],
        'ON_DELIVERY' => ['#EAF2E8','#3F5C43','On delivery'],
        'RETENTION'   => ['#EEF2F6','#7A8BA1','Retention'],
        'NET_DAYS'    => ['#EEF2F6','#7A8BA1','Net days'],
        'MILESTONE'   => ['#F5EAE1','#C48579','Milestone'],
    ];
    $coverageCol = ($termCoveragePct >= 99.5 && $termCoveragePct <= 100.5)
        ? ['#EAF2E8','#3F5C43']
        : (($termCoveragePct === 0.0) ? ['#F5EAE1','#C48579'] : ['#FEF3E7','#8B6914']);
?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <strong><i class="fas fa-file-contract me-2 text-muted"></i>Payment terms
            <span class="badge ms-2" style="background:<?= $coverageCol[0]; ?>;color:<?= $coverageCol[1]; ?>;border:1px solid <?= $coverageCol[1]; ?>;font-size:.62rem;text-transform:capitalize;">
                <?= number_format($termCoveragePct, 1); ?>% covered
            </span>
            <?php if ($termsLocked): ?><span class="badge bg-light text-muted ms-1" style="font-size:.6rem;"><i class="fas fa-lock me-1"></i>Locked</span><?php endif; ?>
        </strong>
        <?php if ($canEditTerms): ?>
            <button type="button" class="btn btn-sm" id="btn_add_term" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
                <i class="fas fa-plus me-1"></i>Add term
            </button>
        <?php endif; ?>
    </div>
    <?php if (!empty($paymentTerms)): ?>
        <div class="table-responsive">
            <table class="table table-sm mb-0 align-middle">
                <thead class="table-light">
                    <tr>
                        <th style="width:36px;">#</th>
                        <th>Label</th>
                        <th style="width:120px;">Trigger</th>
                        <th class="text-end" style="width:90px;">%</th>
                        <th class="text-end" style="width:130px;">Amount</th>
                        <th style="width:180px;">Condition</th>
                        <?php if ($canEditTerms): ?><th class="text-end" style="width:70px;"></th><?php endif; ?>
                    </tr>
                </thead>
                <tbody id="terms_tbody">
                    <?php foreach ($paymentTerms as $pt):
                        $tc = $termChip[$pt['trigger_type']] ?? $termChip['ON_DELIVERY'];
                    ?>
                        <tr data-term-id="<?= (int)$pt['c0d']; ?>">
                            <td class="text-muted small"><?= (int)$pt['seq_no']; ?></td>
                            <td class="small">
                                <strong><?= htmlspecialchars($pt['label']); ?></strong>
                                <?php if (!empty($pt['notes'])): ?><div class="text-muted" style="font-size:.62rem;"><?= htmlspecialchars($pt['notes']); ?></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 text-muted"><?= $pt['percent'] !== null ? number_format((float)$pt['percent'], (fmod((float)$pt['percent'],1)==0?0:1)) . '%' : '—'; ?></td>
                            <td class="text-end small" style="font-weight:600;color:#334155;"><?= htmlspecialchars($l['currency']); ?> <?= number_format((float)$pt['computed_amount']); ?></td>
                            <td class="small text-muted" style="font-size:.65rem;">
                                <?php
                                    switch ($pt['trigger_type']) {
                                        case 'ON_DELIVERY': echo 'GRN &ge; <strong>' . number_format((float)($pt['grn_percent_gate'] ?? 100), 0) . '%</strong>'; break;
                                        case 'RETENTION':   echo (int)($pt['retention_days'] ?? 0) . 'd after fully received'; break;
                                        case 'NET_DAYS':    echo 'Net <strong>' . (int)($pt['net_days'] ?? 30) . 'd</strong> from invoice'; break;
                                        case 'MILESTONE':   echo !empty($pt['milestone_condition']) ? htmlspecialchars(mb_strimwidth((string)$pt['milestone_condition'], 0, 60, '…')) : '<em>—</em>'; break;
                                        case 'ADVANCE':     echo 'Before issue'; break;
                                        case 'ON_ORDER':    echo 'At issue'; break;
                                        default: echo '—';
                                    }
                                ?>
                            </td>
                            <?php if ($canEditTerms): ?>
                                <td class="text-end">
                                    <button type="button" class="btn btn-sm btn-link p-0 me-1 btn_edit_term" 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_term text-danger" title="Remove"><i class="fas fa-times"></i></button>
                                </td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <div class="card-footer d-flex justify-content-between py-2 small" style="background:#F8FAFC;">
            <span class="text-muted">Total covered</span>
            <span>
                <strong style="color:#334155;"><?= htmlspecialchars($l['currency']); ?> <?= number_format($termCoverage); ?></strong>
                <span class="text-muted mx-1">of</span>
                <strong><?= htmlspecialchars($l['currency']); ?> <?= number_format($lpoAmount); ?></strong>
            </span>
        </div>
    <?php else: ?>
        <div class="card-body p-3 text-muted small">
            No payment terms yet.
            <?php if ($canEditTerms): ?>
                Add at least one before issuing to the supplier — e.g. <em>30% Advance · 70% On Delivery</em>.
            <?php else: ?>
                Terms will govern which Payment Requests Procurement can raise (Slice D2).
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<?php if ($isIssued): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <strong><i class="fas fa-paper-plane me-2 text-muted"></i>Issued to supplier</strong>
        <?php if (!empty($l['issue_attachment_path'])): ?>
            <a href="<?= PROOT; ?>Lpos/issueAttachmentDownload/<?= (int)$l['c0d']; ?>" target="_blank" class="btn btn-sm btn-outline-secondary" title="<?= htmlspecialchars((string)$l['issue_attachment_original_name']); ?>">
                <i class="fas fa-paperclip me-1"></i>Signed LPO
            </a>
        <?php endif; ?>
    </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;text-transform:capitalize;">Method</div><div class="small" style="font-weight:600;text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ', (string)$l['issue_method']))); ?></div></div>
            <div class="col-md-3"><div class="text-muted small" style="font-size:.62rem;text-transform:capitalize;">Ref</div><div class="small"><code><?= htmlspecialchars((string)($l['issue_ref'] ?: '—')); ?></code></div></div>
            <div class="col-md-3"><div class="text-muted small" style="font-size:.62rem;text-transform:capitalize;">Issued on</div><div class="small"><?= htmlspecialchars((string)$l['issued_at']); ?></div></div>
            <div class="col-md-3"><div class="text-muted small" style="font-size:.62rem;text-transform:capitalize;">Issued by</div><div class="small"><?= htmlspecialchars((string)$l['issued_by_name']); ?></div></div>
            <?php if (!empty($l['issue_note'])): ?>
                <div class="col-12"><div class="text-muted small" style="font-size:.62rem;text-transform:capitalize;">Note</div><div class="small"><?= nl2br(htmlspecialchars((string)$l['issue_note'])); ?></div></div>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<?php
    // Slice 8Z-s · Slice D2 · Payment Requests history card
    $prStatusChip = [
        'DRAFT'        => ['#F1F5F9','#334155','Draft'],
        'SUBMITTED'    => ['#EEF2F6','#7A8BA1','Submitted'],
        'PC_CONFIRMED' => ['#EEF2F6','#7A8BA1','PC confirmed'],
        'PM_REVIEWED'  => ['#EEF2F6','#7A8BA1','PM reviewed'],
        'SCHEDULED'    => ['#FEF3E7','#8B6914','Scheduled'],
        'PAID'         => ['#EAF2E8','#3F5C43','Paid'],
        'REJECTED'     => ['#F5EAE1','#C48579','Rejected'],
        'CANCELLED'    => ['#F1F5F9','#334155','Cancelled'],
    ];
?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <strong><i class="fas fa-money-check-alt me-2 text-muted"></i>Payment Requests
            <span class="text-muted ms-2" style="font-weight:400;font-size:.7rem;"><?= count($paymentRequests); ?> raised &middot; claimed <?= htmlspecialchars($l['currency']); ?> <?= number_format($totalClaimed); ?></span>
        </strong>
        <?php if ($canRaisePr): ?>
            <button type="button" class="btn btn-sm" id="btn_raise_pr_inline" style="background:#8B6914;border-color:#8B6914;color:#fff;font-weight:600;">
                <i class="fas fa-plus me-1"></i>Raise PR
            </button>
        <?php endif; ?>
    </div>
    <?php if (empty($paymentRequests)): ?>
        <div class="card-body p-3 text-muted small">
            No Payment Requests raised yet.
            <?php if ($canRaisePr): ?>
                Click <strong>Raise PR</strong> above to claim against one of the payment terms.
            <?php elseif (empty($paymentTerms)): ?>
                Add payment terms first, then Procurement can raise a PR.
            <?php endif; ?>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-sm mb-0 align-middle">
                <thead class="table-light">
                    <tr>
                        <th>PR #</th>
                        <th class="text-end">Amount</th>
                        <th>Raised on</th>
                        <th>Status</th>
                        <th>Next</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($paymentRequests as $pr):
                        $ps = $prStatusChip[$pr['status']] ?? ['#F1F5F9','#334155',$pr['status']];
                        $nextLbl = ['PC_CONFIRM'=>'PC confirm','PM_REVIEW'=>'PM review','FM_SCHEDULE'=>'FM schedule','ACCT_RECORD'=>'Accountant'][$pr['next_check_status']] ?? '&mdash;';
                    ?>
                        <tr>
                            <td class="small"><a href="<?= PROOT; ?>PaymentRequests/view/<?= (int)$pr['c0d']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars($pr['pr_no']); ?></strong></a>
                                <?php if (!empty($pr['supplier_invoice_no'])): ?><div class="text-muted" style="font-size:.6rem;">Inv <?= htmlspecialchars((string)$pr['supplier_invoice_no']); ?></div><?php endif; ?>
                            </td>
                            <td class="text-end small" style="font-weight:600;color:#334155;"><?= htmlspecialchars($pr['currency']); ?> <?= number_format((float)$pr['requested_amount']); ?></td>
                            <td class="small text-muted"><?= htmlspecialchars((string)$pr['raised_on']); ?><div style="font-size:.6rem;"><?= htmlspecialchars((string)$pr['raised_by_name']); ?></div></td>
                            <td><span class="badge" style="background:<?= $ps[0]; ?>;color:<?= $ps[1]; ?>;border:1px solid <?= $ps[1]; ?>;font-size:.6rem;text-transform:capitalize;"><?= htmlspecialchars($ps[2]); ?></span></td>
                            <td class="small text-muted" style="text-transform:capitalize;"><?= $nextLbl; ?></td>
                            <td class="text-end"><a href="<?= PROOT; ?>PaymentRequests/view/<?= (int)$pr['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-right"></i></a></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>
<?php endif; ?>
<?php if (!empty($lpoItems) || $canReceive): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <strong><i class="fas fa-boxes me-2 text-muted"></i>Line items · receipt status
            <span class="badge <?= $rsCls; ?> ms-2" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$l['receipt_status'] ?? 'NOT_RECEIVED'))); ?></span>
        </strong>
        <?php if ($canReceive): ?>
            <a href="<?= PROOT; ?>GoodsGrn/receive/<?= (int)$l['c0d']; ?>" class="btn btn-sm btn-primary" style="background:<?= BRAND_COLOR; ?>;border-color:<?= BRAND_COLOR; ?>;">
                <i class="fas fa-truck-loading me-1"></i> Record GRN
            </a>
        <?php endif; ?>
    </div>
    <?php if (!empty($lpoItems)): ?>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr><th style="width:40px;">#</th><th>Description</th><th class="text-end">Ordered</th><th class="text-end">Received</th><th class="text-end">Balance</th><th class="text-end">Unit price</th><th class="text-end">Line total</th></tr>
            </thead>
            <tbody>
                <?php foreach ($lpoItems as $li):
                    $ord = (float)$li['qty'];
                    $rec = (float)$li['qty_received'];
                    $bal = round($ord - $rec, 4);
                ?>
                    <tr>
                        <td class="text-muted"><?= (int)$li['item_no']; ?></td>
                        <td><?= htmlspecialchars($li['description']); ?></td>
                        <td class="text-end"><?= number_format($ord, (fmod($ord,1)==0?0:2)); ?> <span class="text-muted small"><?= htmlspecialchars($li['unit']); ?></span></td>
                        <td class="text-end" style="color:<?= $rec>0?'#22c55e':''; ?>;font-weight:600;"><?= number_format($rec, (fmod($rec,1)==0?0:2)); ?></td>
                        <td class="text-end" style="color:<?= $bal>0?'#f59e0b':'#22c55e'; ?>;font-weight:600;"><?= number_format($bal, (fmod($bal,1)==0?0:2)); ?></td>
                        <td class="text-end text-muted"><?= number_format((float)$li['unit_price']); ?></td>
                        <td class="text-end"><?= number_format((float)$li['line_total']); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<?php if (!empty($grns)): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong><i class="fas fa-truck-loading me-2 text-muted"></i>GRNs against this LPO</strong></div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr><th>GRN #</th><th>Received on</th><th>Supplier delivery ref</th><th>Received by</th><th>Condition</th><th></th></tr>
            </thead>
            <tbody>
                <?php foreach ($grns as $g): ?>
                    <tr>
                        <td><a href="<?= PROOT; ?>GoodsGrn/view/<?= (int)$g['c0d']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars($g['grn_no']); ?></strong></a></td>
                        <td class="text-muted small"><?= htmlspecialchars($g['received_on']); ?></td>
                        <td class="text-muted"><?= htmlspecialchars($g['supplier_delivery_note_ref'] ?: '—'); ?></td>
                        <td class="text-muted"><?= htmlspecialchars($g['received_by_name']); ?></td>
                        <td>
                            <?php if ((int)$g['condition_ok']===1): ?>
                                <span class="badge bg-success"><i class="fas fa-check me-1"></i>OK</span>
                            <?php else: ?>
                                <span class="badge bg-warning text-dark"><i class="fas fa-exclamation-triangle me-1"></i>Issues</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end"><a href="<?= PROOT; ?>GoodsGrn/view/<?= (int)$g['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-right"></i></a></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<?php if (!empty($approval)): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <strong><i class="fas fa-stream me-2 text-muted"></i>Approval Chain</strong>
        <a href="<?= PROOT; ?>FinChains/view/<?= (int)$approval['c0d']; ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-arrow-right me-1"></i> Open approval</a>
    </div>
    <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 = ($approval['status'] === 'APPROVED') ? 'done'
                    : (($approval['status'] === 'IN_PROGRESS' && $n < $curNo) ? 'done'
                    : (($approval['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;"><?= 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>
<?php elseif ($canSubmit): ?>
    <div class="card border-0 shadow-sm mb-3">
        <div class="card-body p-3 d-flex align-items-center justify-content-between">
            <div class="text-muted small">This LPO is in <code>DRAFT</code>. Submit for approval to send it into the queue.</div>
            <button type="button" class="btn btn-sm btn-primary" style="background:<?= BRAND_COLOR; ?>;border-color:<?= BRAND_COLOR; ?>;" onclick="rsSubmitLpo(<?= (int)$l['c0d']; ?>)">
                <i class="fas fa-paper-plane me-1"></i> Submit for approval
            </button>
        </div>
    </div>
<?php endif; ?>

<?php
    $pvs       = $this->data['pvs']         ?? [];
    $canPrepPv = !empty($this->data['can_prep_pv']);
?>
<?php if (!empty($pvs) || $canPrepPv): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <strong><i class="fas fa-money-check-alt me-2 text-muted"></i>Payment Vouchers</strong>
        <?php if ($canPrepPv): ?>
            <button type="button" class="btn btn-sm btn-primary" style="background:<?= BRAND_COLOR; ?>;border-color:<?= BRAND_COLOR; ?>;" onclick="rsPrepPvFromLpo(<?= (int)$l['c0d']; ?>)">
                <i class="fas fa-file-invoice-dollar me-1"></i> Prepare PV
            </button>
        <?php endif; ?>
    </div>
    <?php if (!empty($pvs)): ?>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr><th>PV #</th><th>Status</th><th>Scheduled</th><th>Paid</th><th>Reference</th><th class="text-end">Amount</th><th></th></tr>
            </thead>
            <tbody>
                <?php foreach ($pvs as $pv):
                    $sc = ['DRAFT'=>'bg-light text-muted','SCHEDULED'=>'bg-info text-white','PAID'=>'bg-success','CANCELLED'=>'bg-secondary'][$pv['status']] ?? 'bg-light text-muted';
                ?>
                    <tr>
                        <td><a href="<?= PROOT; ?>PaymentVouchers/view/<?= (int)$pv['c0d']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars($pv['pv_no']); ?></strong></a></td>
                        <td><span class="badge <?= $sc; ?>" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower($pv['status'])); ?></span></td>
                        <td class="text-muted small"><?= htmlspecialchars($pv['scheduled_on'] ?: '—'); ?></td>
                        <td class="text-muted small"><?= htmlspecialchars($pv['paid_on'] ?: '—'); ?></td>
                        <td class="text-muted"><?= htmlspecialchars($pv['reference_no'] ?: '—'); ?></td>
                        <td class="text-end"><?= htmlspecialchars($l['currency']); ?> <?= number_format((float)$pv['amount']); ?></td>
                        <td class="text-end"><a href="<?= PROOT; ?>PaymentVouchers/view/<?= (int)$pv['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-right"></i></a></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
        <div class="card-body p-3 text-muted small">No PV drafted yet. Prepare one to move this into the payments queue.</div>
    <?php endif; ?>
</div>
<?php endif; ?>

<script>
function rsPrepPvFromLpo(lpoId) {
    if (!confirm('Draft a Payment Voucher against this LPO?')) return;
    fetch('<?= PROOT; ?>PaymentVouchers/prepAj', {
        method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'lpo_id=' + encodeURIComponent(lpoId)
    }).then(r=>r.json()).then(j=>{
        if (!j.ok) { alert(j.msg||'Failed'); return; }
        window.location = '<?= PROOT; ?>PaymentVouchers/view/' + j.id;
    });
}
function rsSubmitLpo(lid) {
    if (!confirm('Submit this LPO for approval?')) return;
    fetch('<?= PROOT; ?>Lpos/submitAj', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'lpo_id=' + encodeURIComponent(lid)
    }).then(r => r.json()).then(j => {
        alert(j.msg || (j.ok?'Submitted':'Failed'));
        if (j.ok) location.reload();
    });
}
</script>

<?php if ($isSupplier && ($canEditTerms || $canIssue)): ?>
<script>
(function () {
    var LPO_ID   = <?= (int)$l['c0d']; ?>;
    var PROOT    = '<?= PROOT; ?>';
    var CURRENCY = <?= json_encode((string)$l['currency']); ?>;
    var LPO_AMT  = <?= (float)$lpoAmount; ?>;

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

    <?php if ($canEditTerms): ?>
    // ── Payment terms CRUD ─────────────────────────────────────────────
    function termFormHtml(pt) {
        pt = pt || {};
        var trig = pt.trigger_type || 'ON_DELIVERY';
        function opt(v, lbl, cur) { return '<option value="' + v + '"' + (cur===v?' selected':'') + '>' + lbl + '</option>'; }
        var trigSel = '<select name="trigger_type" id="tt_trigger" class="form-select form-select-sm">' +
            opt('ADVANCE','Advance (before issue)',trig) +
            opt('ON_ORDER','On order (at issue)',trig) +
            opt('ON_DELIVERY','On delivery',trig) +
            opt('RETENTION','Retention',trig) +
            opt('NET_DAYS','Net days after invoice',trig) +
            opt('MILESTONE','Milestone (custom)',trig) +
        '</select>';
        var pct   = pt.percent != null ? pt.percent : '';
        var fixed = pt.fixed_amount != null ? pt.fixed_amount : '';
        return '<form id="tt_form">' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-5"><label class="form-label small">Trigger *</label>' + trigSel + '</div>' +
              '<div class="col-7"><label class="form-label small">Label *</label><input name="label" class="form-control form-control-sm" value="' + esc(pt.label||'') + '" placeholder="e.g. Advance 30%"></div>' +
            '</div>' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-6"><label class="form-label small">Percent (0–100)</label><input name="percent" id="tt_pct" type="number" step="0.01" min="0" max="100" class="form-control form-control-sm" value="' + pct + '"></div>' +
              '<div class="col-6"><label class="form-label small">…or Fixed amount</label><input name="fixed_amount" id="tt_fixed" type="number" step="0.01" min="0" class="form-control form-control-sm" value="' + fixed + '"></div>' +
            '</div>' +
            '<div class="row g-2 mb-2" id="tt_on_delivery" style="display:' + (trig==='ON_DELIVERY'?'flex':'none') + ';">' +
              '<div class="col-6"><label class="form-label small">GRN % gate</label><input name="grn_percent_gate" type="number" min="0" max="100" class="form-control form-control-sm" value="' + (pt.grn_percent_gate != null ? pt.grn_percent_gate : 100) + '"></div>' +
              '<div class="col-6"><div class="small text-muted" style="padding-top:1.7rem;font-size:.62rem;">Claimable once GRN qty reaches this %.</div></div>' +
            '</div>' +
            '<div class="row g-2 mb-2" id="tt_net" style="display:' + (trig==='NET_DAYS'?'flex':'none') + ';">' +
              '<div class="col-6"><label class="form-label small">Net days *</label><input name="net_days" type="number" min="0" class="form-control form-control-sm" value="' + (pt.net_days != null ? pt.net_days : 30) + '"></div>' +
            '</div>' +
            '<div class="row g-2 mb-2" id="tt_ret" style="display:' + (trig==='RETENTION'?'flex':'none') + ';">' +
              '<div class="col-6"><label class="form-label small">Retention days *</label><input name="retention_days" type="number" min="0" class="form-control form-control-sm" value="' + (pt.retention_days != null ? pt.retention_days : 90) + '"></div>' +
            '</div>' +
            '<div class="mb-2" id="tt_ms" style="display:' + (trig==='MILESTONE'?'block':'none') + ';">' +
              '<label class="form-label small">Milestone condition *</label><input name="milestone_condition" class="form-control form-control-sm" value="' + esc(pt.milestone_condition||'') + '" placeholder="e.g. FAT sign-off received">' +
            '</div>' +
            '<div class="mb-2"><label class="form-label small">Notes</label><input name="notes" class="form-control form-control-sm" value="' + esc(pt.notes||'') + '"></div>' +
        '</form>';
    }
    function wireTermToggle() {
        var sel = document.getElementById('tt_trigger'); if (!sel) return;
        sel.addEventListener('change', function () {
            document.getElementById('tt_on_delivery').style.display = (sel.value==='ON_DELIVERY') ? 'flex' : 'none';
            document.getElementById('tt_net').style.display         = (sel.value==='NET_DAYS')    ? 'flex' : 'none';
            document.getElementById('tt_ret').style.display         = (sel.value==='RETENTION')   ? 'flex' : 'none';
            document.getElementById('tt_ms').style.display          = (sel.value==='MILESTONE')   ? 'block': 'none';
        });
        // Live percent<->amount echo
        var pct = document.getElementById('tt_pct'), fx = document.getElementById('tt_fixed');
        if (pct) pct.addEventListener('input', function () { if (pct.value !== '') fx.value = ''; });
        if (fx)  fx.addEventListener('input',  function () { if (fx.value  !== '') pct.value = ''; });
    }
    function submitTerm(url, extra) {
        var form = document.getElementById('tt_form');
        var payload = {
            lpo_id: LPO_ID,
            trigger_type:        form.trigger_type.value,
            label:               form.label.value,
            percent:             form.percent.value,
            fixed_amount:        form.fixed_amount.value,
            net_days:            form.net_days ? form.net_days.value : '',
            retention_days:      form.retention_days ? form.retention_days.value : '',
            milestone_condition: form.milestone_condition ? form.milestone_condition.value : '',
            grn_percent_gate:    form.grn_percent_gate ? form.grn_percent_gate.value : '',
            notes:               form.notes.value,
        };
        Object.assign(payload, extra || {});
        $.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_term').addEventListener('click', function () {
        $.confirm({
            title: 'Add payment term',
            columnClass: 'col-md-7',
            content: termFormHtml(),
            onOpen: wireTermToggle,
            buttons: {
                save: { text: 'Add', btnClass: 'btn-success', action: function () { return submitTerm(PROOT + 'Lpos/addPaymentTermAj'); }},
                cancel: function () {}
            }
        });
    });
    // Row-level actions
    var TERMS_JSON = <?= json_encode(array_values(array_map(function ($t) {
        return [
            'c0d'                 => (int)$t['c0d'],
            'label'               => (string)$t['label'],
            'trigger_type'        => (string)$t['trigger_type'],
            'percent'             => $t['percent']      !== null ? (float)$t['percent'] : null,
            'fixed_amount'        => $t['fixed_amount'] !== null ? (float)$t['fixed_amount'] : null,
            'net_days'            => $t['net_days']       !== null ? (int)$t['net_days']       : null,
            'retention_days'      => $t['retention_days'] !== null ? (int)$t['retention_days'] : null,
            'grn_percent_gate'    => $t['grn_percent_gate'] !== null ? (float)$t['grn_percent_gate'] : null,
            'milestone_condition' => (string)($t['milestone_condition'] ?? ''),
            'notes'               => (string)($t['notes'] ?? ''),
        ];
    }, $paymentTerms))); ?>;
    var TMAP = {}; TERMS_JSON.forEach(function (t) { TMAP[t.c0d] = t; });
    var tbody = document.getElementById('terms_tbody');
    if (tbody) tbody.addEventListener('click', function (e) {
        var editBtn = e.target.closest('.btn_edit_term');
        var delBtn  = e.target.closest('.btn_del_term');
        if (!editBtn && !delBtn) return;
        var tr = (editBtn || delBtn).closest('tr'); if (!tr) return;
        var tid = tr.getAttribute('data-term-id');
        if (delBtn) {
            $.confirm({
                title: 'Remove term?', type: 'red',
                content: 'This payment term will be removed. Payment Request availability will recompute.',
                buttons: {
                    yes: { text: 'Remove', btnClass: 'btn-danger', action: function () {
                        $.post(PROOT + 'Lpos/removePaymentTermAj', { term_id: tid }, 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 = TMAP[tid] || {};
        $.confirm({
            title: 'Edit payment term',
            columnClass: 'col-md-7',
            content: termFormHtml(current),
            onOpen: wireTermToggle,
            buttons: {
                save: { text: 'Save', btnClass: 'btn-primary', action: function () { return submitTerm(PROOT + 'Lpos/updatePaymentTermAj', { term_id: tid }); }},
                cancel: function () {}
            }
        });
    });
    <?php endif; ?>

    <?php if ($canIssue): ?>
    // ── Issue to supplier dialog ───────────────────────────────────────
    var b = document.getElementById('btn_issue_supplier');
    if (b) b.addEventListener('click', function () {
        <?php if (empty($paymentTerms)): ?>
        $.confirm({
            title: 'Add payment terms first',
            content: 'Add at least one payment term before issuing this LPO to the supplier.',
            type: 'orange',
            buttons: { ok: function () {} }
        });
        return;
        <?php endif; ?>
        <?php if (abs($termCoveragePct - 100) > 0.5): ?>
        var okConfirm = confirm('Payment terms currently cover <?= number_format($termCoveragePct, 1); ?>% of the LPO amount. Continue anyway?');
        if (!okConfirm) return;
        <?php endif; ?>
        $.confirm({
            title: 'Issue LPO to supplier',
            columnClass: 'col-md-6',
            content:
                '<div class="small mb-2 text-muted">This flips the LPO to <strong>ISSUED</strong> and stamps how you sent it. No email is sent — audit only.</div>' +
                '<form id="iss_form" enctype="multipart/form-data">' +
                '  <div class="row g-2 mb-2">' +
                '    <div class="col-5"><label class="form-label small">Method *</label>' +
                '      <select name="issue_method" class="form-select form-select-sm">' +
                '        <option value="EMAIL">Email</option>' +
                '        <option value="PORTAL">Supplier portal</option>' +
                '        <option value="WHATSAPP">WhatsApp</option>' +
                '        <option value="COURIER">Courier</option>' +
                '        <option value="IN_PERSON">In-person</option>' +
                '        <option value="OTHER">Other</option>' +
                '      </select></div>' +
                '    <div class="col-7"><label class="form-label small">Reference</label>' +
                '      <input name="issue_ref" class="form-control form-control-sm" placeholder="email msg id / tracking # / thread ref"></div>' +
                '  </div>' +
                '  <div class="mb-2"><label class="form-label small">Note</label><input name="issue_note" class="form-control form-control-sm" placeholder="e.g. Copied A. Musa via email"></div>' +
                '  <div class="mb-2"><label class="form-label small">Signed LPO PDF (optional)</label><input type="file" name="attachment" class="form-control form-control-sm" accept=".pdf,image/*,.doc,.docx"></div>' +
                '</form>',
            type: 'green',
            buttons: {
                yes: { text: 'Issue', btnClass: 'btn-success', action: function () {
                    var form = document.getElementById('iss_form');
                    var fd = new FormData(form);
                    fd.append('lpo_id', LPO_ID);
                    $.ajax({
                        url: PROOT + 'Lpos/issueToSupplierAj',
                        method: 'POST', data: fd, processData: false, contentType: false, dataType: 'json'
                    }).done(function (r) {
                        if (r && r.ok) { rsToast('Issued to supplier.', 'success'); setTimeout(function(){location.reload();}, 500); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }).fail(function () { $.alert({title:'Network error', type:'red'}); });
                    return false;
                }},
                cancel: function () {}
            }
        });
    });
    <?php endif; ?>
})();
</script>
<?php endif; ?>

<?php if ($isSupplier && $canRaisePr): ?>
<script>
(function () {
    var LPO_ID   = <?= (int)$l['c0d']; ?>;
    var PROOT    = '<?= PROOT; ?>';
    var CURRENCY = <?= json_encode((string)$l['currency']); ?>;
    var TERMS    = <?= json_encode(array_values(array_map(function ($t) {
        return [
            'c0d'             => (int)$t['c0d'],
            'label'           => (string)$t['label'],
            'trigger_type'    => (string)$t['trigger_type'],
            'computed_amount' => (float)$t['computed_amount'],
            'claimed_amount'  => (float)$t['claimed_amount'],
            'remaining'       => (float)$t['remaining'],
            'claimable_now'   => (float)$t['claimable_now'],
            'blocked_reason'  => $t['blocked_reason'],
            'net_days'        => $t['net_days'] !== null ? (int)$t['net_days'] : null,
            'grn_percent_gate'=> $t['grn_percent_gate'] !== null ? (float)$t['grn_percent_gate'] : null,
        ];
    }, $termAvailability))); ?>;

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

    function buildDialog() {
        var netDaysAny = TERMS.some(function (t) { return t.trigger_type === 'NET_DAYS'; });
        var rows = TERMS.map(function (t) {
            var pctLabel = ({ADVANCE:'Advance',ON_ORDER:'On order',ON_DELIVERY:'On delivery',RETENTION:'Retention',NET_DAYS:'Net days',MILESTONE:'Milestone'})[t.trigger_type] || t.trigger_type;
            var claimable = t.claimable_now;
            var netDaysHint = (t.trigger_type === 'NET_DAYS') ? ' <span class="text-muted" style="font-size:.6rem;">(fill invoice date to unlock)</span>' : '';
            var disabled = (claimable <= 0.005 && t.trigger_type !== 'NET_DAYS' && t.trigger_type !== 'MILESTONE');
            var reason = t.blocked_reason ? '<div class="text-muted" style="font-size:.6rem;color:#C48579;">' + esc(t.blocked_reason) + '</div>' : '';
            return '<tr data-term-id="' + t.c0d + '">' +
                '<td><input type="checkbox" class="form-check-input pr_pick" ' + (disabled?'disabled':'') + '></td>' +
                '<td class="small"><strong>' + esc(t.label) + '</strong> <span class="text-muted" style="font-size:.6rem;">' + esc(pctLabel) + netDaysHint + '</span>' + reason + '</td>' +
                '<td class="text-end small text-muted">' + fmt(t.remaining) + '</td>' +
                '<td class="text-end small" style="color:' + (claimable>0?'#3F5C43':'#C48579') + ';font-weight:600;">' + fmt(claimable) + '</td>' +
                '<td><input type="number" step="0.01" min="0" class="form-control form-control-sm pr_amt text-end" value="' + (claimable > 0 ? claimable : '') + '" ' + (disabled?'disabled':'') + '></td>' +
                '<td><input type="text" class="form-control form-control-sm pr_note" placeholder="—"></td>' +
            '</tr>';
        }).join('');

        return '<div class="small mb-2 text-muted">Pick terms to claim, adjust amounts if you\'re asking for a partial. Total updates below.</div>' +
            (netDaysAny ? '<div class="row g-2 mb-2" style="background:#FEF3E7;padding:.4rem .6rem;border:1px solid #D4A574;border-radius:6px;">' +
                '<div class="col-6"><label class="form-label small">Supplier invoice #</label><input id="pr_inv_no" class="form-control form-control-sm"></div>' +
                '<div class="col-6"><label class="form-label small">Supplier invoice date</label><input id="pr_inv_date" type="date" class="form-control form-control-sm"></div>' +
                '<div class="col-12 text-muted" style="font-size:.62rem;">Required when a Net-days term is on this PR.</div>' +
            '</div>' : '') +
            '<div class="table-responsive"><table class="table table-sm mb-0 align-middle">' +
            '<thead class="table-light"><tr><th style="width:30px;"></th><th>Term</th><th class="text-end" style="width:100px;">Remaining</th><th class="text-end" style="width:110px;">Claimable now</th><th style="width:130px;">Claim</th><th style="width:160px;">Note</th></tr></thead>' +
            '<tbody id="pr_lines">' + rows + '</tbody>' +
            '<tfoot><tr><td colspan="4" class="text-end small text-muted">PR total</td><td class="text-end small" style="font-weight:700;color:#334155;" id="pr_total">' + CURRENCY + ' 0</td><td></td></tr></tfoot>' +
            '</table></div>' +
            '<div class="mt-2"><label class="form-label small">Notes (optional)</label><input id="pr_notes" class="form-control form-control-sm"></div>';
    }

    function wireDialog() {
        var tbody = document.getElementById('pr_lines');
        function recalc() {
            var total = 0;
            tbody.querySelectorAll('tr').forEach(function (tr) {
                if (!tr.querySelector('.pr_pick').checked) return;
                total += parseFloat(tr.querySelector('.pr_amt').value || 0);
            });
            document.getElementById('pr_total').textContent = CURRENCY + ' ' + fmt(total);
        }
        tbody.addEventListener('change', function (e) {
            var tr = e.target.closest('tr'); if (!tr) return;
            if (e.target.classList.contains('pr_pick')) {
                var amt = tr.querySelector('.pr_amt');
                amt.disabled = !e.target.checked;
            }
            recalc();
        });
        tbody.addEventListener('input', function (e) { if (e.target.classList.contains('pr_amt')) recalc(); });
        recalc();
    }

    function submitDialog() {
        var lines = [];
        document.querySelectorAll('#pr_lines tr').forEach(function (tr) {
            if (!tr.querySelector('.pr_pick').checked) return;
            var amt = parseFloat(tr.querySelector('.pr_amt').value || 0);
            if (amt <= 0) return;
            lines.push({
                term_id: parseInt(tr.getAttribute('data-term-id'), 10),
                amount:  amt,
                note:    tr.querySelector('.pr_note').value || ''
            });
        });
        if (lines.length === 0) { $.alert({title:'Pick at least one term', type:'orange'}); return false; }
        var invNo   = (document.getElementById('pr_inv_no')   || {}).value || '';
        var invDate = (document.getElementById('pr_inv_date') || {}).value || '';
        $.post(PROOT + 'PaymentRequests/raiseAj', {
            lpo_id: LPO_ID,
            supplier_invoice_no: invNo,
            supplier_invoice_date: invDate,
            notes: document.getElementById('pr_notes').value || '',
            lines: JSON.stringify(lines)
        }, function (r) {
            if (r && r.ok) { rsToast('PR raised.', 'success'); setTimeout(function(){window.location.href = PROOT + 'PaymentRequests/view/' + r.pr_id;}, 500); }
            else $.alert({title:'Could not raise', content:(r && r.msg) || 'Server error', type:'red'});
        }, 'json').fail(function () { $.alert({title:'Network error', type:'red'}); });
        return false;
    }

    function openRaiseDialog() {
        $.confirm({
            title: 'Raise Payment Request',
            columnClass: 'col-md-9',
            content: buildDialog(),
            onOpen: wireDialog,
            buttons: {
                submit: { text: 'Submit for PC confirm', btnClass: 'btn-success', action: submitDialog },
                cancel: function () {}
            }
        });
    }

    var b1 = document.getElementById('btn_raise_pr');
    var b2 = document.getElementById('btn_raise_pr_inline');
    if (b1) b1.addEventListener('click', openRaiseDialog);
    if (b2) b2.addEventListener('click', openRaiseDialog);
})();
</script>
<?php endif; ?>

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