<?php $this->start('body');
    $po         = $this->data['po'];
    $items      = $this->data['items'] ?? [];
    $invoices   = $this->data['invoices'] ?? [];
    $canInvoice = !empty($this->data['can_invoice']);
    // Slice 8Z-g Batch 1 · Procurement scrub surface
    $hideMargin = !empty($this->data['hide_margin']);
    $hideSell   = !empty($this->data['hide_sell']);
    $canAccept  = !empty($this->data['can_accept']);
    $canQuery   = !empty($this->data['can_query']);
    $canReopen  = !empty($this->data['can_reopen']);
    $overheads  = $this->data['overheads'] ?? [];
    $anyScrub   = $canAccept || $canQuery || $canReopen;
    // Sum overheads (estimate) for the cost-side summary shown to PC/Procurement
    $ovhEst = 0.0; foreach ($overheads as $o) $ovhEst += (float)$o['amount'];
    // Slice 8Z-h · Batch 2 — sourcing path picker
    $canPickPath = !empty($this->data['can_pick_path']);
    $engagement  = $this->data['engagement'] ?? [];
    // Slice 8Z-j Batch 4 — % of PO total (admin-tunable), not flat threshold
    $discoveryCapPct  = (float)($this->data['discovery_cap_pct']  ?? 5);
    $discoveryExecPct = (float)($this->data['discovery_exec_pct'] ?? 3);
    $poTotal          = (float)($po['total'] ?? 0);
    $discoveryCapAmt  = round($poTotal * ($discoveryCapPct / 100), 2);
    $discoveryExecAmt = round($poTotal * ($discoveryExecPct / 100), 2);
    $sourcingPath = (string)($po['sourcing_path'] ?? 'UNSET');
    $showSourcingCard = $canPickPath && !empty($po['handover_at']); // Only after PC has handed over

    $sc = ['DRAFT'=>'bg-light text-muted','CONFIRMED'=>'bg-info text-white','SOURCING'=>'bg-primary','INVOICING'=>'bg-warning text-dark','CLOSED'=>'bg-success','CANCELLED'=>'bg-secondary'][$po['status']] ?? 'bg-light text-muted';
    $subSell = (float)$po['subtotal_sell'];
    $subCog  = (float)$po['subtotal_cog'];
    $mgn = $subSell > 0 ? (($subSell - $subCog) / $subSell) * 100 : 0;
    $invoicedTot = 0.0; foreach ($invoices as $iv) $invoicedTot += (float)$iv['total'];

    // Per-item chip palette (warm/faded)
    $itemStatusChip = [
        'PENDING'   => ['#F1F5F9','#334155','Pending'],
        'CONFIRMED' => ['#E8EEF3','#7A8BA1','Confirmed'],
        'ACCEPTED'  => ['#EAF2E8','#3F5C43','Accepted'],
        'QUERIED'   => ['#F5EAE1','#C48579','Queried'],
    ];
    $ovhCatChip = [
        'TRANSPORT'    => ['#EEF2F6','#7A8BA1','Transport'],
        'HSE'          => ['#FEF3E7','#8B6914','HSE'],
        'INSURANCE'    => ['#E8EEF3','#7A8BA1','Insurance'],
        'PACKAGING'    => ['#EEF2F6','#7A8BA1','Packaging'],
        'WAREHOUSING'  => ['#EEF2F6','#7A8BA1','Warehousing'],
        'INSTALLATION' => ['#EAF2E8','#3F5C43','Installation'],
        'OTHER'        => ['#F1F5F9','#334155','Other'],
    ];
?>

<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-contract me-2 text-muted"></i><?= htmlspecialchars($po['client_po_no']); ?></h5>
        <div class="text-muted" style="font-size:.72rem;">
            <?= htmlspecialchars($po['po_date']); ?> · <?= htmlspecialchars($po['customer_name']); ?>
            <?php if (!empty($po['project_no'])): ?> · <a href="<?= PROOT; ?>Projects/view/<?= (int)$po['project_id']; ?>"><?= htmlspecialchars($po['project_no']); ?></a><?php endif; ?>
            · <span class="badge <?= $sc; ?>" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower($po['status'])); ?></span>
            <?php if ($po['customer_po_ref']): ?> · Their ref: <code class="text-body"><?= htmlspecialchars($po['customer_po_ref']); ?></code><?php endif; ?>
        </div>
    </div>
    <a href="<?= PROOT; ?>GoodsClientPos" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> All Client POs</a>
</div>

<div class="row g-3 mb-3">
    <?php if ($hideSell): ?>
        <!-- PC/Procurement cost-side view: COG + Overheads (est) = total sourcing ceiling -->
        <div class="col-md-4"><div class="card border-0 shadow-sm"><div class="card-body p-2"><div class="text-muted small">Cog (planned ceiling)</div><div style="font-weight:700;font-size:1.15rem;color:#334155;"><?= htmlspecialchars($po['currency']); ?> <?= number_format($subCog); ?></div></div></div></div>
        <div class="col-md-4"><div class="card border-0 shadow-sm"><div class="card-body p-2"><div class="text-muted small">Overheads (estimate)</div><div style="font-weight:600;font-size:1.05rem;color:#334155;"><?= htmlspecialchars($po['currency']); ?> <?= number_format($ovhEst); ?></div><div class="text-muted" style="font-size:.6rem;"><?= count($overheads); ?> line<?= count($overheads) === 1 ? '' : 's'; ?></div></div></div></div>
        <div class="col-md-4"><div class="card border-0 shadow-sm" style="background:#F8FAFC;border:1px solid #E2E8F0;"><div class="card-body p-2"><div class="text-muted small">Total sourcing ceiling</div><div style="font-weight:700;font-size:1.15rem;color:#3F5C43;"><?= htmlspecialchars($po['currency']); ?> <?= number_format($subCog + $ovhEst); ?></div><div class="text-muted" style="font-size:.6rem;">Cog + overheads</div></div></div></div>
    <?php else: ?>
        <div class="col-md-3"><div class="card border-0 shadow-sm"><div class="card-body p-2"><div class="text-muted small">Sell (net)</div><div style="font-weight:600;font-size:1.05rem;"><?= htmlspecialchars($po['currency']); ?> <?= number_format($subSell); ?></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">Cog (planned)</div><div style="font-weight:600;"><?= htmlspecialchars($po['currency']); ?> <?= number_format($subCog); ?></div></div></div></div>
        <?php if (!$hideMargin): ?>
            <div class="col-md-3"><div class="card border-0 shadow-sm"><div class="card-body p-2"><div class="text-muted small">Planned margin</div><div style="font-weight:700;font-size:1.15rem;color:<?= $mgn<20?'#C48579':($mgn<25?'#8B6914':'#3F5C43'); ?>;"><?= number_format($mgn, 1); ?>%</div></div></div></div>
        <?php endif; ?>
        <div class="col-md-3"><div class="card border-0 shadow-sm"><div class="card-body p-2"><div class="text-muted small">Total (incl VAT @ <?= number_format((float)$po['vat_rate'],2); ?>%)</div><div style="font-weight:700;font-size:1.15rem;"><?= htmlspecialchars($po['currency']); ?> <?= number_format((float)$po['total']); ?></div></div></div></div>
    <?php endif; ?>
</div>

<!-- PC Briefing panel (delivery block + handover note) -->
<?php if (!empty($po['handover_at']) || !empty($po['primary_delivery_location']) || !empty($po['incoterm']) || !empty($po['handover_notes'])): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header py-2" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;">
        <div class="d-flex align-items-center justify-content-between">
            <div class="small" style="font-weight:600;color:#334155;">
                <i class="fas fa-clipboard-list me-1 text-muted"></i>PC briefing
                <span class="text-muted ms-2" style="font-weight:400;font-size:.65rem;">Read-only · everything Procurement needs to know before sourcing</span>
            </div>
            <?php if (!empty($po['handover_at'])): ?>
                <span class="badge" style="background:#EEF2F6;color:#7A8BA1;border:1px solid #7A8BA1;font-size:.62rem;">
                    Handed over <?= htmlspecialchars(date('d M · H:i', strtotime($po['handover_at']))); ?>
                    <?php if (!empty($po['handover_by_name'])): ?> by <?= htmlspecialchars($po['handover_by_name']); ?><?php endif; ?>
                </span>
            <?php endif; ?>
        </div>
    </div>
    <div class="card-body p-3">
        <div class="row g-3">
            <?php if (!empty($po['incoterm']) || !empty($po['delivery_deadline']) || !empty($po['delivery_mode'])): ?>
                <div class="col-md-4">
                    <div class="text-muted small mb-1" style="font-size:.65rem;font-weight:600;text-transform:capitalize;">Delivery terms</div>
                    <?php if (!empty($po['incoterm'])): ?>
                        <div class="small"><span class="text-muted">Incoterm:</span> <strong><?= htmlspecialchars($po['incoterm']); ?></strong></div>
                    <?php endif; ?>
                    <?php if (!empty($po['delivery_deadline'])): ?>
                        <div class="small"><span class="text-muted">Deadline:</span> <strong><?= htmlspecialchars(date('d M Y', strtotime($po['delivery_deadline']))); ?></strong></div>
                    <?php endif; ?>
                    <?php if (!empty($po['delivery_mode'])): ?>
                        <div class="small"><span class="text-muted">Mode:</span> <?= htmlspecialchars(strtolower(str_replace('_',' ', $po['delivery_mode']))); ?></div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
            <?php if (!empty($po['primary_delivery_location']) || !empty($po['delivery_contact_name'])): ?>
                <div class="col-md-4">
                    <div class="text-muted small mb-1" style="font-size:.65rem;font-weight:600;text-transform:capitalize;">Ship to</div>
                    <?php if (!empty($po['primary_delivery_location'])): ?>
                        <div class="small"><?= nl2br(htmlspecialchars($po['primary_delivery_location'])); ?></div>
                    <?php endif; ?>
                    <?php if (!empty($po['delivery_contact_name']) || !empty($po['delivery_contact_phone'])): ?>
                        <div class="small text-muted mt-1" style="font-size:.68rem;">
                            <i class="fas fa-user me-1"></i><?= htmlspecialchars($po['delivery_contact_name']); ?>
                            <?php if (!empty($po['delivery_contact_phone'])): ?> · <?= htmlspecialchars($po['delivery_contact_phone']); ?><?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
            <?php if (!empty($po['delivery_special_instructions']) || !empty($po['handover_notes'])): ?>
                <div class="col-md-4">
                    <?php if (!empty($po['handover_notes'])): ?>
                        <div class="text-muted small mb-1" style="font-size:.65rem;font-weight:600;text-transform:capitalize;">PC handover note</div>
                        <div class="small" style="color:#334155;background:#FEF3E7;border:1px solid #E5CE9F;border-radius:4px;padding:.4em .6em;">
                            <?= nl2br(htmlspecialchars($po['handover_notes'])); ?>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($po['delivery_special_instructions'])): ?>
                        <div class="text-muted small mt-2 mb-1" style="font-size:.65rem;font-weight:600;text-transform:capitalize;">Special instructions</div>
                        <div class="small text-muted"><?= nl2br(htmlspecialchars($po['delivery_special_instructions'])); ?></div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Overheads panel (read-only for Procurement — they usually supplied these numbers) -->
<?php if (!empty($overheads)): ?>
<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-layer-group me-1 text-muted"></i>Project overheads
        <span class="text-muted ms-2" style="font-weight:400;font-size:.65rem;">
            <?= count($overheads); ?> lines · scoped to this PO + project-wide
        </span>
    </div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th style="width:120px;">Category</th>
                    <th>Label</th>
                    <th class="text-end" style="width:130px;">Estimate</th>
                    <th class="text-end" style="width:130px;">Actual</th>
                    <th class="text-end" style="width:110px;">Δ</th>
                    <th style="width:90px;">Source</th>
                </tr>
            </thead>
            <tbody>
                <?php
                    $totEst = 0.0; $totAct = 0.0;
                    foreach ($overheads as $o):
                        $cat = $ovhCatChip[$o['category']] ?? ['#F1F5F9','#334155', $o['category']];
                        $est = (float)$o['amount'];
                        $act = $o['amount_actual'] === null ? null : (float)$o['amount_actual'];
                        $delta = $act === null ? null : round($act - $est, 2);
                        $totEst += $est; if ($act !== null) $totAct += $act;
                ?>
                    <tr>
                        <td><span class="badge" style="background:<?= $cat[0]; ?>;color:<?= $cat[1]; ?>;border:1px solid <?= $cat[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($cat[2]); ?></span></td>
                        <td class="small"><?= htmlspecialchars($o['label']); ?>
                            <?php if (!empty($o['notes'])): ?><div class="text-muted" style="font-size:.62rem;"><?= htmlspecialchars($o['notes']); ?></div><?php endif; ?>
                        </td>
                        <td class="text-end small" style="font-weight:600;color:#334155;"><?= number_format($est); ?></td>
                        <td class="text-end small"><?= $act === null ? '<span class="text-muted">—</span>' : number_format($act); ?></td>
                        <td class="text-end small">
                            <?php if ($delta === null): ?>
                                <span class="text-muted">—</span>
                            <?php else: ?>
                                <span style="color:<?= $delta > 0 ? '#C48579' : ($delta < 0 ? '#3F5C43' : '#334155'); ?>;font-weight:600;"><?= ($delta > 0 ? '+' : '') . number_format($delta); ?></span>
                            <?php endif; ?>
                        </td>
                        <td class="small text-muted" style="font-size:.62rem;">
                            <?php if ($o['source'] === 'TENDER_CARRY_OVER'): ?>
                                <i class="fas fa-history me-1" style="color:#7A8BA1;"></i>Tender
                            <?php else: ?>
                                <i class="fas fa-plus me-1" style="color:#7A9E7E;"></i>PC-added
                            <?php endif; ?>
                            <?php if (empty($o['po_id'])): ?><div class="text-muted" style="font-size:.6rem;">Project-wide</div><?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot style="background:#F8FAFC;">
                <tr>
                    <td colspan="2" class="small text-muted" style="font-weight:600;">Total</td>
                    <td class="text-end small" style="font-weight:600;color:#334155;"><?= htmlspecialchars($po['currency']); ?> <?= number_format($totEst); ?></td>
                    <td class="text-end small" style="font-weight:600;color:#334155;"><?= htmlspecialchars($po['currency']); ?> <?= number_format($totAct); ?></td>
                    <td class="text-end small">
                        <?php $totDelta = $totAct - $totEst; ?>
                        <span style="color:<?= $totDelta > 0 ? '#C48579' : ($totDelta < 0 ? '#3F5C43' : '#334155'); ?>;font-weight:600;"><?= ($totDelta > 0 ? '+' : '') . number_format($totDelta); ?></span>
                    </td>
                    <td></td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>
<?php endif; ?>

<?php if ($showSourcingCard):
    // Chip palettes for the engagement states
    $cashChip = [
        'DRAFT'    => ['#F1F5F9','#334155','Draft'],
        'SUBMITTED'=> ['#EEF2F6','#7A8BA1','Awaiting approval'],
        'APPROVED' => ['#EAF2E8','#3F5C43','Approved · awaiting cash'],
        'ISSUED'   => ['#EDE7DC','#5B4F3C','Cash ready'],
        'PAID'     => ['#EAF2E8','#3F5C43','Cash collected'],
        'RETIRED'  => ['#EAF2E8','#3F5C43','Retired'],
        'DECLINED' => ['#F5EAE1','#C48579','Declined'],
    ];
    $retChip = [
        'DRAFT'    => ['#F1F5F9','#334155','Retirement drafted'],
        'SUBMITTED'=> ['#EEF2F6','#7A8BA1','Retirement submitted'],
        'APPROVED' => ['#EAF2E8','#3F5C43','Retirement approved · findings ready for RFQ'],
        'REJECTED' => ['#F5EAE1','#C48579','Retirement bounced back'],
    ];
    $engCashChip = !empty($engagement) ? ($cashChip[$engagement['cash_out_status']] ?? ['#F1F5F9','#334155',$engagement['cash_out_status']]) : null;
    $engRetChip  = !empty($engagement) && !empty($engagement['retirement_status']) ? ($retChip[$engagement['retirement_status']] ?? null) : null;
?>
<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-route me-1 text-muted"></i>Sourcing path
            <?php if ($sourcingPath === 'UNSET'): ?>
                <span class="text-muted ms-2" style="font-weight:400;font-size:.65rem;">Procurement's call: research suppliers first or go straight to RFQ (you can change your mind later)</span>
            <?php endif; ?>
        </div>
        <div class="d-flex align-items-center gap-2">
            <?php if ($sourcingPath === 'DISCOVERY'): ?>
                <span class="badge" style="background:#FEF3E7;color:#8B6914;border:1px solid #8B6914;font-size:.62rem;text-transform:capitalize;"><i class="fas fa-binoculars me-1"></i>Path A · Product Discovery</span>
            <?php elseif ($sourcingPath === 'SKIP_TO_RFQ'): ?>
                <span class="badge" style="background:#EAF2E8;color:#3F5C43;border:1px solid #3F5C43;font-size:.62rem;text-transform:capitalize;"><i class="fas fa-forward me-1"></i>Path B · Skip to RFQ</span>
            <?php endif; ?>
            <?php // Slice 8Z-j Batch 4 · always-available "Skip to RFQ" escape hatch (unless already SKIP_TO_RFQ) ?>
            <?php if ($sourcingPath !== 'SKIP_TO_RFQ'): ?>
                <button type="button" id="btn_switch_skip" class="btn btn-sm" style="background:#fff;border:1px solid #7A8BA1;color:#7A8BA1;font-weight:600;font-size:.62rem;padding:.15em .55em;" title="Skip Discovery — go straight to RFQ. You can still invite Discovery shortlist suppliers manually later.">
                    <i class="fas fa-forward me-1"></i>Skip to RFQ now
                </button>
            <?php endif; ?>
        </div>
    </div>
    <div class="card-body p-3">

        <?php if ($sourcingPath === 'UNSET'): ?>
            <!-- Path picker -->
            <div class="row g-3">
                <div class="col-md-6">
                    <div class="p-3 rounded h-100" style="background:#FEF3E7;border:1px dashed #8B6914;">
                        <div class="mb-2"><strong style="color:#5B4F3C;font-size:.85rem;"><i class="fas fa-binoculars me-1"></i>Path A · Product Discovery</strong></div>
                        <div class="small text-muted mb-3" style="font-size:.7rem;color:#64748B;">
                            You need cash first — for supplier research, sample buys, a trade fair, or a trip to a supplier before you can quote confidently. Findings feed straight into the RFQ shortlist.
                        </div>
                        <button type="button" id="btn_pick_discovery" class="btn btn-sm w-100" style="background:#8B6914;border-color:#8B6914;color:#fff;font-weight:600;">
                            <i class="fas fa-hand-holding-usd me-1"></i>Request Product Discovery
                        </button>
                        <div class="text-muted mt-2" style="font-size:.62rem;">
                            Threshold: &le; <?= htmlspecialchars($po['currency']); ?> <?= number_format($discoveryThreshold); ?> = PM &rarr; FM · above = PM &rarr; FM &rarr; Exec.
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="p-3 rounded h-100" style="background:#EAF2E8;border:1px dashed #3F5C43;">
                        <div class="mb-2"><strong style="color:#3F5C43;font-size:.85rem;"><i class="fas fa-forward me-1"></i>Path B · Skip to RFQ</strong></div>
                        <div class="small text-muted mb-3" style="font-size:.7rem;color:#64748B;">
                            You already know the suppliers. Skip Discovery and go straight to sending RFQs. Faster — but no formal research trail if the client asks.
                        </div>
                        <button type="button" id="btn_pick_skip" class="btn btn-sm w-100" style="background:#3F5C43;border-color:#3F5C43;color:#fff;font-weight:600;">
                            <i class="fas fa-check me-1"></i>Skip Discovery &rarr; RFQ
                        </button>
                        <div class="text-muted mt-2" style="font-size:.62rem;">
                            Reversing: not possible from the UI — cancel via Admin if you change your mind.
                        </div>
                    </div>
                </div>
            </div>

        <?php elseif ($sourcingPath === 'DISCOVERY'): ?>
            <!-- Path A · Discovery engagement status -->
            <?php if (empty($engagement)): ?>
                <div class="d-flex align-items-center justify-content-between">
                    <div class="small text-muted">Discovery selected — request the cash advance to kick off supplier research.</div>
                    <button type="button" id="btn_request_discovery" 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>Request Discovery advance
                    </button>
                </div>
            <?php else: ?>
                <div class="row g-2 align-items-center">
                    <div class="col-md-3">
                        <div class="text-muted small" style="font-size:.65rem;font-weight:600;text-transform:capitalize;">Discovery LPO</div>
                        <div><a href="<?= PROOT; ?>Lpos/view/<?= (int)$engagement['lpo_id']; ?>" class="text-decoration-none" style="color:#7A8BA1;font-weight:600;"><?= htmlspecialchars($engagement['lpo_no']); ?></a></div>
                        <div class="text-muted small" style="font-size:.62rem;"><?= htmlspecialchars($engagement['currency']); ?> <?= number_format((float)$engagement['amount']); ?></div>
                    </div>
                    <div class="col-md-3">
                        <div class="text-muted small" style="font-size:.65rem;font-weight:600;text-transform:capitalize;">Cash status</div>
                        <span class="badge" style="background:<?= $engCashChip[0]; ?>;color:<?= $engCashChip[1]; ?>;border:1px solid <?= $engCashChip[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($engCashChip[2]); ?></span>
                    </div>
                    <div class="col-md-3">
                        <div class="text-muted small" style="font-size:.65rem;font-weight:600;text-transform:capitalize;">Retirement</div>
                        <?php if ($engRetChip): ?>
                            <span class="badge" style="background:<?= $engRetChip[0]; ?>;color:<?= $engRetChip[1]; ?>;border:1px solid <?= $engRetChip[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($engRetChip[2]); ?></span>
                        <?php else: ?>
                            <span class="text-muted small">Not started</span>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-3 text-end">
                        <?php if (in_array($engagement['cash_out_status'], ['PAID','ISSUED'], true) && (empty($engagement['retirement_status']) || $engagement['retirement_status'] === 'REJECTED')): ?>
                            <a href="<?= PROOT; ?>Retirements/new/<?= (int)$engagement['lpo_id']; ?>" 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>Retire + capture findings
                            </a>
                        <?php elseif ($engagement['retirement_status'] === 'SUBMITTED' || $engagement['retirement_status'] === 'DRAFT'): ?>
                            <a href="<?= PROOT; ?>Retirements/view/<?= (int)$engagement['retirement_id']; ?>" class="btn btn-sm btn-outline-secondary">
                                <i class="fas fa-file-invoice-dollar me-1"></i>Open retirement
                            </a>
                        <?php elseif ($engagement['retirement_status'] === 'APPROVED'): ?>
                            <span class="text-muted small" style="font-size:.65rem;"><i class="fas fa-check-circle me-1" style="color:#3F5C43;"></i>Findings ready — proceed to RFQ</span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="text-muted mt-2" style="font-size:.62rem;">
                    <i class="fas fa-info-circle me-1"></i>The "Start RFQ" button (top of Line items) will pre-load your SHORTLISTED suppliers once the retirement is APPROVED.
                </div>
            <?php endif; ?>

        <?php elseif ($sourcingPath === 'SKIP_TO_RFQ'): ?>
            <div class="small text-muted">
                <i class="fas fa-check-circle me-1" style="color:#3F5C43;"></i>
                Ready to send RFQs — use the "Start RFQ" button on the Line items card above. You'll pick suppliers manually from the vendor directory.
            </div>
        <?php endif; ?>

    </div>
</div>
<?php endif; ?>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <strong>Line items</strong>
        <div>
            <?php if (UserGroups::can('GoodsRfq','fromClientPo')): ?>
                <a href="<?= PROOT; ?>GoodsRfq/fromClientPo/<?= (int)$po['c0d']; ?>" class="btn btn-sm btn-outline-primary me-1" title="Start sourcing (RFQ) for this PO">
                    <i class="fas fa-file-signature me-1"></i> Start RFQ
                </a>
            <?php endif; ?>
            <?php if ($canInvoice): ?>
                <a href="<?= PROOT; ?>Sales/draft?client_po_id=<?= (int)$po['c0d']; ?>" class="btn btn-sm btn-primary" style="background:<?= BRAND_COLOR; ?>;border-color:<?= BRAND_COLOR; ?>;">
                    <i class="fas fa-file-invoice me-1"></i> Draft Invoice from PO
                </a>
            <?php endif; ?>
        </div>
    </div>
    <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" style="width:70px;">Qty</th>
                    <th style="width:60px;">Unit</th>
                    <?php if (!$hideSell): ?><th class="text-end" style="width:100px;">Sell</th><?php endif; ?>
                    <th class="text-end" style="width:100px;">Cog</th>
                    <?php if (!$hideMargin): ?><th class="text-end" style="width:80px;">Margin</th><?php endif; ?>
                    <th class="text-end" style="width:80px;">Rec'd</th>
                    <th class="text-end" style="width:80px;">Del'd</th>
                    <th class="text-end" style="width:80px;">Inv'd</th>
                    <th style="width:100px;">Status</th>
                    <?php if ($anyScrub): ?><th style="width:180px;" class="text-end">Action</th><?php endif; ?>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($items as $it):
                    $ls   = (float)$it['line_total_sell'];
                    $lc   = (float)$it['line_total_cog'];
                    $lmgn = $ls > 0 ? (($ls - $lc) / $ls) * 100 : 0;
                    $qty  = (float)$it['qty'];
                    $rec  = (float)$it['qty_received'];
                    $del  = (float)$it['qty_delivered'];
                    $stat = (string)$it['item_status'];
                    $sChip = $itemStatusChip[$stat] ?? ['#F1F5F9','#334155',$stat];
                    // Which action buttons apply for this row + role
                    $showAccept = $canAccept && $stat === 'CONFIRMED';
                    $showQuery  = $canQuery  && in_array($stat, ['CONFIRMED','ACCEPTED'], true);
                    $showReopen = $canReopen && $stat === 'ACCEPTED';
                ?>
                    <tr data-item-id="<?= (int)$it['c0d']; ?>">
                        <td class="text-muted small"><?= (int)$it['item_no']; ?></td>
                        <td>
                            <div class="small" style="font-weight:600;color:#334155;"><?= htmlspecialchars($it['description']); ?></div>
                            <?php
                                $meta = [];
                                if (!empty($it['brand']))       $meta[] = '<i class="fas fa-tag me-1" style="color:#94A3B8;"></i>' . htmlspecialchars($it['brand']);
                                if (!empty($it['source_pref']) && $it['source_pref'] !== 'ANY') $meta[] = htmlspecialchars($it['source_pref']);
                                if (!empty($it['priority'])) {
                                    $pc = ['LOW'=>'#7A8BA1','MED'=>'#334155','HIGH'=>'#8B6914','CRITICAL'=>'#C48579'][$it['priority']] ?? '#334155';
                                    $meta[] = '<span style="color:' . $pc . ';">● ' . htmlspecialchars($it['priority']) . '</span>';
                                }
                                if ((int)$it['alt_ok'] === 1)   $meta[] = '<i class="fas fa-random me-1" style="color:#7A9E7E;"></i>alt OK';
                                if (!empty($it['deliver_by']))  $meta[] = 'by ' . htmlspecialchars(date('d M', strtotime($it['deliver_by'])));
                                if (!empty($it['deliver_to']))  $meta[] = '→ ' . htmlspecialchars(mb_strimwidth($it['deliver_to'], 0, 30, '…'));
                            ?>
                            <?php if (!empty($meta)): ?>
                                <div class="text-muted mt-1" style="font-size:.62rem;"><?= implode(' · ', $meta); ?></div>
                            <?php endif; ?>
                            <?php if (!empty($it['alt_note'])): ?>
                                <div class="text-muted" style="font-size:.62rem;"><em>Alt: <?= htmlspecialchars($it['alt_note']); ?></em></div>
                            <?php endif; ?>
                            <?php if (!empty($it['scrub_remarks'])): ?>
                                <div class="mt-1" style="font-size:.62rem;color:#334155;background:#F8FAFC;border-left:2px solid #7A8BA1;padding:.25em .5em;">
                                    <strong style="color:#7A8BA1;">PC:</strong> <?= htmlspecialchars($it['scrub_remarks']); ?>
                                </div>
                            <?php endif; ?>
                            <?php if (!empty($it['procurement_note'])): ?>
                                <div class="mt-1" style="font-size:.62rem;color:#334155;background:<?= $stat === 'QUERIED' ? '#F5EAE1' : '#EAF2E8'; ?>;border-left:2px solid <?= $stat === 'QUERIED' ? '#C48579' : '#3F5C43'; ?>;padding:.25em .5em;">
                                    <strong style="color:<?= $stat === 'QUERIED' ? '#C48579' : '#3F5C43'; ?>;">Proc:</strong> <?= htmlspecialchars($it['procurement_note']); ?>
                                    <?php if (!empty($it['procurement_actioned_by_name'])): ?>
                                        <span class="text-muted" style="font-size:.6rem;"> · <?= htmlspecialchars($it['procurement_actioned_by_name']); ?><?php if (!empty($it['procurement_actioned_at'])): ?> · <?= htmlspecialchars(date('d M · H:i', strtotime($it['procurement_actioned_at']))); ?><?php endif; ?></span>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </td>
                        <td class="text-end small"><?= number_format($qty, (fmod($qty,1)==0?0:2)); ?></td>
                        <td class="text-muted small"><?= htmlspecialchars($it['unit']); ?></td>
                        <?php if (!$hideSell): ?>
                            <td class="text-end small"><?= number_format((float)$it['unit_price_sell']); ?></td>
                        <?php endif; ?>
                        <td class="text-end text-muted small"><?= number_format((float)$it['unit_price_cog']); ?></td>
                        <?php if (!$hideMargin): ?>
                            <td class="text-end small" style="color:<?= $lmgn<20?'#C48579':($lmgn<25?'#8B6914':'#3F5C43'); ?>;font-weight:600;"><?= number_format($lmgn,1); ?>%</td>
                        <?php endif; ?>
                        <td class="text-end small" style="color:<?= $rec>=$qty?'#3F5C43':($rec>0?'#8B6914':'#94A3B8'); ?>;"><?= number_format($rec, (fmod($rec,1)==0?0:2)); ?></td>
                        <td class="text-end small" style="color:<?= $del>=$qty?'#3F5C43':($del>0?'#8B6914':'#94A3B8'); ?>;font-weight:600;"><?= number_format($del, (fmod($del,1)==0?0:2)); ?></td>
                        <td class="text-end small text-muted"><?= number_format((float)$it['qty_invoiced'], (fmod((float)$it['qty_invoiced'],1)==0?0:2)); ?></td>
                        <td><span class="badge" style="background:<?= $sChip[0]; ?>;color:<?= $sChip[1]; ?>;border:1px solid <?= $sChip[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($sChip[2]); ?></span></td>
                        <?php if ($anyScrub): ?>
                        <td class="text-end">
                            <?php if ($showAccept): ?>
                                <button type="button" class="btn btn-sm btn_accept" title="Lock in spec — item can no longer be edited by PC" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;padding:.15em .5em;font-size:.62rem;">
                                    <i class="fas fa-check me-1"></i>Accept
                                </button>
                            <?php endif; ?>
                            <?php if ($showQuery): ?>
                                <button type="button" class="btn btn-sm btn_query" title="Bounce back to PC with a question" style="background:#fff;border:1px solid #C48579;color:#C48579;font-weight:600;padding:.15em .5em;font-size:.62rem;">
                                    <i class="fas fa-question me-1"></i>Query
                                </button>
                            <?php endif; ?>
                            <?php if ($showReopen): ?>
                                <button type="button" class="btn btn-sm btn_reopen" title="Reopen — flip back to QUERIED so PC can edit" style="background:#fff;border:1px solid #7A8BA1;color:#7A8BA1;font-weight:600;padding:.15em .5em;font-size:.62rem;">
                                    <i class="fas fa-undo me-1"></i>Reopen
                                </button>
                            <?php endif; ?>
                        </td>
                        <?php endif; ?>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($items)): ?>
                    <tr><td colspan="<?= 9 + (!$hideSell ? 1 : 0) + (!$hideMargin ? 1 : 0) + ($anyScrub ? 1 : 0); ?>" class="text-center text-muted py-4" style="font-size:.72rem;">No items on this PO.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php
    $dns        = $this->data['dns']         ?? [];
    $canDeliver = !empty($this->data['can_deliver']);
?>
<?php if (!empty($dns) || $canDeliver): ?>
<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-truck me-2 text-muted"></i>Customer Delivery Notes</strong>
        <?php if ($canDeliver): ?>
            <a href="<?= PROOT; ?>GoodsCustomerDeliveries/deliver/<?= (int)$po['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 Delivery
            </a>
        <?php endif; ?>
    </div>
    <?php if (!empty($dns)): ?>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr><th>DN #</th><th>Date</th><th>Delivered to</th><th>Delivered by</th><th>Condition</th><th></th></tr>
            </thead>
            <tbody>
                <?php foreach ($dns as $d): ?>
                    <tr>
                        <td><a href="<?= PROOT; ?>GoodsCustomerDeliveries/view/<?= (int)$d['c0d']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars($d['dn_no']); ?></strong></a></td>
                        <td class="text-muted small"><?= htmlspecialchars($d['delivery_date']); ?></td>
                        <td><?= htmlspecialchars($d['delivered_to']); ?></td>
                        <td class="text-muted"><?= htmlspecialchars($d['delivered_by_name']); ?></td>
                        <td>
                            <?php if ((int)$d['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; ?>GoodsCustomerDeliveries/view/<?= (int)$d['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 customer deliveries yet — stock in warehouse is ready to deliver.</div>
    <?php endif; ?>
</div>
<?php endif; ?>

<?php
    // Slice 8Z-q · Related LPOs card
    $relLpos = $this->data['related_lpos'] ?? [];
    $cogLpos = []; $expLpos = [];
    $cogPlanned = 0.0; $cogPaid = 0.0; $expPlanned = 0.0; $expPaid = 0.0;
    foreach ($relLpos as $rlp) {
        if (($rlp['lpo_type'] ?? '') === 'SUPPLIER') {
            $cogLpos[] = $rlp;
            $cogPlanned += (float)$rlp['amount'];
            $cogPaid    += (float)($rlp['amount_paid'] ?? 0);
        } else {
            $expLpos[] = $rlp;
            $expPlanned += (float)$rlp['amount'];
            $expPaid    += (float)($rlp['amount_paid'] ?? 0);
        }
    }
    $lpoStatusChip = [
        'DRAFT'     => ['#F1F5F9','#334155','Draft'],
        'SUBMITTED' => ['#EEF2F6','#7A8BA1','Submitted'],
        'APPROVED'  => ['#EAF2E8','#3F5C43','Approved'],
        'BOOKED'    => ['#EEF2F6','#7A8BA1','Booked'],
        'ISSUED'    => ['#EAF2E8','#3F5C43','Issued'],
        'PAID'      => ['#EAF2E8','#3F5C43','Paid'],
        'RETIRED'   => ['#EEF2F6','#334155','Retired'],
        'CLOSED'    => ['#F1F5F9','#334155','Closed'],
        'DECLINED'  => ['#F5EAE1','#C48579','Declined'],
    ];
    $renderLpoRow = function ($rlp) use ($po, $lpoStatusChip) {
        $st = $lpoStatusChip[$rlp['cash_out_status']] ?? ['#F1F5F9','#334155',$rlp['cash_out_status']];
        $paid = (float)($rlp['amount_paid'] ?? 0);
        $amt  = (float)$rlp['amount'];
        $paidHint = ($paid > 0 && $paid < $amt) ? '<span class="text-muted" style="font-size:.6rem;">Paid ' . number_format($paid) . '</span>' : '';
        $recConf = !empty($rlp['receipt_confirmed_at']) ? '<i class="fas fa-check-circle ms-1" style="color:#3F5C43;" title="Receipt confirmed"></i>' : '';
        $due = '';
        if (!empty($rlp['retirement_due_date']) && $rlp['retirement_due_date'] !== '0000-00-00') {
            $d = (int)floor((strtotime($rlp['retirement_due_date']) - strtotime(date('Y-m-d'))) / 86400);
            $col = $d < 0 ? '#C48579' : ($d <= 3 ? '#8B6914' : '#7A8BA1');
            $due = '<div style="font-size:.6rem;color:' . $col . ';">' . ($d < 0 ? 'Overdue ' . abs($d) . 'd' : 'Retire in ' . $d . 'd') . '</div>';
        }
        return '<tr>'
            . '<td class="small"><a href="' . PROOT . 'Lpos/view/' . (int)$rlp['c0d'] . '" class="text-decoration-none"><strong>' . htmlspecialchars($rlp['lpo_no']) . '</strong></a>' . $recConf . '</td>'
            . '<td class="small text-muted"><span class="badge bg-light text-muted" style="text-transform:capitalize;font-size:.6rem;">' . htmlspecialchars(strtolower(str_replace('_',' ', (string)$rlp['lpo_type']))) . '</span></td>'
            . '<td class="small">' . htmlspecialchars((string)($rlp['payee_name'] ?: '—')) . '</td>'
            . '<td class="text-end small" style="font-weight:600;color:#334155;">' . htmlspecialchars($rlp['currency']) . ' ' . number_format($amt) . ($paidHint ? '<div>' . $paidHint . '</div>' : '') . '</td>'
            . '<td><span class="badge" style="background:' . $st[0] . ';color:' . $st[1] . ';border:1px solid ' . $st[1] . ';font-size:.6rem;text-transform:capitalize;">' . htmlspecialchars($st[2]) . '</span>' . $due . '</td>'
            . '<td class="text-end"><a href="' . PROOT . 'Lpos/view/' . (int)$rlp['c0d'] . '" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-right"></i></a></td>'
            . '</tr>';
    };
?>
<?php if (!empty($relLpos)): ?>
<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-link me-2 text-muted"></i>Related LPOs</strong>
        <span class="text-muted small">
            <?= count($cogLpos); ?> supplier &middot; <?= count($expLpos); ?> internal-cash
        </span>
    </div>
    <?php if (!empty($cogLpos)): ?>
        <div class="px-3 pt-2 pb-1 small" style="background:#F8FAFC;border-top:1px solid #E2E8F0;border-bottom:1px solid #E2E8F0;color:#334155;">
            <strong style="text-transform:capitalize;"><i class="fas fa-truck me-1 text-muted"></i>Cost of goods (Supplier LPOs)</strong>
            <span class="float-end text-muted">Planned <strong style="color:#334155;"><?= htmlspecialchars($po['currency']); ?> <?= number_format($cogPlanned); ?></strong> &middot; Paid <strong style="color:#3F5C43;"><?= htmlspecialchars($po['currency']); ?> <?= number_format($cogPaid); ?></strong></span>
        </div>
        <div class="table-responsive">
            <table class="table table-sm mb-0 align-middle">
                <thead class="table-light">
                    <tr><th>LPO #</th><th>Type</th><th>Payee</th><th class="text-end">Amount</th><th>Status</th><th></th></tr>
                </thead>
                <tbody>
                    <?php foreach ($cogLpos as $rlp) echo $renderLpoRow($rlp); ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
    <?php if (!empty($expLpos)): ?>
        <div class="px-3 pt-2 pb-1 small" style="background:#F8FAFC;border-top:1px solid #E2E8F0;border-bottom:1px solid #E2E8F0;color:#334155;">
            <strong style="text-transform:capitalize;"><i class="fas fa-hand-holding-usd me-1 text-muted"></i>Expenses (Petty cash / imprest / discovery)</strong>
            <span class="float-end text-muted">Planned <strong style="color:#334155;"><?= htmlspecialchars($po['currency']); ?> <?= number_format($expPlanned); ?></strong> &middot; Paid <strong style="color:#3F5C43;"><?= htmlspecialchars($po['currency']); ?> <?= number_format($expPaid); ?></strong></span>
        </div>
        <div class="table-responsive">
            <table class="table table-sm mb-0 align-middle">
                <thead class="table-light">
                    <tr><th>LPO #</th><th>Type</th><th>Payee</th><th class="text-end">Amount</th><th>Status</th><th></th></tr>
                </thead>
                <tbody>
                    <?php foreach ($expLpos as $rlp) echo $renderLpoRow($rlp); ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
    <?php $grandPlanned = $cogPlanned + $expPlanned; $grandPaid = $cogPaid + $expPaid; ?>
    <div class="card-footer d-flex justify-content-between align-items-center py-2 small" style="background:#F8FAFC;">
        <span class="text-muted">Total planned outlay against this PO</span>
        <span>
            <strong style="color:#334155;"><?= htmlspecialchars($po['currency']); ?> <?= number_format($grandPlanned); ?></strong>
            <span class="text-muted mx-2">&middot;</span>
            Paid <strong style="color:#3F5C43;"><?= htmlspecialchars($po['currency']); ?> <?= number_format($grandPaid); ?></strong>
        </span>
    </div>
</div>
<?php endif; ?>

<?php if (!empty($invoices)): ?>
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <strong><i class="fas fa-file-invoice me-2 text-muted"></i>Invoices from this PO</strong>
        <span class="text-muted small">Σ invoiced: <strong><?= htmlspecialchars($po['currency']); ?> <?= number_format($invoicedTot); ?></strong> · Contract: <?= htmlspecialchars($po['currency']); ?> <?= number_format((float)$po['total']); ?></span>
    </div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr><th>Invoice #</th><th>Date</th><th class="text-end">Total</th><th>Status</th><th></th></tr>
            </thead>
            <tbody>
                <?php foreach ($invoices as $iv):
                    $sci = ['DRAFT'=>'bg-light text-muted','SUBMITTED'=>'bg-info text-white','PC_APPROVED'=>'bg-primary','PM_APPROVED'=>'bg-primary','ISSUED'=>'bg-success','CANCELLED'=>'bg-secondary'][$iv['invoice_workflow_status']] ?? 'bg-light text-muted';
                    $displayNo = $iv['sale_no'] ?: $iv['invoice_ref'];
                ?>
                    <tr>
                        <td><a href="<?= PROOT; ?>Sales/view/<?= (int)$iv['c0d']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars($displayNo); ?></strong></a></td>
                        <td class="text-muted small"><?= htmlspecialchars($iv['invoice_date']); ?></td>
                        <td class="text-end" style="font-weight:600;"><?= htmlspecialchars($po['currency']); ?> <?= number_format((float)$iv['total']); ?></td>
                        <td><span class="badge <?= $sci; ?>" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$iv['invoice_workflow_status']))); ?></span></td>
                        <td class="text-end"><a href="<?= PROOT; ?>Sales/view/<?= (int)$iv['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 ($anyScrub || $showSourcingCard): ?>
<script>
(function () {
    var PO_ID    = <?= (int)$po['c0d']; ?>;
    var CURRENCY = <?= json_encode((string)$po['currency']); ?>;
    var PO_TOTAL = <?= (float)$poTotal; ?>;
    var DISCOVERY_CAP_PCT  = <?= (float)$discoveryCapPct; ?>;
    var DISCOVERY_EXEC_PCT = <?= (float)$discoveryExecPct; ?>;
    var DISCOVERY_CAP_AMT  = <?= (float)$discoveryCapAmt; ?>;
    var DISCOVERY_EXEC_AMT = <?= (float)$discoveryExecAmt; ?>;

    function fire(url, itemId, note, confirmType) {
        $.post(url, { po_id: PO_ID, item_id: itemId, note: note || '' }, 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').fail(function () { $.alert({title:'Network error', type:'red'}); });
    }

    // Accept: optional note dialog
    document.querySelectorAll('.btn_accept').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var itemId = this.closest('tr').getAttribute('data-item-id');
            $.confirm({
                title: 'Accept item spec?',
                content:
                    '<div class="small mb-2">Locks the spec — PC can no longer edit unless a Reopen is issued.</div>' +
                    '<label class="form-label small">Note (optional)</label>' +
                    '<textarea id="acc_note" class="form-control form-control-sm" rows="2" placeholder="e.g. Spec confirmed with supplier, MOQ met."></textarea>',
                type: 'green',
                buttons: {
                    yes: { text: 'Accept', btnClass: 'btn-success', action: function () {
                        var note = document.getElementById('acc_note').value || '';
                        fire('<?= PROOT; ?>GoodsClientPos/acceptItemAj', itemId, note);
                    }},
                    cancel: function () {}
                }
            });
        });
    });

    // Query: mandatory note dialog
    document.querySelectorAll('.btn_query').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var itemId = this.closest('tr').getAttribute('data-item-id');
            $.confirm({
                title: 'Query item back to PC?',
                content:
                    '<div class="small mb-2">Bounces the item back to PC as QUERIED. PC + PM will be notified.</div>' +
                    '<label class="form-label small">Question / reason *</label>' +
                    '<textarea id="qry_note" class="form-control form-control-sm" rows="3" placeholder="Explain what needs changing…"></textarea>',
                type: 'orange',
                buttons: {
                    yes: { text: 'Query', btnClass: 'btn-warning', action: function () {
                        var note = (document.getElementById('qry_note').value || '').trim();
                        if (!note) { $.alert({title:'Note required', content:'Explain what needs changing.', type:'orange'}); return false; }
                        fire('<?= PROOT; ?>GoodsClientPos/queryItemAj', itemId, note);
                    }},
                    cancel: function () {}
                }
            });
        });
    });

    // Reopen (PC-only): mandatory note dialog
    document.querySelectorAll('.btn_reopen').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var itemId = this.closest('tr').getAttribute('data-item-id');
            $.confirm({
                title: 'Reopen this accepted item?',
                content:
                    '<div class="small mb-2">Flips the item back to QUERIED so specs can change. Procurement will be notified.</div>' +
                    '<label class="form-label small">Reason for reopening *</label>' +
                    '<textarea id="rop_note" class="form-control form-control-sm" rows="3" placeholder="e.g. Client changed the port count — need alternate SFPs."></textarea>',
                type: 'blue',
                buttons: {
                    yes: { text: 'Reopen', btnClass: 'btn-primary', action: function () {
                        var note = (document.getElementById('rop_note').value || '').trim();
                        if (!note) { $.alert({title:'Reason required', content:'Explain why you are reopening.', type:'orange'}); return false; }
                        fire('<?= PROOT; ?>GoodsClientPos/reopenItemAj', itemId, note);
                    }},
                    cancel: function () {}
                }
            });
        });
    });

    /* ── Batch 2 · Sourcing path handlers ─────────────────────────── */

    function setPath(path) {
        $.post('<?= PROOT; ?>GoodsClientPos/setSourcingPathAj', { po_id: PO_ID, path: path }, function (r) {
            if (r && r.ok) { rsToast('Path locked in.', 'success'); setTimeout(function(){location.reload();}, 400); }
            else $.alert({title:'Could not save', content:(r && r.msg) || 'Server error', type:'red'});
        }, 'json');
    }

    var btnDisc = document.getElementById('btn_pick_discovery');
    if (btnDisc) btnDisc.addEventListener('click', function () {
        $.confirm({
            title: 'Choose Product Discovery?',
            content: '<div class="small">Path A locks in the Discovery route. You\'ll request a cash advance next, then capture findings when you retire it.<br><br><strong>This choice cannot be reversed from the UI.</strong></div>',
            type: 'orange',
            buttons: {
                yes: { text: 'Lock in Discovery', btnClass: 'btn-warning', action: function () { setPath('DISCOVERY'); }},
                cancel: function () {}
            }
        });
    });

    var btnSkip = document.getElementById('btn_pick_skip');
    if (btnSkip) btnSkip.addEventListener('click', function () {
        $.confirm({
            title: 'Skip Discovery, go straight to RFQ?',
            content: '<div class="small">Path B — you already know your suppliers. Ready to hit "Start RFQ" once locked in.<br><br><strong>This choice cannot be reversed from the UI.</strong></div>',
            type: 'green',
            buttons: {
                yes: { text: 'Lock in Skip to RFQ', btnClass: 'btn-success', action: function () { setPath('SKIP_TO_RFQ'); }},
                cancel: function () {}
            }
        });
    });

    // Path A · Discovery cash advance request modal (Batch 4 — multi-select + % caps)
    function openDiscoveryModal() {
        var purposes = ['Market research','Sample purchase','Travel to supplier','Trade fair','Other'];
        var chkHtml = purposes.map(function (p, i) {
            return '<div class="form-check form-check-inline" style="font-size:.7rem;">' +
                   '  <input class="form-check-input dsc_purp" type="checkbox" name="purpose_categories[]" value="' + p + '" id="dsc_p_' + i + '">' +
                   '  <label class="form-check-label" for="dsc_p_' + i + '">' + p + '</label>' +
                   '</div>';
        }).join('');

        var capNote = 'Cap: ' + CURRENCY + ' ' + Math.round(DISCOVERY_CAP_AMT).toLocaleString() +
                      ' (' + DISCOVERY_CAP_PCT + '% of PO total). Exec approval above ' +
                      CURRENCY + ' ' + Math.round(DISCOVERY_EXEC_AMT).toLocaleString() +
                      ' (' + DISCOVERY_EXEC_PCT + '%).';

        $.confirm({
            title: 'Request Product Discovery advance',
            columnClass: 'col-md-7',
            content:
                '<form id="dsc_form">' +
                  '<div class="row g-2 mb-2">' +
                    '<div class="col-5"><label class="form-label small">Amount (' + CURRENCY + ') *</label>' +
                      '<input type="number" step="0.01" min="0" name="amount" class="form-control form-control-sm" required>' +
                      '<div id="dsc_route_hint" class="text-muted mt-1" style="font-size:.62rem;">Route: <strong id="dsc_route">PM &rarr; Accountant &rarr; FM</strong></div>' +
                      '<div id="dsc_cap_hint" class="text-muted" style="font-size:.62rem;">' + capNote + '</div>' +
                    '</div>' +
                    '<div class="col-7"><label class="form-label small">Purpose categories * <span class="text-muted" style="font-weight:400;font-size:.62rem;">(pick 1+)</span></label>' +
                      '<div>' + chkHtml + '</div>' +
                    '</div>' +
                  '</div>' +
                  '<div class="row g-2 mb-2">' +
                    '<div class="col-5"><label class="form-label small">Preferred method <span class="text-muted" style="font-weight:400;">(optional)</span></label>' +
                      '<select name="preferred_method" class="form-select form-select-sm">' +
                        '<option value="">— Accountant decides —</option>' +
                        '<option value="MOBILE_MONEY">Mobile money</option>' +
                        '<option value="BANK_TRANSFER">Bank transfer</option>' +
                        '<option value="PETTY_CASH">Petty cash</option>' +
                        '<option value="CASH_HANDOVER">Cash handover (last resort)</option>' +
                        '<option value="CHEQUE">Cheque</option>' +
                      '</select></div>' +
                    '<div class="col-7"><label class="form-label small">Preferred destination <span class="text-muted" style="font-weight:400;">(<a href="<?= PROOT; ?>PayeeAccounts/my" target="_blank" style="color:#7A9E7E;">register one</a> if missing)</span></label>' +
                      '<select name="preferred_account_id" id="dsc_account" class="form-select form-select-sm"><option value="">— none · Accountant picks —</option></select>' +
                    '</div>' +
                  '</div>' +
                  '<label class="form-label small">Notes / justification</label>' +
                  '<textarea name="notes" rows="2" class="form-control form-control-sm" placeholder="e.g. Chinese switch imports — profile 3 suppliers + buy 1 sample unit for interop testing."></textarea>' +
                '</form>' +
                '<div class="alert py-2 mt-2 mb-0 small" style="background:#EEF2F6;border:1px solid #7A8BA1;color:#334155;font-size:.68rem;">' +
                  '<i class="fas fa-info-circle me-1"></i>' +
                  'When you retire this advance, you\'ll capture supplier profiles + quotes. Suppliers marked <strong>Shortlist</strong> pre-load into the RFQ workspace on this PO.' +
                '</div>',
            onOpen: function () {
                var $f = document.getElementById('dsc_form');
                var $r = document.getElementById('dsc_route');
                var $h = document.getElementById('dsc_cap_hint');
                function refresh() {
                    var v = parseFloat($f.amount.value || 0);
                    // Route hint reflects the 4-step LARGE chain when >Exec threshold
                    $r.textContent = (v > DISCOVERY_EXEC_AMT)
                        ? 'PM → Accountant → FM → Exec (large)'
                        : 'PM → Accountant → FM';
                    // Turn cap hint red if amount exceeds cap
                    if (v > DISCOVERY_CAP_AMT && DISCOVERY_CAP_AMT > 0) {
                        $h.style.color = '#C48579';
                        $h.style.fontWeight = '600';
                    } else {
                        $h.style.color = '';
                        $h.style.fontWeight = '';
                    }
                }
                $f.amount.addEventListener('input', refresh); refresh();
                // Slice 8Z-k · load requester's accounts into destination picker
                $.get('<?= PROOT; ?>PayeeAccounts/listAj?payee_type=STAFF', function (rr) {
                    if (!rr || !rr.ok || !rr.rows) return;
                    var sel = document.getElementById('dsc_account');
                    rr.rows.forEach(function (a) {
                        var opt = document.createElement('option');
                        opt.value = a.id;
                        opt.textContent = a.provider_name + ' · ' + a.account_masked + ' · ' + a.holder_name + (a.status === 'PENDING' ? '  [pending FM]' : '');
                        if (a.is_default) opt.selected = true;
                        sel.appendChild(opt);
                    });
                }, 'json');
            },
            buttons: {
                save: { text: 'Submit for approval', btnClass: 'btn-success', action: function () {
                    var $f = document.getElementById('dsc_form');
                    var amt = parseFloat($f.amount.value || 0);
                    if (!(amt > 0)) { $.alert({title:'Amount required',type:'orange'}); return false; }
                    if (DISCOVERY_CAP_AMT > 0 && amt > DISCOVERY_CAP_AMT) {
                        $.alert({title:'Above cap', content:'Amount exceeds ' + DISCOVERY_CAP_PCT + '% of PO total (' + CURRENCY + ' ' + Math.round(DISCOVERY_CAP_AMT).toLocaleString() + '). Reduce or ask FM to raise the cap in Finance Settings.', type:'red'});
                        return false;
                    }
                    var chks = Array.from(document.querySelectorAll('.dsc_purp:checked')).map(function (c) { return c.value; });
                    if (!chks.length) { $.alert({title:'Purpose required', content:'Pick at least one purpose category.', type:'orange'}); return false; }
                    var payload = {
                        po_id: PO_ID, amount: amt, notes: $f.notes.value,
                        'purpose_categories': chks.join(','),
                        preferred_method: $f.preferred_method.value,
                        preferred_account_id: $f.preferred_account_id.value
                    };
                    $.post('<?= PROOT; ?>GoodsClientPos/requestDiscoveryAj', payload, function (r) {
                        if (r && r.ok) { rsToast(r.msg || 'Submitted.', 'success'); setTimeout(function(){location.reload();}, 500); }
                        else $.alert({title:'Could not submit', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json').fail(function () { $.alert({title:'Network error', type:'red'}); });
                    return false;
                }},
                cancel: function () {}
            }
        });
    }
    var btnReq = document.getElementById('btn_request_discovery');
    if (btnReq) btnReq.addEventListener('click', openDiscoveryModal);

    // Batch 4 · always-available Skip to RFQ escape hatch (works from UNSET or DISCOVERY)
    var btnSw = document.getElementById('btn_switch_skip');
    if (btnSw) btnSw.addEventListener('click', function () {
        $.confirm({
            title: 'Skip to RFQ now?',
            content: '<div class="small">Path will flip to <strong>Skip to RFQ</strong>. If you have a Discovery advance in-flight, it will complete on its own — findings can still seed the RFQ later once retirement is APPROVED.</div>',
            type: 'blue',
            buttons: {
                yes: { text: 'Skip to RFQ', btnClass: 'btn-primary', action: function () {
                    $.post('<?= PROOT; ?>GoodsClientPos/setSourcingPathAj', { po_id: PO_ID, path: 'SKIP_TO_RFQ' }, function (r) {
                        if (r && r.ok) {
                            if (r.warning) $.alert({title:'Switched — heads up', content: r.warning, type:'orange'});
                            else rsToast('Path switched.', 'success');
                            setTimeout(function(){location.reload();}, r.warning ? 1500 : 500);
                        } else $.alert({title:'Could not switch', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }},
                cancel: function () {}
            }
        });
    });
})();
</script>
<?php endif; ?>

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