<?php $this->start('body');
    $p       = $this->data['project'];
    $s       = $this->data['summary']       ?? [];
    $phRows  = $this->data['phase_rollup']  ?? [];
    $pillars = $this->data['pillar_rollup'] ?? [];
    $rev     = $this->data['revenue']       ?? [];
    $alerts  = $this->data['alerts']        ?? [];

    // Warm/faded palette for pillars, matching the fulfil view
    $pillarChip = [
        'PRELIMINARIES' => ['#EDE7DC', '#5B4F3C'],
        'MANPOWER'      => ['#E4DEF0', '#4A3D6B'],
        'MATERIALS'     => ['#E1EBDF', '#3D5B44'],
        'EQUIPMENT'     => ['#F0E1D9', '#6B3F2A'],
        'TOOLS'         => ['#EAE7DA', '#5B5738'],
        'SUBCONTRACTS'  => ['#DDE4E9', '#3D4E5B'],
        'OVERHEADS'     => ['#F1DDDD', '#6B3F3F'],
    ];
    $phStatusPill = [
        'PLANNED'   => ['#f59e0b', 'Planned'],
        'ACTIVE'    => ['#22c55e', 'Active'],
        'CLOSED'    => ['#7A8BA1', 'Closed'],
        'CANCELLED' => ['#dc2626', 'Cancelled'],
    ];

    $margin      = (float)($s['margin_vs_boq'] ?? 0);
    $marginBand  = $margin > 0 ? ['#7A9E7E','#EAF2E8','Headroom']
                : ($margin < 0 ? ['#B87A5A','#F3E5D9','Over-committed'] : ['#7A8BA1','#EDEEF2','Committed']);
?>
<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-chart-line me-1 text-muted"></i>
            <?= htmlspecialchars($p['project_no']); ?> · Project rollup
        </h5>
        <div class="text-muted" style="font-size:.72rem;">
            <?= htmlspecialchars($p['project_customer']); ?> · <?= htmlspecialchars($p['project_name']); ?>
        </div>
    </div>
    <div>
        <a href="<?= PROOT; ?>WorksBoq/view/<?= (int)$p['c0d']; ?>"  class="btn btn-sm btn-outline-secondary"><i class="fas fa-clipboard-list me-1"></i> BOQ</a>
        <a href="<?= PROOT; ?>WorksPhases/plan/<?= (int)$p['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-layer-group me-1"></i> Phases</a>
        <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; ?>WorksCustomerRetention/pool/<?= (int)$p['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-hourglass-half me-1"></i> Customer retention</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" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> All reports</a>
    </div>
</div>

<!-- ── Summary cards ──────────────────────────────────────────────────── -->
<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-file-signature me-1"></i> Contract value
            </div>
            <div style="font-weight:700;font-size:1.15rem;color:#334155;"><?= number_format((float)$s['contract_value']); ?></div>
            <?php if ((float)($s['variation_value'] ?? 0) > 0): ?>
                <div class="small text-muted">incl. variations <?= number_format((float)$s['variation_value']); ?></div>
            <?php endif; ?>
        </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-file-invoice me-1"></i> Committed (in-play CRs)
            </div>
            <div style="font-weight:700;font-size:1.15rem;color:#7A9E7E;"><?= number_format((float)$s['committed_budget']); ?></div>
            <div class="small text-muted"><?= (float)$s['contract_utilisation_pct']; ?>% of contract</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-hand-holding-usd me-1"></i> Paid
            </div>
            <div style="font-weight:700;font-size:1.15rem;color:#B87A5A;"><?= number_format((float)$s['paid']); ?></div>
            <div class="small text-muted"><?= (float)$s['paid_pct']; ?>% of committed · remaining <?= number_format((float)$s['remaining_budget']); ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="p-3 border rounded" style="background:<?= $marginBand[1]; ?>;">
            <div class="text-muted small" style="text-transform:uppercase;letter-spacing:.4px;font-size:.6rem;">
                <i class="fas fa-balance-scale me-1"></i> Margin vs BOQ
            </div>
            <div style="font-weight:700;font-size:1.15rem;color:<?= $marginBand[0]; ?>;">
                <?= number_format($margin); ?>
            </div>
            <div class="small" style="color:<?= $marginBand[0]; ?>;text-transform:capitalize;"><?= strtolower($marginBand[2]); ?></div>
        </div>
    </div>
</div>

<!-- ── Project alert strip ─────────────────────────────────────────────── -->
<?php if (!empty($alerts)):
    $sevCounts = ['HIGH' => 0, 'MEDIUM' => 0, 'LOW' => 0];
    foreach ($alerts as $a) $sevCounts[$a['severity']]++;
    $sevPill = [
        'HIGH'   => ['#B87A5A', '#F3E5D9'],
        'MEDIUM' => ['#5B5738', '#EAE7DA'],
        'LOW'    => ['#3D5B44', '#EAF2E8'],
    ];
    $catChip = [
        'LOSS_MAKING'             => ['#F3E5D9', '#6B3F2A', 'Loss'],
        'OVER_COMMITTED'          => ['#F3E5D9', '#6B3F2A', 'Over-commit'],
        'STALE_DRAFT_IPC'         => ['#EDE7DC', '#5B4F3C', 'Stale IPC'],
        'CUST_RETENTION_PAST_DLP' => ['#EAE7DA', '#5B5738', 'Cust retention'],
        'SUPP_RETENTION_PAST_DLP' => ['#EDE7DC', '#5B4F3C', 'Supp retention'],
        'PHASE_OVERDUE'           => ['#DDE4E9', '#3D4E5B', 'Phase overdue'],
        'DIRECT_AWARD_UNJUSTIFIED'=> ['#F3E5D9', '#6B3F2A', 'Direct award ⚠'],
    ];
?>
<div class="card border-0 shadow-sm mb-3" style="background:#FAF6EF;border-left:3px solid #B87A5A !important;">
    <div class="card-body p-3">
        <div class="d-flex align-items-center justify-content-between mb-2">
            <div style="font-weight:600;color:#5B4F3C;">
                <i class="fas fa-bell me-1" style="color:#B87A5A;"></i>
                <?= count($alerts); ?> alert<?= count($alerts) === 1 ? '' : 's'; ?> on this project
            </div>
            <div>
                <?php foreach (['HIGH','MEDIUM','LOW'] as $sev):
                    if ($sevCounts[$sev] <= 0) continue;
                ?>
                    <span class="badge me-1" style="background:<?= $sevPill[$sev][0]; ?>;color:#fff;text-transform:capitalize;"><?= $sevCounts[$sev]; ?> <?= strtolower($sev); ?></span>
                <?php endforeach; ?>
                <a href="<?= PROOT; ?>WorksAlerts" class="btn btn-sm btn-outline-secondary ms-2"><i class="fas fa-list me-1"></i> All alerts</a>
            </div>
        </div>
        <div>
            <?php foreach ($alerts as $a):
                $cc = $catChip[$a['category']] ?? ['#e5e7eb', '#374151', $a['category']];
            ?>
                <a href="<?= htmlspecialchars($a['action_url']); ?>" class="d-inline-block me-2 mb-1" style="text-decoration:none;">
                    <span class="badge" style="background:<?= $cc[0]; ?>;color:<?= $cc[1]; ?>;text-transform:capitalize;font-weight:600;">
                        <?= htmlspecialchars($cc[2]); ?> · <?= htmlspecialchars($a['summary']); ?>
                    </span>
                </a>
            <?php endforeach; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- ── Meta counts ────────────────────────────────────────────────────── -->
<div class="mb-3" style="font-size:.78rem;color:#5B4F3C;">
    <i class="fas fa-layer-group me-1"></i>
    Phases <strong><?= (int)$s['phase_active']; ?> active</strong>, <?= (int)$s['phase_planned']; ?> planned, <?= (int)$s['phase_closed']; ?> closed
    · <i class="fas fa-file-invoice ms-2 me-1"></i>
    CRs <strong><?= (int)$s['cr_active']; ?> active</strong>, <?= (int)$s['cr_closed']; ?> closed, <?= (int)$s['cr_draft']; ?> in draft/submit
</div>

<!-- ── Revenue vs Cost (live margin) ──────────────────────────────────── -->
<?php
    $marginToDate   = (float)($rev['margin_to_date']  ?? 0);
    $effectiveCash  = (float)($rev['effective_cash']  ?? 0);
    $mBand = $marginToDate > 0 ? ['#7A9E7E','#EAF2E8','Profitable']
           : ($marginToDate < 0 ? ['#B87A5A','#F3E5D9','Loss-making'] : ['#7A8BA1','#EDEEF2','Break-even']);
    $cBand = $effectiveCash > 0 ? ['#3D5B44','#EAF2E8','Cash-positive']
           : ($effectiveCash < 0 ? ['#6B3F2A','#F3E5D9','Financing job'] : ['#5B4F3C','#EDEEF2','Flat']);
?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Revenue vs Cost · live margin</strong>
        <span class="text-muted small ms-2">Certified revenue (from APPROVED IPCs) vs cost paid to date (from LPO payments). Retention flows on both sides.</span>
    </div>
    <div class="card-body p-3" style="background:#FAF8F4;">
        <div class="row g-2">
            <!-- Revenue side -->
            <div class="col-md-4">
                <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-arrow-up me-1" style="color:#3D5B44;"></i> Revenue certified
                    </div>
                    <div style="font-weight:700;font-size:1.15rem;color:#3D5B44;"><?= number_format((float)$rev['revenue_certified']); ?></div>
                    <div class="small text-muted"><?= (int)($rev['ipcs_count'] ?? 0); ?> approved IPC<?= (int)($rev['ipcs_count'] ?? 0) === 1 ? '' : 's'; ?></div>
                    <div class="mt-2" style="font-size:.72rem;color:#5B4F3C;">
                        Invoiced (net): <strong><?= number_format((float)$rev['revenue_invoiced']); ?></strong><br>
                        Received: <strong style="color:#3D5B44;"><?= number_format((float)($rev['customer_received'] ?? 0)); ?></strong>
                        <?php if ((float)($rev['customer_ar_gap'] ?? 0) > 0): ?>
                            · AR gap <strong style="color:#6B3F2A;"><?= number_format((float)$rev['customer_ar_gap']); ?></strong>
                        <?php endif; ?><br>
                        Customer holds: <strong><?= number_format((float)$rev['customer_retention_pool']); ?></strong>
                        <?php if ((float)$rev['customer_retention_released'] > 0): ?>
                            · released <?= number_format((float)$rev['customer_retention_released']); ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <!-- Cost side -->
            <div class="col-md-4">
                <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-arrow-down me-1" style="color:#6B3F2A;"></i> Cost paid
                    </div>
                    <div style="font-weight:700;font-size:1.15rem;color:#6B3F2A;"><?= number_format((float)$rev['cost_paid']); ?></div>
                    <div class="small text-muted">across all in-play CRs</div>
                    <div class="mt-2" style="font-size:.72rem;color:#5B4F3C;">
                        Held as supplier retention: <strong><?= number_format((float)$rev['supplier_retention_held']); ?></strong>
                        <?php if ((float)$rev['supplier_retention_released'] > 0): ?>
                            · released <?= number_format((float)$rev['supplier_retention_released']); ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <!-- Margin -->
            <div class="col-md-4">
                <div class="p-3 border rounded" style="background:<?= $mBand[1]; ?>;">
                    <div class="text-muted small" style="text-transform:uppercase;letter-spacing:.4px;font-size:.6rem;">
                        <i class="fas fa-balance-scale me-1" style="color:<?= $mBand[0]; ?>;"></i> Margin to date
                    </div>
                    <div style="font-weight:700;font-size:1.15rem;color:<?= $mBand[0]; ?>;">
                        <?= number_format($marginToDate); ?>
                        <span class="small ms-1"><?= (float)($rev['margin_pct_to_date'] ?? 0); ?>%</span>
                    </div>
                    <div class="small" style="color:<?= $mBand[0]; ?>;text-transform:capitalize;"><?= strtolower($mBand[2]); ?></div>
                    <div class="mt-2" style="font-size:.72rem;color:<?= $cBand[0]; ?>;">
                        Effective cash position: <strong><?= number_format($effectiveCash); ?></strong>
                        · <span style="text-transform:capitalize;"><?= strtolower($cBand[2]); ?></span>
                    </div>
                </div>
            </div>
        </div>
        <div class="text-muted small mt-2">
            <i class="fas fa-info-circle me-1"></i>
            <strong>Margin to date</strong> = certified revenue − cost paid (before retention settles).
            <strong>Effective cash</strong> = invoiced − paid + supplier retention still in our hand − customer retention still in customer's hand.
        </div>
    </div>
</div>

<!-- ── Per-phase rollup ───────────────────────────────────────────────── -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Per-phase rollup · <?= count($phRows); ?> phase<?= count($phRows) === 1 ? '' : 's'; ?></strong>
        <span class="text-muted small ms-2">Sums pillar totals across every ACTIVE + CLOSED CR on the phase.</span>
    </div>
    <?php if (empty($phRows)): ?>
        <div class="card-body p-3 text-muted small">No phases yet — start with <a href="<?= PROOT; ?>WorksPhases/plan/<?= (int)$p['c0d']; ?>">Phase Planning</a>.</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:60px;">Ph.</th>
                    <th>Title</th>
                    <th style="width:100px;">Status</th>
                    <th style="width:60px;" class="text-end">CRs</th>
                    <th class="text-end">Budget</th>
                    <th class="text-end">Paid</th>
                    <th style="width:130px;">Progress</th>
                    <th style="width:80px;" class="text-end">Open</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($phRows as $row):
                    $sp = $phStatusPill[$row['status']] ?? ['#94a3b8', $row['status']];
                    $pct = min(100, (float)$row['paid_pct']);
                ?>
                <tr>
                    <td class="text-muted"><?= (int)$row['phase_no']; ?></td>
                    <td>
                        <strong><?= htmlspecialchars($row['title']); ?></strong>
                        <?php if (!empty($row['code'])): ?><span class="text-muted small ms-1">· <code><?= htmlspecialchars($row['code']); ?></code></span><?php endif; ?>
                        <?php if (!empty($row['planned_start'])): ?>
                            <div class="text-muted small">planned <?= htmlspecialchars($row['planned_start']); ?> → <?= htmlspecialchars($row['planned_end'] ?? '—'); ?><?php if (!empty($row['actual_end'])): ?> · closed <?= htmlspecialchars($row['actual_end']); ?><?php endif; ?></div>
                        <?php endif; ?>
                    </td>
                    <td><span class="badge" style="background:<?= $sp[0]; ?>;color:#fff;text-transform:capitalize;"><?= strtolower($sp[1]); ?></span></td>
                    <td class="text-end small"><?= (int)$row['cr_count']; ?></td>
                    <td class="text-end"><?= number_format((float)$row['budget']); ?></td>
                    <td class="text-end"><strong><?= number_format((float)$row['paid']); ?></strong></td>
                    <td>
                        <div style="height:6px;background:#F1EDE4;border-radius:3px;">
                            <div style="height:100%;background:#B87A5A;border-radius:3px;width:<?= $pct; ?>%;"></div>
                        </div>
                        <div class="small text-muted mt-1"><?= (float)$row['paid_pct']; ?>%</div>
                    </td>
                    <td class="text-end"><a href="<?= PROOT; ?>WorksPhases/view/<?= (int)$row['phase_id']; ?>" 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>

<!-- ── Per-pillar rollup ──────────────────────────────────────────────── -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Per-pillar rollup</strong>
        <span class="text-muted small ms-2">Project-wide totals across every ACTIVE + CLOSED CR</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:150px;">Pillar</th>
                    <th class="text-end">Budget</th>
                    <th class="text-end">Sourced</th>
                    <th class="text-end">Delivered</th>
                    <th class="text-end">Paid</th>
                    <th class="text-end" style="width:150px;">Variance</th>
                    <th style="width:130px;">Paid %</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($pillars as $pillar => $r):
                $chip = $pillarChip[$pillar] ?? ['#e5e7eb', '#374151'];
                $va = (float)$r['variance'];
                $rowColor = $va < 0 ? '#3D5B44' : ($va > 0 ? '#6B3F2A' : '#5B4F3C');
            ?>
                <tr>
                    <td>
                        <span class="badge" style="background:<?= $chip[0]; ?>;color:<?= $chip[1]; ?>;text-transform:capitalize;">
                            <?= strtolower(str_replace('_', ' ', $pillar)); ?>
                        </span>
                    </td>
                    <td class="text-end"><?= number_format((float)$r['budget']); ?></td>
                    <td class="text-end text-muted"><?= number_format((float)$r['sourced']); ?></td>
                    <td class="text-end text-muted"><?= number_format((float)$r['delivered']); ?></td>
                    <td class="text-end"><strong><?= number_format((float)$r['paid']); ?></strong></td>
                    <td class="text-end" style="color:<?= $rowColor; ?>;font-weight:600;">
                        <?= number_format($va); ?>
                    </td>
                    <td>
                        <div style="height:6px;background:#F1EDE4;border-radius:3px;">
                            <div style="height:100%;background:#B87A5A;border-radius:3px;width:<?= min(100, (float)$r['paid_pct']); ?>%;"></div>
                        </div>
                        <div class="small text-muted mt-1"><?= (float)$r['paid_pct']; ?>%</div>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php $this->end(); ?>
