<?php $this->start('body');
    $p        = $this->data['project'];
    $terms    = $this->data['terms']    ?? ['pct' => 0.0, 'dlp_days' => 365];
    $pool     = $this->data['pool']     ?? [];
    $holdings = $this->data['holdings'] ?? [];

    $dlpChip = [
        'in_dlp'   => ['#EDE7DC', '#5B4F3C', 'In DLP'],
        'past_dlp' => ['#F3E5D9', '#6B3F2A', 'Past DLP'],
        'released' => ['#E1EBDF', '#3D5B44', 'Released'],
    ];
?>
<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-hand-holding-usd me-1 text-muted"></i>
            Retention pool · <?= htmlspecialchars($p['project_no']); ?>
        </h5>
        <div class="text-muted" style="font-size:.72rem;">
            <?= htmlspecialchars($p['project_customer']); ?> · <?= htmlspecialchars($p['project_name']); ?>
        </div>
    </div>
    <div>
        <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>

<!-- ── Contract terms ────────────────────────────────────────────────── -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Contract retention terms</strong>
        <span class="text-muted small ms-2">Applied automatically on every Works CR-sourced payment.</span>
    </div>
    <div class="card-body p-3" style="background:#FAF8F4;">
        <div class="row g-2 align-items-end">
            <div class="col-md-3">
                <label class="form-label" style="font-size:.78rem;">Retention %</label>
                <input type="number" step="0.01" min="0" max="100" id="ret_pct" class="form-control form-control-sm" value="<?= htmlspecialchars((string)$terms['pct']); ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label" style="font-size:.78rem;">DLP (days)</label>
                <input type="number" step="1" min="0" id="ret_dlp" class="form-control form-control-sm" value="<?= (int)$terms['dlp_days']; ?>">
            </div>
            <div class="col-md-6 text-end">
                <button type="button" id="btn_save_terms" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;">
                    <i class="fas fa-save me-1"></i> Save terms (FM / Admin)
                </button>
            </div>
        </div>
        <div class="text-muted small mt-2">
            0% disables retention on future payments. Existing holdings are unaffected.
        </div>
    </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</div>
            <div style="font-weight:700;font-size:1.15rem;color:#5B4F3C;"><?= number_format((float)$pool['total_held']); ?></div>
            <div class="small text-muted"><?= (int)$pool['count_held']; ?> payment<?= (int)$pool['count_held'] === 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-hourglass-end me-1"></i> Past DLP (releasable)</div>
            <div style="font-weight:700;font-size:1.15rem;color:#6B3F2A;"><?= number_format((float)$pool['past_dlp_held']); ?></div>
            <div class="small" style="color:#6B3F2A;">out of held pool</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-unlock me-1"></i> Released</div>
            <div style="font-weight:700;font-size:1.15rem;color:#3D5B44;"><?= number_format((float)$pool['total_released']); ?></div>
            <div class="small text-muted"><?= (int)$pool['count_released']; ?> payment<?= (int)$pool['count_released'] === 1 ? '' : 's'; ?></div>
        </div>
    </div>
    <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-scroll me-1"></i> Contract rate</div>
            <div style="font-weight:700;font-size:1.15rem;color:#334155;"><?= number_format((float)$terms['pct'], 2); ?>%</div>
            <div class="small text-muted">DLP <?= (int)$terms['dlp_days']; ?> days</div>
        </div>
    </div>
</div>

<!-- ── Holdings table ────────────────────────────────────────────────── -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white"><strong>Holdings · <?= count($holdings); ?></strong>
        <span class="text-muted small ms-2">One row per payment where retention was withheld</span>
    </div>
    <?php if (empty($holdings)): ?>
        <div class="card-body p-3 text-muted small">No retention withheld yet. Set retention % above, then future Works LPO payments will auto-record a holding 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:110px;">Held on</th>
                    <th style="width:110px;">DLP ends</th>
                    <th class="text-end">Gross</th>
                    <th class="text-end">Retention</th>
                    <th style="width:100px;">Status</th>
                    <th style="width:120px;" class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($holdings as $h):
                    $chip = $dlpChip[$h['dlp_status']] ?? ['#e5e7eb', '#374151', $h['dlp_status']];
                    $released = $h['status'] === 'RELEASED';
                ?>
                <tr class="holding-row" data-id="<?= (int)$h['c0d']; ?>" data-status="<?= $h['dlp_status']; ?>">
                    <td class="small"><code><?= htmlspecialchars($h['payment_no']); ?></code></td>
                    <td class="small">
                        <a href="<?= PROOT; ?>Lpos/view/<?= (int)$h['lpo_id']; ?>"><?= htmlspecialchars($h['lpo_no']); ?></a>
                        <div class="text-muted"><?= htmlspecialchars($h['payee_name']); ?></div>
                    </td>
                    <td class="small text-muted"><?= htmlspecialchars($h['held_on']); ?></td>
                    <td class="small text-muted">
                        <?= htmlspecialchars($h['dlp_end_on']); ?>
                        <?php if (!$released && (int)$h['days_to_dlp'] > 0): ?>
                            <div class="small text-muted"><?= (int)$h['days_to_dlp']; ?>d left</div>
                        <?php endif; ?>
                    </td>
                    <td class="text-end small text-muted"><?= number_format((float)$h['gross_amount']); ?></td>
                    <td class="text-end"><strong><?= number_format((float)$h['retention_amount']); ?></strong>
                        <div class="small text-muted"><?= number_format((float)$h['retention_pct'], 2); ?>%</div>
                    </td>
                    <td><span class="badge" style="background:<?= $chip[0]; ?>;color:<?= $chip[1]; ?>;text-transform:capitalize;"><?= htmlspecialchars($chip[2]); ?></span></td>
                    <td class="text-end">
                        <?php if (!$released): ?>
                            <button type="button" class="btn btn-sm btn-outline-secondary btn-release"
                                    data-id="<?= (int)$h['c0d']; ?>"
                                    data-past-dlp="<?= $h['dlp_status'] === 'past_dlp' ? '1' : '0'; ?>">
                                <i class="fas fa-unlock me-1"></i> Release
                            </button>
                        <?php else: ?>
                            <span class="text-muted small"><?= htmlspecialchars(substr((string)$h['released_on'], 0, 10)); ?></span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>
<?php $this->end(); ?>

<?php $this->start('section_js'); ?>
<script>
$('#btn_save_terms').on('click', function () {
    var pct = parseFloat($('#ret_pct').val() || '0');
    var dlp = parseInt($('#ret_dlp').val()  || '0', 10);
    $.post('<?= PROOT; ?>WorksRetention/setTermsAj', {
        project_id: <?= (int)$p['c0d']; ?>, pct: pct, dlp_days: dlp
    }, 'json').done(function (r) {
        if (r && r.ok) { rsToast('Terms saved.', 'success'); location.reload(); }
        else            { rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); }
    });
});

$('.btn-release').on('click', function () {
    var id  = $(this).data('id');
    var pdl = String($(this).data('past-dlp')) === '1';
    var forceHint = pdl ? '' :
        '<div class="alert py-2 my-2" style="background:#FEF3C7;border:1px solid #F59E0B;color:#78350F;font-size:.82rem;">' +
        '<i class="fas fa-exclamation-triangle me-1"></i> DLP has not expired. Force-release only with signed sign-off.' +
        '</div><div class="form-check"><input type="checkbox" class="form-check-input" id="force_chk"> <label class="form-check-label" for="force_chk" style="font-size:.82rem;">I am force-releasing early</label></div>';
    $.confirm({
        title: 'Release retention?',
        content: forceHint +
                 '<div class="form-group mt-2"><label class="form-label" style="font-size:.78rem;">Notes (optional)</label>' +
                 '<textarea id="rel_notes" class="form-control form-control-sm" rows="2" placeholder="e.g. Site walk-through signed off · vendor invoice ref"></textarea></div>',
        boxWidth: '460px', useBootstrap: false,
        buttons: {
            confirm: {
                text: 'Release', btnClass: 'btn-success',
                action: function () {
                    var notes = $('#rel_notes').val() || '';
                    var force = pdl ? 0 : ($('#force_chk').is(':checked') ? 1 : 0);
                    $.post('<?= PROOT; ?>WorksRetention/releaseAj', { holding_id: id, notes: notes, force: force }, 'json')
                        .done(function (r) {
                            if (r && r.ok) { rsToast('Released.', 'success'); location.reload(); }
                            else            { rsToast('Cannot release: ' + (r.msg || 'unknown'), 'error'); }
                        });
                }
            },
            cancel: { text: 'Cancel' }
        }
    });
});
</script>
<?php $this->end(); ?>
