<?php $this->start('body');
    $ipc     = $this->data['ipc'];
    $p       = $this->data['project'] ?? [];
    $lines   = $this->data['lines']   ?? [];
    $canEdit = !empty($this->data['can_edit']);
    $receipts = $this->data['receipts'] ?? [];
    $ar       = $this->data['ar']       ?? ['invoiced'=>0,'received'=>0,'outstanding'=>0,'retained'=>0];

    $statusPill = [
        'DRAFT'      => ['#f59e0b', 'Draft'],
        'SUBMITTED'  => ['#0ea5e9', 'Submitted'],
        'APPROVED'   => ['#22c55e', 'Approved'],
        'CANCELLED'  => ['#94a3b8', 'Cancelled'],
    ];
    $sp = $statusPill[$ipc['status']] ?? ['#94a3b8', $ipc['status']];
?>
<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-1 text-muted"></i>
            <code style="font-size:.85rem;color:#334155;background:#F1F5F9;padding:2px 6px;border-radius:3px;"><?= htmlspecialchars($ipc['ipc_no']); ?></code>
            <span class="badge ms-2" style="background:<?= $sp[0]; ?>;color:#fff;text-transform:capitalize;"><?= htmlspecialchars($sp[1]); ?></span>
        </h5>
        <div class="text-muted" style="font-size:.72rem;">
            Project <?= htmlspecialchars($p['project_no'] ?? '?'); ?> · IPC #<?= (int)$ipc['ipc_seq']; ?> ·
            <?= htmlspecialchars((string)$ipc['period_from']); ?> → <?= htmlspecialchars((string)$ipc['period_to']); ?>
        </div>
    </div>
    <div>
        <?php if ($canEdit): ?>
            <button type="button" id="btn_approve" class="btn btn-sm btn-primary" style="background:#7A9E7E;border-color:#7A9E7E;">
                <i class="fas fa-check me-1"></i> Approve · raise invoice
            </button>
        <?php elseif ((int)$ipc['sale_id'] > 0): ?>
            <a href="<?= PROOT; ?>Sales/view/<?= (int)$ipc['sale_id']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-file-invoice me-1"></i> Sales invoice #<?= (int)$ipc['sale_id']; ?></a>
        <?php endif; ?>
        <a href="<?= PROOT; ?>WorksIpcs/list/<?= (int)$ipc['project_id']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> All IPCs</a>
    </div>
</div>

<!-- ── Totals summary ─────────────────────────────────────────────── -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-body p-3">
        <div class="row g-2 text-center">
            <div class="col-md">
                <div class="text-muted small" style="text-transform:uppercase;letter-spacing:.4px;font-size:.6rem;">Certified gross</div>
                <div style="color:#334155;font-weight:700;font-size:.95rem;"><?= number_format((float)$ipc['certified_gross']); ?></div>
            </div>
            <div class="col-md">
                <div class="text-muted small" style="text-transform:uppercase;letter-spacing:.4px;font-size:.6rem;">Retention <?= number_format((float)$ipc['retention_pct'], 2); ?>%</div>
                <div style="color:#6B3F2A;font-weight:700;font-size:.95rem;">- <?= number_format((float)$ipc['retention_amount']); ?></div>
            </div>
            <div class="col-md">
                <div class="text-muted small" style="text-transform:uppercase;letter-spacing:.4px;font-size:.6rem;">Advance recovery</div>
                <?php if ($canEdit): ?>
                    <input type="number" step="0.01" min="0" id="adv_amt" class="form-control form-control-sm text-center" value="<?= htmlspecialchars((string)$ipc['advance_recovery']); ?>" style="max-width:140px;margin:0 auto;">
                <?php else: ?>
                    <div style="color:#6B3F2A;font-weight:700;font-size:.95rem;">- <?= number_format((float)$ipc['advance_recovery']); ?></div>
                <?php endif; ?>
            </div>
            <div class="col-md" style="background:#EAF2E8;border-radius:4px;padding:4px;">
                <div class="text-muted small" style="text-transform:uppercase;letter-spacing:.4px;font-size:.6rem;">Net amount</div>
                <div style="color:#3D5B44;font-weight:800;font-size:1.05rem;"><?= number_format((float)$ipc['net_amount']); ?></div>
            </div>
            <div class="col-md">
                <div class="text-muted small" style="text-transform:uppercase;letter-spacing:.4px;font-size:.6rem;">VAT <?= number_format((float)$ipc['vat_pct'], 2); ?>%</div>
                <div style="color:#334155;font-weight:700;font-size:.95rem;">+ <?= number_format((float)$ipc['vat_amount']); ?></div>
            </div>
            <div class="col-md" style="background:#F1F5F9;border-radius:4px;padding:4px;">
                <div class="text-muted small" style="text-transform:uppercase;letter-spacing:.4px;font-size:.6rem;">Invoice total</div>
                <div style="color:#166534;font-weight:800;font-size:1.05rem;"><?= number_format((float)$ipc['invoice_total']); ?></div>
            </div>
        </div>
    </div>
</div>

<!-- ── BOQ lines ──────────────────────────────────────────────────── -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Lines · <?= count($lines); ?></strong>
        <span class="text-muted small ms-2">Enter <em>this period qty</em> per BOQ item — cumulative rolls up. Over-certify is blocked.</span>
    </div>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th style="width:70px;">Item</th>
                    <th>Description</th>
                    <th class="text-end" style="width:100px;">Contract qty</th>
                    <th class="text-end" style="width:110px;">Rate</th>
                    <th class="text-end" style="width:100px;">Previous</th>
                    <th style="width:110px;">This period</th>
                    <th class="text-end" style="width:130px;">This period amt</th>
                    <th class="text-end" style="width:110px;">Cumulative</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($lines as $l):
                $pct = (float)$l['contract_qty'] > 0 ? round((float)$l['cumulative_qty'] / (float)$l['contract_qty'] * 100, 1) : 0.0;
            ?>
                <tr data-line-id="<?= (int)$l['c0d']; ?>">
                    <td class="small"><code><?= htmlspecialchars($l['item_no']); ?></code></td>
                    <td class="small">
                        <?= htmlspecialchars($l['description']); ?>
                        <?php if (!empty($l['section'])): ?><div class="text-muted"><?= htmlspecialchars($l['section']); ?></div><?php endif; ?>
                    </td>
                    <td class="text-end small"><?= rtrim(rtrim(number_format((float)$l['contract_qty'], 4), '0'), '.'); ?> <span class="text-muted"><?= htmlspecialchars($l['unit']); ?></span></td>
                    <td class="text-end small"><?= number_format((float)$l['contract_rate']); ?></td>
                    <td class="text-end small text-muted"><?= rtrim(rtrim(number_format((float)$l['previous_qty'], 4), '0'), '.'); ?></td>
                    <td>
                        <?php if ($canEdit): ?>
                            <input type="number" step="0.0001" min="0" class="form-control form-control-sm this-qty" value="<?= htmlspecialchars((string)$l['this_period_qty']); ?>">
                        <?php else: ?>
                            <span class="small text-muted"><?= rtrim(rtrim(number_format((float)$l['this_period_qty'], 4), '0'), '.'); ?></span>
                        <?php endif; ?>
                    </td>
                    <td class="text-end"><strong><?= number_format((float)$l['this_period_amount']); ?></strong></td>
                    <td class="text-end small">
                        <?= rtrim(rtrim(number_format((float)$l['cumulative_qty'], 4), '0'), '.'); ?>
                        <div class="small" style="color:<?= $pct >= 100 ? '#3D5B44' : '#5B4F3C'; ?>;"><?= $pct; ?>%</div>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php if (!empty($ipc['notes'])): ?>
<div class="alert py-2 mb-3" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#334155;font-size:.86rem;">
    <?= nl2br(htmlspecialchars($ipc['notes'])); ?>
</div>
<?php endif; ?>

<!-- ── AR position + receipts (only relevant post-approval) ────────── -->
<?php if ((int)$ipc['sale_id'] > 0): ?>
<?php
    $outBand = (float)$ar['outstanding'] > 0 ? ['#B87A5A','#F3E5D9','Outstanding'] : ['#3D5B44','#EAF2E8','Settled'];
?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>AR position · sale #<?= (int)$ipc['sale_id']; ?></strong>
        <span class="text-muted small ms-2">Receipts allocated to this IPC's sales invoice.</span>
    </div>
    <div class="card-body p-3" style="background:#FAF8F4;">
        <div class="row g-2">
            <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-file-invoice me-1"></i> Invoiced</div>
                    <div style="font-weight:700;font-size:1.05rem;color:#334155;"><?= number_format((float)$ar['invoiced']); ?></div>
                    <div class="small text-muted">net + VAT</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-circle me-1"></i> Received</div>
                    <div style="font-weight:700;font-size:1.05rem;color:#3D5B44;"><?= number_format((float)$ar['received']); ?></div>
                    <div class="small text-muted"><?= count($receipts); ?> receipt<?= count($receipts) === 1 ? '' : 's'; ?></div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="p-3 border rounded" style="background:<?= $outBand[1]; ?>;">
                    <div class="text-muted small" style="text-transform:uppercase;letter-spacing:.4px;font-size:.6rem;"><i class="fas fa-hourglass-half me-1"></i> Outstanding</div>
                    <div style="font-weight:700;font-size:1.05rem;color:<?= $outBand[0]; ?>;"><?= number_format((float)$ar['outstanding']); ?></div>
                    <div class="small" style="color:<?= $outBand[0]; ?>;text-transform:capitalize;"><?= strtolower($outBand[2]); ?></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-lock me-1"></i> Retained by customer</div>
                    <div style="font-weight:700;font-size:1.05rem;color:#6B3F2A;"><?= number_format((float)$ar['retained']); ?></div>
                    <div class="small text-muted">separate liability · tracked in Customer retention pool</div>
                </div>
            </div>
        </div>
    </div>
    <?php if (!empty($receipts)): ?>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th>Receipt</th>
                    <th style="width:110px;">Date</th>
                    <th style="width:140px;">Method · ref</th>
                    <th style="width:110px;">Type</th>
                    <th class="text-end" style="width:140px;">Amount</th>
                    <th style="width:80px;" class="text-end">Open</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($receipts as $r): ?>
                <tr>
                    <td><code><?= htmlspecialchars($r['receipt_no']); ?></code></td>
                    <td class="small text-muted"><?= htmlspecialchars($r['receipt_date']); ?></td>
                    <td class="small text-muted">
                        <?= htmlspecialchars(str_replace('_', ' ', (string)$r['payment_method'])); ?>
                        <?php if (!empty($r['bank_reference'])): ?><div><?= htmlspecialchars($r['bank_reference']); ?></div><?php endif; ?>
                    </td>
                    <td class="small text-muted"><?= htmlspecialchars($r['receipt_type']); ?></td>
                    <td class="text-end"><strong><?= number_format((float)$r['amount']); ?></strong> <?= htmlspecialchars($r['currency']); ?></td>
                    <td class="text-end"><a href="<?= PROOT; ?>Receipts/view/<?= (int)$r['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 receipts yet. Record a receipt via <a href="<?= PROOT; ?>Receipts">Customer Receipts</a> against sale #<?= (int)$ipc['sale_id']; ?>.</div>
    <?php endif; ?>
</div>
<?php endif; ?>
<?php $this->end(); ?>

<?php $this->start('section_js'); ?>
<script>
const IPC_ID = <?= (int)$ipc['c0d']; ?>;

$('.this-qty').on('change', function () {
    var $tr  = $(this).closest('tr');
    var lid  = $tr.data('line-id');
    var qty  = parseFloat($(this).val() || '0');
    $.post('<?= PROOT; ?>WorksIpcs/setLineQtyAj', {
        ipc_id: IPC_ID, line_id: lid, this_period_qty: qty
    }, 'json').done(function (r) {
        if (r && r.ok) location.reload();
        else            rsToast('Failed: ' + (r.msg || 'unknown'), 'error');
    });
});

$('#adv_amt').on('change', function () {
    $.post('<?= PROOT; ?>WorksIpcs/setAdvanceAj', {
        ipc_id: IPC_ID, amount: parseFloat($(this).val() || '0')
    }, 'json').done(function (r) {
        if (r && r.ok) location.reload();
        else            rsToast('Failed: ' + (r.msg || 'unknown'), 'error');
    });
});

$('#btn_approve').on('click', function () {
    $.confirm({
        title: 'Approve this IPC?',
        content: '<p style="font-size:.85rem;color:#5B4F3C;">A sales invoice will be raised via <code>Sales::draft</code> for the <strong>net amount</strong>. The IPC will lock and further edits will be disabled.</p>',
        boxWidth: '440px', useBootstrap: false,
        buttons: {
            confirm: {
                text: 'Approve · raise invoice', btnClass: 'btn-success',
                action: function () {
                    $.post('<?= PROOT; ?>WorksIpcs/approveAj', { ipc_id: IPC_ID }, 'json')
                        .done(function (r) {
                            if (r && r.ok) { rsToast('Approved.', 'success'); location.reload(); }
                            else            { rsToast('Cannot approve: ' + (r.msg || 'unknown'), 'error'); }
                        });
                }
            },
            cancel: { text: 'Cancel' }
        }
    });
});
</script>
<?php $this->end(); ?>
