<?php $this->start('body');
    $p        = $this->data['project'];
    $pool     = $this->data['pool']     ?? [];
    $holdings = $this->data['holdings'] ?? [];
    $releases = $this->data['releases'] ?? [];

    $inPool     = (float)($pool['in_pool']     ?? 0);
    $totalHeld  = (float)($pool['total_held']  ?? 0);
    $totalRel   = (float)($pool['total_released'] ?? 0);
    $daysToDlp  = $pool['days_to_dlp'];
    $dlpBand    = ($daysToDlp !== null && $daysToDlp <= 0)
                  ? ['#B87A5A','#F3E5D9','Past DLP · chase customer']
                  : ['#5B4F3C','#EDE7DC','In DLP']; // colour scheme mirrors supplier-side
?>
<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-hourglass-half me-1 text-muted"></i>
            Customer retention · <?= htmlspecialchars($p['project_no']); ?>
        </h5>
        <div class="text-muted" style="font-size:.72rem;">
            <?= htmlspecialchars($p['project_customer']); ?> · <?= htmlspecialchars($p['project_name']); ?>
            · contract retention <?= number_format((float)$pool['contract_pct'], 2); ?>% · DLP <?= (int)$pool['contract_dlp_days']; ?> days
        </div>
    </div>
    <div>
        <a href="<?= PROOT; ?>WorksIpcs/list/<?= (int)$p['c0d']; ?>"                 class="btn btn-sm btn-outline-secondary"><i class="fas fa-file-signature me-1"></i> IPCs</a>
        <a href="<?= PROOT; ?>WorksRetention/pool/<?= (int)$p['c0d']; ?>"            class="btn btn-sm btn-outline-secondary"><i class="fas fa-hand-holding-usd me-1"></i> Supplier retention</a>
        <a href="<?= PROOT; ?>WorksProjectReport/view/<?= (int)$p['c0d']; ?>"        class="btn btn-sm btn-outline-secondary"><i class="fas fa-chart-line me-1"></i> Project report</a>
    </div>
</div>

<!-- ── Pool summary ──────────────────────────────────────────────────── -->
<div class="row g-2 mb-3">
    <div class="col-md-3">
        <div class="p-3 border rounded" style="background:#fff;">
            <div class="text-muted small" style="text-transform:uppercase;letter-spacing:.4px;font-size:.6rem;"><i class="fas fa-lock me-1"></i> Held by customer</div>
            <div style="font-weight:700;font-size:1.15rem;color:#5B4F3C;"><?= number_format($totalHeld); ?></div>
            <div class="small text-muted">across <?= (int)$pool['count_ipcs']; ?> IPC<?= (int)$pool['count_ipcs'] === 1 ? '' : 's'; ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="p-3 border rounded" style="background:#F3E5D9;">
            <div class="text-muted small" style="text-transform:uppercase;letter-spacing:.4px;font-size:.6rem;"><i class="fas fa-inbox me-1"></i> In-pool (still owed to us)</div>
            <div style="font-weight:700;font-size:1.15rem;color:#6B3F2A;"><?= number_format($inPool); ?></div>
            <div class="small" style="color:#6B3F2A;">held − released</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="p-3 border rounded" style="background:#EAF2E8;">
            <div class="text-muted small" style="text-transform:uppercase;letter-spacing:.4px;font-size:.6rem;"><i class="fas fa-check me-1"></i> Released to us</div>
            <div style="font-weight:700;font-size:1.15rem;color:#3D5B44;"><?= number_format($totalRel); ?></div>
            <div class="small text-muted"><?= (int)$pool['count_releases']; ?> release<?= (int)$pool['count_releases'] === 1 ? '' : 's'; ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="p-3 border rounded" style="background:<?= $dlpBand[1]; ?>;">
            <div class="text-muted small" style="text-transform:uppercase;letter-spacing:.4px;font-size:.6rem;"><i class="fas fa-clock me-1"></i> DLP end (estimated)</div>
            <div style="font-weight:700;font-size:1.15rem;color:<?= $dlpBand[0]; ?>;">
                <?= $pool['dlp_end_estimate'] ? htmlspecialchars($pool['dlp_end_estimate']) : '—'; ?>
            </div>
            <div class="small" style="color:<?= $dlpBand[0]; ?>;text-transform:capitalize;">
                <?php if ($daysToDlp === null): ?>—<?php elseif ($daysToDlp > 0): ?><?= $daysToDlp; ?> days left<?php else: ?>past due <?= -$daysToDlp; ?> days<?php endif; ?>
            </div>
        </div>
    </div>
</div>
<div class="text-muted small mb-3">
    <i class="fas fa-info-circle me-1"></i>
    DLP end = (last APPROVED IPC date) + contract DLP days. Anchor off the practical-completion certificate when available.
</div>

<!-- ── Record release ────────────────────────────────────────────────── -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Record release event</strong>
        <span class="text-muted small ms-2">Book-keeping entry only — the bank receipt is captured via the standard AR pipeline.</span>
    </div>
    <div class="card-body p-3" style="background:#FAF8F4;">
        <div class="row g-2 align-items-end">
            <div class="col-md-2">
                <label class="form-label" style="font-size:.78rem;">Released on</label>
                <input type="date" id="rel_date" class="form-control form-control-sm" value="<?= date('Y-m-d'); ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label" style="font-size:.78rem;">Amount (max <?= number_format($inPool); ?>)</label>
                <input type="number" step="0.01" min="0" max="<?= (float)$inPool; ?>" id="rel_amt" class="form-control form-control-sm">
            </div>
            <div class="col-md-2">
                <label class="form-label" style="font-size:.78rem;">Matched receipt #</label>
                <input type="number" step="1" min="0" id="rel_receipt" class="form-control form-control-sm" placeholder="optional">
            </div>
            <div class="col-md-5">
                <label class="form-label" style="font-size:.78rem;">Notes</label>
                <input type="text" id="rel_notes" class="form-control form-control-sm" placeholder="e.g. 50% release at PC · signed off">
            </div>
            <div class="col-12 text-end">
                <button type="button" id="btn_record_release" class="btn btn-sm" style="background:#3D5B44;border-color:#3D5B44;color:#fff;" <?= $inPool <= 0 ? 'disabled' : ''; ?>>
                    <i class="fas fa-plus me-1"></i> Record release (FM / Admin)
                </button>
            </div>
        </div>
    </div>
</div>

<!-- ── Holdings breakdown (per IPC) ──────────────────────────────────── -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Holdings by IPC · <?= count($holdings); ?></strong></div>
    <?php if (empty($holdings)): ?>
        <div class="card-body p-3 text-muted small">No APPROVED IPCs yet — held pool is 0.</div>
    <?php else: ?>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th>IPC</th>
                    <th style="width:60px;">Seq</th>
                    <th style="width:110px;">Date</th>
                    <th class="text-end">Certified</th>
                    <th class="text-end">Retention %</th>
                    <th class="text-end">Retention amt</th>
                    <th class="text-end">Net (customer pays)</th>
                    <th style="width:100px;">Sale</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($holdings as $h): ?>
                <tr>
                    <td><code><?= htmlspecialchars($h['ipc_no']); ?></code></td>
                    <td class="text-muted"><?= (int)$h['ipc_seq']; ?></td>
                    <td class="small text-muted"><?= htmlspecialchars($h['ipc_date']); ?></td>
                    <td class="text-end"><?= number_format((float)$h['certified_gross']); ?></td>
                    <td class="text-end small text-muted"><?= number_format((float)$h['retention_pct'], 2); ?>%</td>
                    <td class="text-end"><strong><?= number_format((float)$h['retention_amount']); ?></strong></td>
                    <td class="text-end small"><?= number_format((float)$h['net_amount']); ?></td>
                    <td class="small">
                        <?php if ((int)$h['sale_id'] > 0): ?>
                            <a href="<?= PROOT; ?>Sales/view/<?= (int)$h['sale_id']; ?>">#<?= (int)$h['sale_id']; ?></a>
                        <?php else: ?><span class="text-muted">—</span><?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<!-- ── Release log ───────────────────────────────────────────────────── -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white"><strong>Release log · <?= count($releases); ?></strong></div>
    <?php if (empty($releases)): ?>
        <div class="card-body p-3 text-muted small">No releases recorded 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 style="width:110px;">Released on</th>
                    <th class="text-end">Amount</th>
                    <th style="width:110px;">Matched receipt</th>
                    <th>Notes</th>
                    <th style="width:150px;">Recorded by</th>
                    <th style="width:80px;" class="text-end">Del</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($releases as $r): ?>
                <tr>
                    <td class="small text-muted"><?= htmlspecialchars($r['released_on']); ?></td>
                    <td class="text-end"><strong><?= number_format((float)$r['amount']); ?></strong></td>
                    <td class="small">
                        <?php if ((int)$r['matched_receipt_id'] > 0): ?>
                            <a href="<?= PROOT; ?>Receipts/view/<?= (int)$r['matched_receipt_id']; ?>">#<?= (int)$r['matched_receipt_id']; ?></a>
                        <?php else: ?><span class="text-muted">—</span><?php endif; ?>
                    </td>
                    <td class="small"><?= htmlspecialchars($r['notes']); ?></td>
                    <td class="small text-muted"><?= htmlspecialchars($r['released_by_name']); ?></td>
                    <td class="text-end">
                        <button type="button" class="btn btn-sm btn-outline-secondary btn-del-release" data-id="<?= (int)$r['c0d']; ?>" title="Remove (FM / Admin)">
                            <i class="fas fa-times"></i>
                        </button>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>
<?php $this->end(); ?>

<?php $this->start('section_js'); ?>
<script>
$('#btn_record_release').on('click', function () {
    var amt = parseFloat($('#rel_amt').val() || '0');
    if (amt <= 0) { rsToast('Amount must be > 0.', 'error'); return; }
    $.post('<?= PROOT; ?>WorksCustomerRetention/recordReleaseAj', {
        project_id:         <?= (int)$p['c0d']; ?>,
        amount:             amt,
        released_on:        $('#rel_date').val(),
        notes:              $('#rel_notes').val(),
        matched_receipt_id: parseInt($('#rel_receipt').val() || '0', 10),
    }, 'json').done(function (r) {
        if (r && r.ok) { rsToast('Release recorded.', 'success'); location.reload(); }
        else            { rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); }
    });
});

$('.btn-del-release').on('click', function () {
    var id = $(this).data('id');
    $.confirm({
        title: 'Remove this release entry?',
        content: '<p style="font-size:.85rem;">The pool balance will grow back by this amount.</p>',
        boxWidth: '420px', useBootstrap: false,
        buttons: {
            confirm: {
                text: 'Remove', btnClass: 'btn-danger',
                action: function () {
                    $.post('<?= PROOT; ?>WorksCustomerRetention/deleteReleaseAj', { release_id: id }, 'json')
                        .done(function (r) {
                            if (r && r.ok) { rsToast('Removed.', 'success'); location.reload(); }
                            else            { rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); }
                        });
                }
            },
            cancel: { text: 'Cancel' }
        }
    });
});
</script>
<?php $this->end(); ?>
