<?php $this->start('body');
    $rfq         = $this->data['rfq'];
    $cpoItems    = $this->data['cpo_items']     ?? [];
    $quotes      = $this->data['quotes']        ?? [];
    $qi          = $this->data['qi_index']      ?? [];
    $availVend   = $this->data['avail_vendors'] ?? [];
    $approval    = $this->data['approval']      ?? [];
    $steps       = $this->data['steps']         ?? [];
    $lpos        = $this->data['lpos']          ?? [];
    $canEdit     = !empty($this->data['can_edit']);
    $canFinalize = !empty($this->data['can_finalize']);
    $awardGap    = (int)($this->data['award_gap']     ?? 0);
    $awardedCount= (int)($this->data['awarded_count'] ?? 0);
    $sc = ['DRAFT'=>'bg-light text-muted','OPEN'=>'bg-info text-white','EVALUATING'=>'bg-warning text-dark','AWARDED'=>'bg-success','CLOSED'=>'bg-secondary','CANCELLED'=>'bg-secondary'][$rfq['status']] ?? 'bg-light text-muted';
    $currency    = $rfq['currency'];
?>

<?php
    // Slice 8Z-i · Batch 3 — count Discovery-seeded invitees for the top banner
    $discoverySeedCount = 0;
    foreach ($quotes as $q) if (!empty($q['discovery_finding_id'])) $discoverySeedCount++;
?>

<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-signature me-2 text-muted"></i><?= htmlspecialchars($rfq['rfq_no']); ?></h5>
        <div class="text-muted" style="font-size:.72rem;">
            Client PO <a href="<?= PROOT; ?>GoodsClientPos/view/<?= (int)$rfq['client_po_id']; ?>"><?= htmlspecialchars($rfq['client_po_no']); ?></a>
            · <?= htmlspecialchars($rfq['customer_name']); ?>
            · <?= htmlspecialchars($rfq['project_no'] ?: '—'); ?>
            · <span class="badge <?= $sc; ?>" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower($rfq['status'])); ?></span>
        </div>
    </div>
    <a href="<?= PROOT; ?>GoodsRfq" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> All RFQs</a>
</div>

<?php if ($discoverySeedCount > 0): ?>
    <div class="alert py-2 mb-3 small d-flex align-items-center justify-content-between" style="background:#FEF3E7;border:1px solid #8B6914;color:#5B4F3C;font-size:.72rem;">
        <div><i class="fas fa-binoculars me-2"></i><strong><?= $discoverySeedCount; ?></strong> supplier<?= $discoverySeedCount === 1 ? '' : 's'; ?> pre-invited from your Product Discovery shortlist. You can still invite more manually below.</div>
        <a href="<?= PROOT; ?>GoodsClientPos/view/<?= (int)$rfq['client_po_id']; ?>" class="text-decoration-none" style="color:#5B4F3C;font-weight:600;">View source PO <i class="fas fa-arrow-right ms-1"></i></a>
    </div>
<?php endif; ?>

<?php if ($canEdit && !empty($availVend)): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong><i class="fas fa-user-plus me-2 text-muted"></i>Invite a supplier</strong></div>
    <div class="card-body p-3">
        <div class="input-group">
            <select id="rsInviteVendor" class="form-select form-select-sm" style="max-width:400px;">
                <option value="">— pick a vendor —</option>
                <?php foreach ($availVend as $v): ?>
                    <option value="<?= (int)$v['c0d']; ?>"><?= htmlspecialchars($v['vendor_name']); ?><?php if ($v['vendor_tin']): ?> · TIN <?= htmlspecialchars($v['vendor_tin']); ?><?php endif; ?></option>
                <?php endforeach; ?>
            </select>
            <button type="button" class="btn btn-sm btn-primary" style="background:<?= BRAND_COLOR; ?>;border-color:<?= BRAND_COLOR; ?>;" onclick="rsInviteVendor()">
                <i class="fas fa-plus me-1"></i> Invite
            </button>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if (empty($quotes)): ?>
    <div class="alert alert-info py-2 mb-3 small">No suppliers invited yet. Invite a supplier above to start capturing quotes.</div>
<?php else: ?>

<!-- ── Matrix ────────────────────────────────────────────────────────────── -->
<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-table me-2 text-muted"></i>Quote matrix</strong>
        <div class="text-muted small">
            <?= $awardedCount; ?> of <?= count($cpoItems); ?> line(s) awarded
            <?php if ($awardGap === 0 && $awardedCount > 0): ?>
                <span class="badge bg-success ms-2">All lines awarded</span>
            <?php endif; ?>
        </div>
    </div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th style="min-width:260px;">Item</th>
                    <th class="text-end">Qty</th>
                    <?php foreach ($quotes as $q):
                        $qcls = ['INVITED'=>'bg-light text-muted','QUOTED'=>'bg-info text-white','AWARDED'=>'bg-success','DECLINED'=>'bg-secondary'][$q['status']] ?? 'bg-light text-muted';
                    ?>
                        <th style="min-width:220px;">
                            <div>
                                <strong><?= htmlspecialchars($q['vendor_name']); ?></strong>
                                <span class="badge <?= $qcls; ?>" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower($q['status'])); ?></span>
                                <?php if (!empty($q['discovery_finding_id'])): ?>
                                    <span class="badge ms-1" style="background:#FEF3E7;color:#8B6914;border:1px solid #8B6914;font-size:.55rem;text-transform:capitalize;" title="Pre-invited from Product Discovery shortlist"><i class="fas fa-binoculars me-1"></i>Discovery</span>
                                <?php endif; ?>
                                <?php if ((int)$q['vendor_id'] === 0): ?>
                                    <span class="badge ms-1" style="background:#F1F5F9;color:#334155;border:1px solid #94A3B8;font-size:.55rem;text-transform:capitalize;" title="Not yet in the vendor master — promote via Vendors module">Ad-hoc</span>
                                <?php endif; ?>
                            </div>
                            <div class="text-muted" style="font-size:.65rem;font-weight:400;"><?= htmlspecialchars($q['vendor_tin'] ?: '—'); ?></div>
                            <?php if ($canEdit): ?>
                                <button type="button" class="btn btn-sm btn-outline-primary mt-1" onclick="rsAwardAllFromSupplier(<?= (int)$q['c0d']; ?>)" title="Award every line this supplier quoted">
                                    <i class="fas fa-star me-1"></i> Award all
                                </button>
                            <?php endif; ?>
                        </th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($cpoItems as $item):
                    $cpoItemId = (int)$item['c0d'];
                ?>
                    <tr>
                        <td>
                            <strong><?= htmlspecialchars($item['description']); ?></strong>
                            <div class="text-muted small">Planned Cog: <?= number_format((float)$item['unit_price_cog']); ?> · Sell: <?= number_format((float)$item['unit_price_sell']); ?></div>
                        </td>
                        <td class="text-end"><?= number_format((float)$item['qty'], (fmod((float)$item['qty'],1)==0?0:2)); ?> <span class="text-muted small"><?= htmlspecialchars($item['unit']); ?></span></td>
                        <?php foreach ($quotes as $q):
                            $qId    = (int)$q['c0d'];
                            $cell   = $qi[$cpoItemId][$qId] ?? null;
                            $up     = $cell ? (float)$cell['unit_price']    : 0;
                            $qa     = $cell ? (float)$cell['qty_available'] : 0;
                            $awd    = $cell && (int)$cell['awarded_flag'] === 1;
                            $qiId   = $cell ? (int)$cell['c0d'] : 0;
                            // Compare vs planned Cog: cheaper = better
                            $vsCog  = ((float)$item['unit_price_cog'] > 0 && $up > 0)
                                       ? (($up - (float)$item['unit_price_cog']) / (float)$item['unit_price_cog']) * 100 : null;
                            $cellBg = $awd ? 'background:#dcfce7;' : ($vsCog !== null && $vsCog < 0 ? 'background:#f0f9ff;' : '');
                        ?>
                            <td style="<?= $cellBg; ?>">
                                <?php if ($canEdit): ?>
                                    <div class="input-group input-group-sm">
                                        <span class="input-group-text" style="font-size:.68rem;">Unit</span>
                                        <input type="number" step="0.01" class="form-control form-control-sm"
                                               data-rsQuoteId="<?= $qId; ?>" data-rsCpoItemId="<?= $cpoItemId; ?>"
                                               value="<?= $up > 0 ? htmlspecialchars((string)$up) : ''; ?>"
                                               onchange="rsSaveQuoteItem(this, <?= $qId; ?>, <?= $cpoItemId; ?>)">
                                    </div>
                                <?php elseif ($up > 0): ?>
                                    <div><strong><?= number_format($up); ?></strong></div>
                                <?php else: ?>
                                    <div class="text-muted small">no quote</div>
                                <?php endif; ?>
                                <?php if ($up > 0): ?>
                                    <div class="text-muted small mt-1">
                                        Line: <?= number_format($up * (float)$item['qty']); ?>
                                        <?php if ($vsCog !== null): ?>
                                            <span style="color:<?= $vsCog < 0 ? '#22c55e' : ($vsCog > 5 ? '#ef4444' : '#f59e0b'); ?>;">
                                                (<?= $vsCog < 0 ? '' : '+'; ?><?= number_format($vsCog, 1); ?>% vs Cog)
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                    <?php if ($canEdit): ?>
                                        <div class="mt-1">
                                            <button type="button" class="btn btn-sm <?= $awd ? 'btn-success' : 'btn-outline-success'; ?>"
                                                    onclick="rsAward(<?= $qiId; ?>)">
                                                <i class="fas <?= $awd ? 'fa-check-circle' : 'fa-circle'; ?> me-1"></i> <?= $awd ? 'Awarded' : 'Award'; ?>
                                            </button>
                                        </div>
                                    <?php elseif ($awd): ?>
                                        <span class="badge bg-success mt-1"><i class="fas fa-check-circle me-1"></i>Awarded</span>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </td>
                        <?php endforeach; ?>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php if ($canFinalize): ?>
    <div class="card-footer bg-white text-end">
        <?php if ($awardGap > 0): ?>
            <span class="text-muted small me-3"><?= $awardGap; ?> line(s) still need an award before finalizing.</span>
        <?php endif; ?>
        <button type="button" class="btn btn-sm btn-primary" style="background:<?= BRAND_COLOR; ?>;border-color:<?= BRAND_COLOR; ?>;"
                onclick="rsFinalize()" <?= $awardGap > 0 ? '' : ''; ?>>
            <i class="fas fa-paper-plane me-1"></i> Finalize &amp; Submit LPO batch
        </button>
    </div>
    <?php endif; ?>
</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>GOODS_LPO_APPROVAL · batch 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
                $curSid = (int)($approval['current_step_id'] ?? 0);
                $curNo  = 0; foreach ($steps as $st) if ((int)$st['c0d']===$curSid) $curNo = (int)$st['step_no'];
            ?>
            <?php foreach ($steps as $i => $st):
                $n  = (int)$st['step_no'];
                $stt = ($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'][$stt];
                $col  = ['done'=>'#22c55e','now'=>'#f59e0b','todo'=>'#cbd5e1'][$stt];
            ?>
                <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($st['step_label']); ?></div>
                            <div class="text-muted" style="font-size:.62rem;text-transform:uppercase;"><?= htmlspecialchars($st['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 endif; ?>

<?php if (!empty($lpos)): ?>
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white"><strong><i class="fas fa-clipboard-list me-2 text-muted"></i>Supplier LPOs drafted</strong></div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr><th>LPO #</th><th>Supplier</th><th class="text-end">Amount</th><th>Status</th><th></th></tr>
            </thead>
            <tbody>
                <?php foreach ($lpos as $l):
                    $lc = ['DRAFT'=>'bg-light text-muted','SUBMITTED'=>'bg-info text-white','APPROVED'=>'bg-success','ISSUED'=>'bg-primary','PAID'=>'bg-success','DECLINED'=>'bg-danger','CLOSED'=>'bg-secondary'][$l['cash_out_status']] ?? 'bg-light text-muted';
                ?>
                    <tr>
                        <td><a href="<?= PROOT; ?>Lpos/view/<?= (int)$l['c0d']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars($l['lpo_no']); ?></strong></a></td>
                        <td><?= htmlspecialchars($l['payee_name']); ?></td>
                        <td class="text-end"><?= htmlspecialchars($l['currency']); ?> <?= number_format((float)$l['amount']); ?></td>
                        <td><span class="badge <?= $lc; ?>" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower($l['cash_out_status'])); ?></span></td>
                        <td class="text-end"><a href="<?= PROOT; ?>Lpos/view/<?= (int)$l['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; ?>

<script>
function rsInviteVendor() {
    const sel = document.getElementById('rsInviteVendor');
    const vid = parseInt(sel.value || '0', 10);
    if (!vid) { alert('Pick a vendor first.'); return; }
    fetch('<?= PROOT; ?>GoodsRfq/inviteSupplierAj', {
        method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'rfq_id=<?= (int)$rfq['c0d']; ?>&vendor_id=' + vid
    }).then(r=>r.json()).then(j=>{ if (!j.ok) { alert(j.msg||'Failed'); return; } location.reload(); });
}
function rsSaveQuoteItem(inp, quoteId, cpoItemId) {
    const up = parseFloat(inp.value || '0');
    if (up < 0) return;
    fetch('<?= PROOT; ?>GoodsRfq/saveQuoteItemAj', {
        method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'rfq_quote_id=' + quoteId + '&client_po_item_id=' + cpoItemId + '&unit_price=' + up + '&qty_available=0&lead_time_days=0'
    }).then(r=>r.json()).then(j=>{ if (!j.ok) { alert(j.msg||'Failed'); return; } location.reload(); });
}
function rsAward(qiId) {
    fetch('<?= PROOT; ?>GoodsRfq/awardAj', {
        method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'quote_item_id=' + qiId
    }).then(r=>r.json()).then(j=>{ if (!j.ok) { alert(j.msg||'Failed'); return; } location.reload(); });
}
function rsAwardAllFromSupplier(qId) {
    fetch('<?= PROOT; ?>GoodsRfq/awardAllFromSupplierAj', {
        method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'rfq_quote_id=' + qId
    }).then(r=>r.json()).then(j=>{ alert(j.msg||(j.ok?'Awarded':'Failed')); if (j.ok) location.reload(); });
}
function rsFinalize() {
    if (!confirm('Finalize this RFQ? All awarded lines will become supplier LPOs and go into the PC→PM→FM→Exec approval chain.')) return;
    fetch('<?= PROOT; ?>GoodsRfq/finalizeAj', {
        method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'rfq_id=<?= (int)$rfq['c0d']; ?>'
    }).then(r=>r.json()).then(j=>{ alert(j.msg||(j.ok?'Finalized':'Failed')); if (j.ok) location.reload(); });
}
</script>

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