<?php $this->start('body');
    $cr       = $this->data['cr'];
    $p        = $this->data['project'];
    $ph       = $this->data['phase'] ?? [];
    $progress = $this->data['progress'] ?? [];
    $lines    = $this->data['sourceable_lines'] ?? [];
    $lpos     = $this->data['lpos'] ?? [];
    $issued   = $this->data['issued'] ?? [];
    $payments = $this->data['payments'] ?? [];
    $vendors  = $this->data['vendors'] ?? [];

    // Warm/faded palette (per user preference for rsflow.dspera new views)
    $pillarChip = [
        'PRELIMINARIES' => ['#EDE7DC', '#5B4F3C'],
        'MANPOWER'      => ['#E4DEF0', '#4A3D6B'],
        'MATERIALS'     => ['#E1EBDF', '#3D5B44'],
        'EQUIPMENT'     => ['#F0E1D9', '#6B3F2A'],
        'TOOLS'         => ['#EAE7DA', '#5B5738'],
        'SUBCONTRACTS'  => ['#DDE4E9', '#3D4E5B'],
        'OVERHEADS'     => ['#F1DDDD', '#6B3F3F'],
    ];
    $sourceable = ['MATERIALS','TOOLS','SUBCONTRACTS','EQUIPMENT'];
    $statusPill = [
        'DRAFT'      => ['#f59e0b', 'Draft'],
        'SUBMITTED'  => ['#0ea5e9', 'Submitted'],
        'APPROVED'   => ['#22c55e', 'Approved'],
        'ACTIVE'     => ['#166534', 'Active'],
        'CLOSED'     => ['#7A8BA1', 'Closed'],
        'DECLINED'   => ['#dc2626', 'Declined'],
        'CANCELLED'  => ['#94a3b8', 'Cancelled'],
    ];
?>
<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-truck-loading me-1 text-muted"></i>
            Fulfil · <?= htmlspecialchars($cr['cr_no']); ?>
            <span class="text-muted small ms-1">v<?= (int)$cr['version']; ?></span>
        </h5>
        <div class="text-muted" style="font-size:.72rem;">
            <?= htmlspecialchars($p['project_no'] ?? ''); ?> · <?= htmlspecialchars($p['project_name'] ?? ''); ?>
            <?php if (!empty($ph)): ?> · Ph.<?= (int)$ph['phase_no']; ?> · <?= htmlspecialchars($ph['title']); ?><?php endif; ?>
        </div>
    </div>
    <a href="<?= PROOT; ?>WorksCrs/view/<?= (int)$cr['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> CR detail</a>
</div>

<?php if ($cr['status'] !== 'ACTIVE'): ?>
    <div class="alert py-2" style="background:#FEF3C7;border:1px solid #F59E0B;color:#78350F;">
        <i class="fas fa-exclamation-triangle me-1"></i>
        <strong>CR not ACTIVE</strong> · current status <?= htmlspecialchars($cr['status']); ?>. Sourcing is disabled until the CR is approved end-to-end.
    </div>
<?php else: ?>
    <div class="d-flex align-items-center justify-content-between py-2 px-3 mb-3 rounded" style="background:#FAF6EF;border:1px solid #E4DAC7;">
        <div style="font-size:.8rem;color:#5B4F3C;">
            <i class="fas fa-flag-checkered me-1"></i>
            When every LPO on this CR is <strong>PAID</strong>, PC can close the CR and freeze a per-pillar variance snapshot.
        </div>
        <button type="button" id="btn_close_cr" class="btn btn-sm" style="background:#B87A5A;border-color:#B87A5A;color:#fff;">
            <i class="fas fa-times-circle me-1"></i> Close CR
        </button>
    </div>
<?php endif; ?>

<!-- ── Per-pillar progress ────────────────────────────────────────────── -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Pillar progress</strong>
        <span class="text-muted small ms-2">Sourced via LPO (sage) · Delivered on site (steel) · Paid (terracotta)</span>
    </div>
    <div class="card-body p-3" style="background:#FAF8F4;">
        <div class="row g-2">
            <?php foreach ($progress as $pillar => $ppr):
                $chip = $pillarChip[$pillar] ?? ['#e5e7eb', '#374151'];
            ?>
                <div class="col-md-6 col-lg-4">
                    <div class="p-2 border rounded" style="background:#fff;">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                            <span class="badge" style="background:<?= $chip[0]; ?>;color:<?= $chip[1]; ?>;font-weight:600;text-transform:capitalize;">
                                <?= strtolower(str_replace('_', ' ', $pillar)); ?>
                            </span>
                            <span class="small text-muted"><?= number_format($ppr['budget']); ?></span>
                        </div>
                        <div style="height:6px;background:#F1EDE4;border-radius:3px;position:relative;">
                            <div style="height:100%;background:#7A9E7E;border-radius:3px;width:<?= min(100, (float)$ppr['sourced_pct']); ?>%;"></div>
                        </div>
                        <div style="height:6px;background:#F1EDE4;border-radius:3px;margin-top:3px;position:relative;">
                            <div style="height:100%;background:#4A6D8A;border-radius:3px;width:<?= min(100, (float)$ppr['delivered_pct']); ?>%;"></div>
                        </div>
                        <div style="height:6px;background:#F1EDE4;border-radius:3px;margin-top:3px;position:relative;">
                            <div style="height:100%;background:#B87A5A;border-radius:3px;width:<?= min(100, (float)$ppr['paid_pct']); ?>%;"></div>
                        </div>
                        <div class="d-flex justify-content-between mt-1" style="font-size:.68rem;">
                            <span style="color:#7A9E7E;">Src <?= number_format($ppr['sourced']); ?> · <?= (float)$ppr['sourced_pct']; ?>%</span>
                            <span style="color:#4A6D8A;">Del <?= number_format($ppr['delivered']); ?> · <?= (float)$ppr['delivered_pct']; ?>%</span>
                            <span style="color:#B87A5A;">Pd <?= number_format($ppr['paid']); ?> · <?= (float)$ppr['paid_pct']; ?>%</span>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- ── Sourceable-line picker per pillar ──────────────────────────────── -->
<?php foreach ($sourceable as $pillar):
    $chip = $pillarChip[$pillar];
    $items = $lines[$pillar] ?? [];
    $canSource = $cr['status'] === 'ACTIVE';
?>
<div class="card border-0 shadow-sm mb-3" id="pillar-<?= strtolower($pillar); ?>">
    <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <div>
            <span class="badge me-1" style="background:<?= $chip[0]; ?>;color:<?= $chip[1]; ?>;font-weight:600;text-transform:capitalize;">
                <?= strtolower(str_replace('_', ' ', $pillar)); ?>
            </span>
            <strong>Draft supplier LPO</strong>
            <span class="text-muted small ms-1"><?= count($items); ?> line<?= count($items) === 1 ? '' : 's'; ?> available</span>
        </div>
    </div>
    <?php if (empty($items)): ?>
        <div class="card-body p-3 text-muted small">No <?= strtolower($pillar); ?> lines on this CR (or all fully sourced).</div>
    <?php else: ?>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th style="width:32px;"></th>
                    <th>Line</th>
                    <th style="width:110px;" class="text-end">Budget qty</th>
                    <th style="width:120px;" class="text-end">Budget total</th>
                    <th style="width:120px;" class="text-end">Sourced</th>
                    <th style="width:120px;" class="text-end">Remaining</th>
                    <th style="width:110px;">This qty</th>
                    <th style="width:130px;">This unit price</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($items as $it):
                    $remaining = (float)$it['remaining_amount'];
                    $spent     = $remaining <= 0.01;
                ?>
                <tr class="pillar-line" data-pillar="<?= $pillar; ?>" data-line-id="<?= (int)$it['line_id']; ?>" style="<?= $spent ? 'opacity:.55;' : ''; ?>">
                    <td><input type="checkbox" class="line-pick" <?= $spent || !$canSource ? 'disabled' : ''; ?>></td>
                    <td>
                        <div><?= htmlspecialchars($it['description']); ?></div>
                        <div class="text-muted small"><?= htmlspecialchars($it['unit']); ?> · unit cost <?= number_format((float)$it['unit_cost']); ?></div>
                    </td>
                    <td class="text-end small"><?= number_format((float)$it['qty'], 2); ?></td>
                    <td class="text-end"><?= number_format((float)$it['line_total']); ?></td>
                    <td class="text-end small"><?= number_format((float)$it['sourced_amount']); ?></td>
                    <td class="text-end"><strong><?= number_format($remaining); ?></strong></td>
                    <td><input type="number" step="0.01" min="0" class="form-control form-control-sm line-qty" value="<?= $spent ? '' : htmlspecialchars((string)$it['qty']); ?>" <?= $spent || !$canSource ? 'disabled' : ''; ?>></td>
                    <td><input type="number" step="0.01" min="0" class="form-control form-control-sm line-price" value="<?= $spent ? '' : htmlspecialchars((string)$it['unit_cost']); ?>" <?= $spent || !$canSource ? 'disabled' : ''; ?>></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <div class="card-footer bg-white">
        <div class="row g-2 align-items-end">
            <div class="col-md-5">
                <label class="form-label" style="font-size:.78rem;">Vendor</label>
                <select class="form-select form-select-sm vendor-pick" <?= !$canSource ? 'disabled' : ''; ?>>
                    <option value="0">— pick vendor —</option>
                    <?php foreach ($vendors as $v): ?>
                        <option value="<?= (int)$v['c0d']; ?>" data-name="<?= htmlspecialchars($v['vendor_name']); ?>"><?= htmlspecialchars($v['vendor_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label" style="font-size:.78rem;">Currency</label>
                <input type="text" class="form-control form-control-sm currency-pick" value="<?= htmlspecialchars($p['currency'] ?? 'TZS'); ?>" <?= !$canSource ? 'disabled' : ''; ?>>
            </div>
            <div class="col-md-4 text-end">
                <button type="button" class="btn btn-sm btn-primary btn-draft-lpo"
                        data-pillar="<?= $pillar; ?>"
                        style="background:#7A9E7E;border-color:#7A9E7E;"
                        <?= !$canSource ? 'disabled' : ''; ?>>
                    <i class="fas fa-file-invoice me-1"></i> Draft LPO for picked lines
                </button>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>
<?php endforeach; ?>

<!-- ── LPOs already sourced from this CR ──────────────────────────────── -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>LPOs sourced from this CR · <?= count($lpos); ?></strong></div>
    <?php if (empty($lpos)): ?>
        <div class="card-body p-3 text-muted small">No LPOs drafted yet.</div>
    <?php else: ?>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th>LPO</th>
                    <th style="width:130px;">Pillar</th>
                    <th>Vendor</th>
                    <th class="text-end">Amount</th>
                    <th style="width:130px;">Status</th>
                    <th style="width:120px;" class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($lpos as $l):
                    $sp = $statusPill[$l['cash_out_status']] ?? ['#94a3b8', $l['cash_out_status']];
                    $ch = $pillarChip[$l['source_cr_pillar']] ?? ['#e5e7eb', '#374151'];
                ?>
                <?php $isPending = strpos((string)$l['lpo_no'], 'PENDING-') === 0; ?>
                <tr>
                    <td>
                        <?php if ($isPending): ?>
                            <span class="badge" style="background:#EDE7DC;color:#5B4F3C;">PENDING</span>
                            <div class="text-muted small" style="font-size:.65rem;" title="Real LPO number allocated only on Exec approval per Slice 8k">no # yet</div>
                        <?php else: ?>
                            <code><?= htmlspecialchars($l['lpo_no']); ?></code>
                        <?php endif; ?>
                    </td>
                    <td><span class="badge" style="background:<?= $ch[0]; ?>;color:<?= $ch[1]; ?>;text-transform:capitalize;"><?= strtolower($l['source_cr_pillar']); ?></span></td>
                    <td class="small"><?= htmlspecialchars($l['payee_name']); ?></td>
                    <td class="text-end"><strong><?= number_format((float)$l['amount']); ?></strong> <?= htmlspecialchars($l['currency']); ?></td>
                    <td>
                        <span class="badge" style="background:<?= $sp[0]; ?>;color:#fff;text-transform:capitalize;"><?= strtolower($sp[1]); ?></span>
                        <?php if ($l['cash_out_status'] === 'SUBMITTED' && (int)$l['approval_id'] > 0): ?>
                            <div class="small text-muted mt-1"><i class="fas fa-hourglass-half me-1"></i>in chain</div>
                        <?php endif; ?>
                    </td>
                    <td class="text-end">
                        <?php if ($l['cash_out_status'] === 'DRAFT'): ?>
                            <button type="button" class="btn btn-sm btn-outline-primary btn-submit-lpo me-1" data-lpo-id="<?= (int)$l['c0d']; ?>" title="Submit for WORKS_LPO_APPROVAL chain (PC → PM → FM → Exec)">
                                <i class="fas fa-paper-plane"></i>
                            </button>
                        <?php endif; ?>
                        <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>
    <?php endif; ?>
</div>

<!-- ── Payments allocated to this CR ──────────────────────────────────── -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Payments · <?= count($payments); ?></strong>
        <span class="text-muted small ms-2">Payment vouchers + bank payments allocated to LPOs sourced from this CR</span>
    </div>
    <?php if (empty($payments)): ?>
        <div class="card-body p-3 text-muted small">No payments yet. Once a supplier LPO is PV-prepped, scheduled and paid, it appears here.</div>
    <?php else: ?>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th>Payment</th>
                    <th>LPO · Vendor</th>
                    <th style="width:130px;">Pillar</th>
                    <th style="width:110px;">PV</th>
                    <th style="width:110px;">Date</th>
                    <th style="width:140px;">Method · Ref</th>
                    <th class="text-end" style="width:140px;">Amount</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($payments as $pay):
                    $ch = $pillarChip[$pay['source_cr_pillar']] ?? ['#e5e7eb', '#374151'];
                ?>
                <tr>
                    <td><code><?= htmlspecialchars($pay['payment_no']); ?></code></td>
                    <td class="small">
                        <a href="<?= PROOT; ?>Lpos/view/<?= (int)$pay['lpo_id']; ?>"><?= htmlspecialchars($pay['lpo_no']); ?></a>
                        <div class="text-muted"><?= htmlspecialchars($pay['payee_name']); ?></div>
                    </td>
                    <td><span class="badge" style="background:<?= $ch[0]; ?>;color:<?= $ch[1]; ?>;text-transform:capitalize;"><?= strtolower((string)$pay['source_cr_pillar']); ?></span></td>
                    <td class="small"><?= htmlspecialchars((string)($pay['pv_no'] ?? '—')); ?></td>
                    <td class="small text-muted"><?= htmlspecialchars((string)$pay['payment_date']); ?></td>
                    <td class="small text-muted">
                        <?= htmlspecialchars(str_replace('_', ' ', (string)$pay['payment_method'])); ?>
                        <?php if (!empty($pay['reference_no'])): ?><div><?= htmlspecialchars($pay['reference_no']); ?></div><?php endif; ?>
                    </td>
                    <td class="text-end"><strong><?= number_format((float)$pay['alloc_amount']); ?></strong></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<!-- ── Delivery register ──────────────────────────────────────────────── -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>On-site delivery register · <?= count($issued); ?></strong>
        <span class="text-muted small ms-2">Record what physically landed on site — closes the loop against the CR budget</span>
    </div>
    <?php if (empty($issued)): ?>
        <div class="card-body p-3 text-muted small">Nothing recorded yet. Deliveries land here as they happen — record via the LPO page.</div>
    <?php else: ?>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th>Description</th>
                    <th style="width:130px;">Pillar</th>
                    <th style="width:110px;">Date</th>
                    <th style="width:130px;">Recorded by</th>
                    <th style="width:110px;" class="text-end">Qty</th>
                    <th style="width:130px;" class="text-end">Total</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($issued as $iss):
                    $ch = $pillarChip[$iss['cr_pillar']] ?? ['#e5e7eb', '#374151'];
                ?>
                <tr>
                    <td><?= htmlspecialchars($iss['description']); ?><?php if (!empty($iss['notes'])): ?><div class="text-muted small"><?= htmlspecialchars($iss['notes']); ?></div><?php endif; ?></td>
                    <td><span class="badge" style="background:<?= $ch[0]; ?>;color:<?= $ch[1]; ?>;text-transform:capitalize;"><?= strtolower($iss['cr_pillar']); ?></span></td>
                    <td class="small text-muted"><?= htmlspecialchars($iss['issued_on']); ?></td>
                    <td class="small text-muted"><?= htmlspecialchars($iss['issued_by_name']); ?></td>
                    <td class="text-end"><?= rtrim(rtrim(number_format((float)$iss['qty'], 4), '0'), '.'); ?> <?= htmlspecialchars($iss['unit']); ?></td>
                    <td class="text-end"><strong><?= number_format((float)$iss['total']); ?></strong></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

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

<?php $this->start('section_js'); ?>
<script>
$('#btn_close_cr').on('click', function () {
    $.confirm({
        title: 'Close this CR?',
        content: '<p style="font-size:.85rem;color:#5B4F3C;">Once closed, sourcing and delivery writes are locked and a per-pillar variance snapshot is frozen.</p>' +
                 '<div class="form-group"><label class="form-label" style="font-size:.78rem;">Reason (optional)</label>' +
                 '<textarea id="close_reason" class="form-control form-control-sm" rows="2" placeholder="e.g. Phase 1 complete · scope executed"></textarea></div>',
        boxWidth: '440px',
        useBootstrap: false,
        buttons: {
            confirm: {
                text: 'Close CR', btnClass: 'btn-danger',
                action: function () {
                    var reason = $('#close_reason').val() || '';
                    $.post('<?= PROOT; ?>WorksCrs/closeAj', { id: <?= (int)$cr['c0d']; ?>, reason: reason }, 'json')
                        .done(function (r) {
                            if (r && r.ok) { rsToast('CR closed.', 'success'); location.href = '<?= PROOT; ?>WorksCrs/view/<?= (int)$cr['c0d']; ?>'; }
                            else            { rsToast('Cannot close: ' + (r.msg || 'unknown'), 'error'); }
                        });
                }
            },
            cancel: { text: 'Cancel' }
        }
    });
});

$('.btn-draft-lpo').on('click', function () {
    var pillar = $(this).data('pillar');
    var card   = $('#pillar-' + pillar.toLowerCase());
    var vSel   = card.find('.vendor-pick');
    var vId    = parseInt(vSel.val(), 10) || 0;
    var vNm    = vSel.find('option:selected').data('name') || vSel.find('option:selected').text();
    var cur    = card.find('.currency-pick').val() || 'TZS';
    if (vId <= 0) { rsToast('Pick a vendor.', 'error'); return; }

    var lines = [];
    card.find('.pillar-line').each(function () {
        var $tr = $(this);
        if (!$tr.find('.line-pick').is(':checked')) return;
        var qty = parseFloat($tr.find('.line-qty').val()   || '0');
        var up  = parseFloat($tr.find('.line-price').val() || '0');
        if (qty > 0 && up > 0) {
            lines.push({ line_id: $tr.data('line-id'), qty: qty, unit_price: up });
        }
    });
    if (!lines.length) { rsToast('No lines picked or qty/price missing.', 'error'); return; }

    $.post('<?= PROOT; ?>WorksCrs/draftLpoAj', {
        cr_id:       <?= (int)$cr['c0d']; ?>,
        pillar:      pillar,
        vendor_id:   vId,
        vendor_name: vNm,
        currency:    cur,
        lines:       lines
    }, 'json').done(function (r) {
        if (r && r.ok) {
            rsToast('LPO drafted.', 'success');
            location.reload();
        } else {
            rsToast('Failed: ' + (r.msg || 'unknown'), 'error');
        }
    });
});

// Submit a DRAFT LPO into WORKS_LPO_APPROVAL. Reuses the existing Lpos/submitAj endpoint —
// the LPO row already has approval_chain_key='WORKS_LPO_APPROVAL' stamped at draft time.
$('.btn-submit-lpo').on('click', function () {
    var lid = $(this).data('lpo-id');
    $.confirm({
        title: 'Submit LPO for approval?',
        content: '<p style="font-size:.85rem;color:#5B4F3C;">Kicks off the WORKS_LPO_APPROVAL chain: PC → PM → FM → Exec. Payables cannot prep a PV until the chain reaches APPROVED.</p>',
        boxWidth: '440px', useBootstrap: false,
        buttons: {
            confirm: {
                text: 'Submit', btnClass: 'btn-primary',
                action: function () {
                    $.post('<?= PROOT; ?>Lpos/submitAj', { lpo_id: lid }, 'json')
                        .done(function (r) {
                            if (r && r.ok) { rsToast('Submitted for approval.', 'success'); location.reload(); }
                            else            { rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); }
                        });
                }
            },
            cancel: { text: 'Cancel' }
        }
    });
});
</script>
<?php $this->end(); ?>
