<?php $this->start('body');
    $cr        = $this->data['cr'];
    $phase     = $this->data['phase'];
    $prj       = $this->data['project'] ?? [];
    $lines     = $this->data['lines'] ?? [];
    $activities= $this->data['activities'] ?? [];
    $phaseActs = $this->data['phase_activities'] ?? [];
    $phaseBoq  = $this->data['phase_boq_items']  ?? [];
    $pillars   = $this->data['pillars'] ?? [];
    $approval  = $this->data['approval'] ?? [];
    $history   = $this->data['history']  ?? [];
    $canEdit   = !empty($this->data['can_edit']);
    $canSubmit = !empty($this->data['can_submit']);
    $variance  = $this->data['variance'] ?? [];

    $statusPill = [
        'DRAFT'      => ['#f59e0b', 'Draft'],
        'SUBMITTED'  => ['#0ea5e9', 'Submitted'],
        'APPROVED'   => ['#22c55e', 'Approved'],
        'ACTIVE'     => ['#166534', 'Active'],
        'SUPERSEDED' => ['#94a3b8', 'Superseded'],
        'CLOSED'     => ['#7A8BA1', 'Closed'],
        'DECLINED'   => ['#dc2626', 'Declined'],
        'CANCELLED'  => ['#94a3b8', 'Cancelled'],
    ];
    $sp = $statusPill[$cr['status']] ?? ['#94a3b8', $cr['status']];

    $pillarMeta = [
        'PRELIMINARIES' => ['label' => 'Preliminaries', 'color' => '#7A8BA1', 'icon' => 'fa-tools'],
        'MANPOWER'      => ['label' => 'Manpower',      'color' => '#D4A574', 'icon' => 'fa-users'],
        'MATERIALS'     => ['label' => 'Materials',     'color' => '#0ea5e9', 'icon' => 'fa-boxes'],
        'EQUIPMENT'     => ['label' => 'Equipment',     'color' => '#7A9E7E', 'icon' => 'fa-truck-monster'],
        'TOOLS'         => ['label' => 'Tools',         'color' => '#a78bfa', 'icon' => 'fa-hammer'],
        'SUBCONTRACTS'  => ['label' => 'Sub-contracts', 'color' => '#94a3b8', 'icon' => 'fa-handshake'],
        'OVERHEADS'     => ['label' => 'Overheads',     'color' => '#f59e0b', 'icon' => 'fa-shield-alt'],
    ];
    $pillarTotalCol = [
        'PRELIMINARIES' => 'total_preliminaries',
        'MANPOWER'      => 'total_manpower',
        'MATERIALS'     => 'total_materials',
        'EQUIPMENT'     => 'total_equipment',
        'TOOLS'         => 'total_tools',
        'SUBCONTRACTS'  => 'total_subcontracts',
        'OVERHEADS'     => 'total_overheads',
    ];
?>
<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-invoice me-1 text-muted"></i>
            <code style="font-size:.85rem;color:#334155;background:#F1F5F9;padding:2px 6px;border-radius:3px;"><?= htmlspecialchars($cr['cr_no']); ?></code>
            · <?= htmlspecialchars($cr['title']); ?>
            <span class="badge ms-2" style="background:<?= $sp[0]; ?>;color:#fff;"><?= htmlspecialchars($sp[1]); ?></span>
            <span class="text-muted small ms-2">v<?= (int)$cr['version']; ?></span>
        </h5>
        <div class="text-muted" style="font-size:.72rem;">
            Project <?= htmlspecialchars($prj['project_no'] ?? '?'); ?> · Phase <?= (int)$phase['phase_no']; ?> · <?= htmlspecialchars($phase['title']); ?>
        </div>
    </div>
    <div>
        <?php if ($cr['status'] === 'ACTIVE'): ?>
            <a href="<?= PROOT; ?>WorksCrs/fulfil/<?= (int)$cr['c0d']; ?>" class="btn btn-sm btn-primary me-1" style="background:#7A9E7E;border-color:#7A9E7E;">
                <i class="fas fa-truck-loading me-1"></i> Fulfil (source LPOs · track delivery)
            </a>
        <?php endif; ?>
        <a href="<?= PROOT; ?>WorksPhases/view/<?= (int)$phase['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Phase</a>
    </div>
</div>

<!-- Pillar totals + grand total -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-body p-3">
        <div class="row g-2 text-center">
            <?php foreach ($pillars as $p => $meta):
                $m = $pillarMeta[$p]; $tCol = $pillarTotalCol[$p];
                $v = (float)($cr[$tCol] ?? 0);
            ?>
                <div class="col-md">
                    <div class="text-muted small" style="text-transform:uppercase;letter-spacing:.4px;font-size:.6rem;">
                        <i class="fas <?= $m['icon']; ?>" style="color:<?= $m['color']; ?>;"></i> <?= htmlspecialchars($m['label']); ?>
                    </div>
                    <div style="color:#334155;font-weight:700;font-size:.95rem;"><?= number_format($v); ?></div>
                </div>
            <?php endforeach; ?>
            <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;">Grand total</div>
                <div style="color:#166534;font-weight:800;font-size:1.05rem;"><?= number_format((float)$cr['grand_total']); ?></div>
            </div>
        </div>
    </div>
</div>

<?php if (!empty($variance)):
    $totVarAmt = 0; foreach ($variance as $vv) $totVarAmt += (float)$vv['variance_amount'];
    $band = $totVarAmt < 0 ? ['#7A9E7E','#EAF2E8','Under-spend'] : ($totVarAmt > 0 ? ['#B87A5A','#F3E5D9','Over-spend'] : ['#7A8BA1','#EDEEF2','On budget']);
?>
<div class="card border-0 shadow-sm mb-3" style="background:<?= $band[1]; ?>;">
    <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <div>
            <i class="fas fa-flag-checkered me-1" style="color:<?= $band[0]; ?>;"></i>
            <strong>Closure variance snapshot</strong>
            <span class="ms-2 badge" style="background:<?= $band[0]; ?>;color:#fff;text-transform:capitalize;"><?= strtolower($band[2]); ?></span>
            <?php if (!empty($cr['closed_on'])): ?>
                <span class="text-muted small ms-2">Closed <?= htmlspecialchars(substr((string)$cr['closed_on'], 0, 10)); ?> by <?= htmlspecialchars((string)$cr['closed_by_name']); ?></span>
            <?php endif; ?>
        </div>
        <div class="fw-bold" style="color:<?= $band[0]; ?>;">Total variance <?= number_format($totVarAmt); ?></div>
    </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>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($variance as $vv):
                    $va = (float)$vv['variance_amount']; $vp = (float)$vv['variance_pct'];
                    $rowColor = $va < 0 ? '#3D5B44' : ($va > 0 ? '#6B3F2A' : '#5B4F3C');
                ?>
                <tr>
                    <td class="fw-semibold" style="text-transform:capitalize;"><?= strtolower(str_replace('_',' ', (string)$vv['pillar'])); ?></td>
                    <td class="text-end"><?= number_format((float)$vv['budget']); ?></td>
                    <td class="text-end text-muted"><?= number_format((float)$vv['sourced']); ?></td>
                    <td class="text-end text-muted"><?= number_format((float)$vv['delivered']); ?></td>
                    <td class="text-end"><?= number_format((float)$vv['paid']); ?></td>
                    <td class="text-end" style="color:<?= $rowColor; ?>;font-weight:600;">
                        <?= number_format($va); ?> <span class="small text-muted">(<?= number_format($vp, 1); ?>%)</span>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- Actions -->
<div class="d-flex gap-2 mb-3">
    <?php if ($canSubmit): ?>
        <button type="button" class="btn btn-sm btn-primary" style="background:#7A9E7E;border-color:#7A9E7E;" onclick="crSubmit()">
            <i class="fas fa-paper-plane me-1"></i> Submit for approval (PC → PM → FM → Exec)
        </button>
    <?php endif; ?>
    <?php if ($cr['status'] === 'SUBMITTED'): ?>
        <a href="<?= PROOT; ?>FinChains/myQueue" class="btn btn-sm btn-outline-secondary"><i class="fas fa-inbox me-1"></i> Chain queue</a>
    <?php endif; ?>
</div>

<!-- Activities -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Activities · <?= count($activities); ?></strong>
        <span class="text-muted small ms-2">What the site will actually deliver this cycle</span>
    </div>
    <?php if ($canEdit): ?>
    <div class="card-body p-3" style="background:#F8FAFC;">
        <div class="row g-2 align-items-end">
            <div class="col-md-4">
                <label class="form-label" style="font-size:.78rem;">Title</label>
                <input id="ac_title" class="form-control form-control-sm" placeholder="Access track clearance">
            </div>
            <div class="col-md-1">
                <label class="form-label" style="font-size:.78rem;">Unit</label>
                <input id="ac_unit" class="form-control form-control-sm">
            </div>
            <div class="col-md-2">
                <label class="form-label" style="font-size:.78rem;">Planned qty</label>
                <input type="number" step="0.01" id="ac_qty" class="form-control form-control-sm">
            </div>
            <div class="col-md-2">
                <label class="form-label" style="font-size:.78rem;">Link phase activity</label>
                <select id="ac_link" class="form-select form-select-sm">
                    <option value="0">—</option>
                    <?php foreach ($phaseActs as $pa): ?>
                        <option value="<?= (int)$pa['c0d']; ?>"><?= (int)$pa['activity_no']; ?> · <?= htmlspecialchars(mb_strimwidth($pa['title'], 0, 40, '…')); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label" style="font-size:.78rem;">Link BOQ item</label>
                <select id="ac_boq" class="form-select form-select-sm">
                    <option value="0">—</option>
                    <?php foreach ($phaseBoq as $bi): ?>
                        <option value="<?= (int)$bi['boq_item_id']; ?>"><?= htmlspecialchars($bi['item_no']); ?> · <?= htmlspecialchars(mb_strimwidth($bi['description'], 0, 40, '…')); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-1 text-end">
                <button type="button" class="btn btn-sm btn-primary" onclick="crAddActivity()"><i class="fas fa-plus"></i></button>
            </div>
        </div>
    </div>
    <?php endif; ?>
    <div class="card-body p-0">
        <?php if (!empty($activities)): ?>
            <table class="table table-sm mb-0 align-middle">
                <thead class="table-light">
                    <tr><th style="width:50px;">#</th><th>Title</th><th style="width:80px;">Unit</th><th style="width:110px;" class="text-end">Planned qty</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($activities as $a): ?>
                        <tr>
                            <td class="text-muted"><?= (int)$a['activity_no']; ?></td>
                            <td>
                                <strong><?= htmlspecialchars($a['title']); ?></strong>
                                <?php if (!empty($a['description'])): ?><div class="text-muted small"><?= htmlspecialchars($a['description']); ?></div><?php endif; ?>
                            </td>
                            <td class="small"><?= htmlspecialchars($a['unit']); ?></td>
                            <td class="text-end"><?= number_format((float)$a['planned_qty'], 2); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <div class="p-3 text-center text-muted small">No activities yet<?= $canEdit ? ' — add at least one before submitting.' : '.' ?></div>
        <?php endif; ?>
    </div>
</div>

<!-- 7 pillar editors -->
<?php foreach ($pillars as $pillar => $meta):
    $m         = $pillarMeta[$pillar];
    $tCol      = $pillarTotalCol[$pillar];
    $pillarLns = $lines[$pillar] ?? [];
    $subtotal  = (float)($cr[$tCol] ?? 0);
?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <strong style="color:<?= $m['color']; ?>;">
            <i class="fas <?= $m['icon']; ?> me-1"></i> <?= htmlspecialchars($m['label']); ?>
        </strong>
        <span class="text-muted small">Subtotal <strong style="color:<?= $m['color']; ?>;"><?= number_format($subtotal); ?></strong></span>
    </div>

    <?php if ($canEdit): ?>
    <div class="card-body p-2" style="background:#F8FAFC;">
        <div class="row g-2 align-items-end small">
            <?php switch ($pillar):
                case 'PRELIMINARIES': ?>
                    <div class="col-md-6"><label class="form-label small">Description</label><input class="form-control form-control-sm" id="l_desc_<?= $pillar; ?>" placeholder="e.g. Site office setup"></div>
                    <div class="col-md-3"><label class="form-label small">Amount</label><input type="number" step="0.01" class="form-control form-control-sm" id="l_amt_<?= $pillar; ?>"></div>
                    <div class="col-md-2"><label class="form-label small">Notes</label><input class="form-control form-control-sm" id="l_notes_<?= $pillar; ?>"></div>
                    <?php break; case 'MANPOWER': ?>
                    <div class="col-md-4"><label class="form-label small">Role</label><input class="form-control form-control-sm" id="l_role_MANPOWER" placeholder="e.g. Foreman"></div>
                    <div class="col-md-1"><label class="form-label small">Persons</label><input type="number" class="form-control form-control-sm" id="l_persons_MANPOWER" value="1"></div>
                    <div class="col-md-1"><label class="form-label small">Days</label><input type="number" step="0.5" class="form-control form-control-sm" id="l_days_MANPOWER"></div>
                    <div class="col-md-2"><label class="form-label small">Rate/day</label><input type="number" step="0.01" class="form-control form-control-sm" id="l_rate_MANPOWER"></div>
                    <div class="col-md-3"><label class="form-label small">Notes</label><input class="form-control form-control-sm" id="l_notes_MANPOWER"></div>
                    <?php break; case 'MATERIALS': ?>
                    <div class="col-md-4"><label class="form-label small">Description</label><input class="form-control form-control-sm" id="l_desc_MATERIALS"></div>
                    <div class="col-md-1"><label class="form-label small">Qty</label><input type="number" step="0.01" class="form-control form-control-sm" id="l_qty_MATERIALS"></div>
                    <div class="col-md-1"><label class="form-label small">Unit</label><input class="form-control form-control-sm" id="l_unit_MATERIALS"></div>
                    <div class="col-md-2"><label class="form-label small">Unit cost</label><input type="number" step="0.01" class="form-control form-control-sm" id="l_uc_MATERIALS"></div>
                    <div class="col-md-3"><label class="form-label small">Notes</label><input class="form-control form-control-sm" id="l_notes_MATERIALS"></div>
                    <?php break; case 'EQUIPMENT': ?>
                    <div class="col-md-4"><label class="form-label small">Description</label><input class="form-control form-control-sm" id="l_desc_EQUIPMENT" placeholder="Excavator / Roller etc"></div>
                    <div class="col-md-1"><label class="form-label small">Hours</label><input type="number" step="0.5" class="form-control form-control-sm" id="l_hrs_EQUIPMENT"></div>
                    <div class="col-md-2"><label class="form-label small">Rate/hour</label><input type="number" step="0.01" class="form-control form-control-sm" id="l_rate_EQUIPMENT"></div>
                    <div class="col-md-2"><label class="form-label small">In-house?</label><select class="form-select form-select-sm" id="l_in_house_EQUIPMENT"><option value="1">Yes</option><option value="0">Hired</option></select></div>
                    <div class="col-md-2"><label class="form-label small">Notes</label><input class="form-control form-control-sm" id="l_notes_EQUIPMENT"></div>
                    <?php break; case 'TOOLS': ?>
                    <div class="col-md-4"><label class="form-label small">Description</label><input class="form-control form-control-sm" id="l_desc_TOOLS"></div>
                    <div class="col-md-1"><label class="form-label small">Qty</label><input type="number" step="0.01" class="form-control form-control-sm" id="l_qty_TOOLS"></div>
                    <div class="col-md-1"><label class="form-label small">Unit</label><input class="form-control form-control-sm" id="l_unit_TOOLS"></div>
                    <div class="col-md-2"><label class="form-label small">Unit cost</label><input type="number" step="0.01" class="form-control form-control-sm" id="l_uc_TOOLS"></div>
                    <div class="col-md-3"><label class="form-label small">Notes</label><input class="form-control form-control-sm" id="l_notes_TOOLS"></div>
                    <?php break; case 'SUBCONTRACTS': ?>
                    <div class="col-md-3"><label class="form-label small">Subcontractor</label><input class="form-control form-control-sm" id="l_name_SUBCONTRACTS"></div>
                    <div class="col-md-3"><label class="form-label small">Scope</label><input class="form-control form-control-sm" id="l_scope_SUBCONTRACTS"></div>
                    <div class="col-md-3"><label class="form-label small">Lump sum</label><input type="number" step="0.01" class="form-control form-control-sm" id="l_lump_SUBCONTRACTS"></div>
                    <div class="col-md-2"><label class="form-label small">Notes</label><input class="form-control form-control-sm" id="l_notes_SUBCONTRACTS"></div>
                    <?php break; case 'OVERHEADS': ?>
                    <div class="col-md-2"><label class="form-label small">Category</label>
                        <select class="form-select form-select-sm" id="l_cat_OVERHEADS">
                            <option value="HSE">HSE</option><option value="SITE_OFFICE">Site office</option><option value="TESTING">Testing</option>
                            <option value="INSURANCE">Insurance</option><option value="OTHER">Other</option>
                        </select>
                    </div>
                    <div class="col-md-5"><label class="form-label small">Description</label><input class="form-control form-control-sm" id="l_desc_OVERHEADS"></div>
                    <div class="col-md-2"><label class="form-label small">Amount</label><input type="number" step="0.01" class="form-control form-control-sm" id="l_amt_OVERHEADS"></div>
                    <div class="col-md-2"><label class="form-label small">Notes</label><input class="form-control form-control-sm" id="l_notes_OVERHEADS"></div>
                    <?php break; endswitch; ?>
            <div class="col-md-1 text-end">
                <button type="button" class="btn btn-sm btn-primary" onclick="crAddLine('<?= $pillar; ?>')"><i class="fas fa-plus"></i></button>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="card-body p-0">
        <?php if (!empty($pillarLns)): ?>
            <table class="table table-sm mb-0 align-middle">
                <thead class="table-light">
                    <?php switch ($pillar):
                        case 'PRELIMINARIES':
                        case 'OVERHEADS': ?>
                        <tr><th>#</th><th>Description</th><?php if ($pillar==='OVERHEADS'): ?><th style="width:100px;">Category</th><?php endif; ?><th class="text-end" style="width:130px;">Amount</th><?php if ($canEdit): ?><th style="width:50px;"></th><?php endif; ?></tr>
                        <?php break; case 'MANPOWER': ?>
                        <tr><th>#</th><th>Role</th><th style="width:70px;">Persons</th><th style="width:70px;">Days</th><th class="text-end" style="width:100px;">Rate</th><th class="text-end" style="width:120px;">Total</th><?php if ($canEdit): ?><th style="width:50px;"></th><?php endif; ?></tr>
                        <?php break; case 'MATERIALS':
                        case 'TOOLS': ?>
                        <tr><th>#</th><th>Description</th><th style="width:70px;">Qty</th><th style="width:60px;">Unit</th><th class="text-end" style="width:100px;">Unit cost</th><th class="text-end" style="width:120px;">Total</th><?php if ($canEdit): ?><th style="width:50px;"></th><?php endif; ?></tr>
                        <?php break; case 'EQUIPMENT': ?>
                        <tr><th>#</th><th>Description</th><th style="width:70px;">Hours</th><th class="text-end" style="width:100px;">Rate</th><th style="width:80px;">Source</th><th class="text-end" style="width:120px;">Total</th><?php if ($canEdit): ?><th style="width:50px;"></th><?php endif; ?></tr>
                        <?php break; case 'SUBCONTRACTS': ?>
                        <tr><th>#</th><th>Sub-contractor</th><th>Scope</th><th class="text-end" style="width:130px;">Lump sum</th><?php if ($canEdit): ?><th style="width:50px;"></th><?php endif; ?></tr>
                        <?php break; endswitch; ?>
                </thead>
                <tbody>
                    <?php foreach ($pillarLns as $ln): ?>
                        <tr>
                            <td class="text-muted"><?= (int)$ln['line_no']; ?></td>
                            <?php switch ($pillar):
                                case 'PRELIMINARIES': ?>
                                    <td><?= htmlspecialchars($ln['description']); ?><?php if (!empty($ln['notes'])): ?><div class="text-muted small"><?= htmlspecialchars($ln['notes']); ?></div><?php endif; ?></td>
                                    <td class="text-end"><strong><?= number_format((float)$ln['amount']); ?></strong></td>
                                    <?php break; case 'OVERHEADS': ?>
                                    <td><?= htmlspecialchars($ln['description']); ?><?php if (!empty($ln['notes'])): ?><div class="text-muted small"><?= htmlspecialchars($ln['notes']); ?></div><?php endif; ?></td>
                                    <td class="small"><span class="badge bg-light text-dark"><?= htmlspecialchars($ln['category']); ?></span></td>
                                    <td class="text-end"><strong><?= number_format((float)$ln['amount']); ?></strong></td>
                                    <?php break; case 'MANPOWER': ?>
                                    <td><?= htmlspecialchars($ln['role']); ?></td>
                                    <td class="small"><?= (int)$ln['persons']; ?></td>
                                    <td class="small"><?= number_format((float)$ln['days'], 1); ?></td>
                                    <td class="text-end small"><?= number_format((float)$ln['rate']); ?></td>
                                    <td class="text-end"><strong><?= number_format((float)$ln['total']); ?></strong></td>
                                    <?php break; case 'MATERIALS':
                                    case 'TOOLS': ?>
                                    <td><?= htmlspecialchars($ln['description']); ?></td>
                                    <td class="small"><?= number_format((float)$ln['qty'], 2); ?></td>
                                    <td class="small"><?= htmlspecialchars($ln['unit']); ?></td>
                                    <td class="text-end small"><?= number_format((float)$ln['unit_cost']); ?></td>
                                    <td class="text-end"><strong><?= number_format((float)$ln['total']); ?></strong></td>
                                    <?php break; case 'EQUIPMENT': ?>
                                    <td><?= htmlspecialchars($ln['description']); ?></td>
                                    <td class="small"><?= number_format((float)$ln['hours'], 1); ?></td>
                                    <td class="text-end small"><?= number_format((float)$ln['rate']); ?></td>
                                    <td class="small"><?= (int)$ln['in_house_flag'] === 1 ? 'In-house' : 'Hired'; ?></td>
                                    <td class="text-end"><strong><?= number_format((float)$ln['total']); ?></strong></td>
                                    <?php break; case 'SUBCONTRACTS': ?>
                                    <td><?= htmlspecialchars($ln['subcontractor_name']); ?></td>
                                    <td class="small text-muted"><?= htmlspecialchars($ln['scope']); ?></td>
                                    <td class="text-end"><strong><?= number_format((float)$ln['lump_sum']); ?></strong></td>
                                    <?php break; endswitch; ?>
                            <?php if ($canEdit): ?>
                                <td class="text-end"><button type="button" class="btn btn-sm btn-outline-danger" onclick="crDelLine('<?= $pillar; ?>', <?= (int)$ln['c0d']; ?>)"><i class="fas fa-trash"></i></button></td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</div>
<?php endforeach; ?>

<!-- Chain history if any -->
<?php if (!empty($approval)): ?>
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white"><strong>Approval chain</strong>
        <?php if ($approval['status'] !== 'IN_PROGRESS'): ?>
            <span class="badge ms-2" style="background:<?= ($approval['status']==='APPROVED')?'#22c55e':'#dc2626'; ?>;color:#fff;"><?= htmlspecialchars($approval['status']); ?></span>
        <?php endif; ?>
    </div>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light"><tr><th>When</th><th>Step</th><th>Action</th><th>By</th><th>Comment</th></tr></thead>
            <tbody>
                <?php foreach ($history as $h):
                    $dec = strtoupper((string)$h['decision']);
                    $col = ['SUBMIT'=>'#0ea5e9','APPROVE'=>'#22c55e','SEND_BACK'=>'#f59e0b','DECLINE'=>'#dc2626'][$dec] ?? '#94a3b8';
                ?>
                    <tr>
                        <td class="text-muted small"><?= htmlspecialchars($h['decided_on']); ?></td>
                        <td class="small"><?= htmlspecialchars($h['to_step_label'] ?? $h['from_step_label'] ?? '—'); ?></td>
                        <td><span class="badge" style="background:<?= $col; ?>;color:#fff;text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$dec))); ?></span></td>
                        <td class="small"><?= htmlspecialchars($h['actor_display'] ?? ''); ?></td>
                        <td class="text-muted small"><?= htmlspecialchars($h['comment']); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

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

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

function pillarPayload(pillar) {
    switch (pillar) {
        case 'PRELIMINARIES': return {
            description: $('#l_desc_PRELIMINARIES').val().trim(),
            amount:      $('#l_amt_PRELIMINARIES').val(),
            notes:       $('#l_notes_PRELIMINARIES').val(),
        };
        case 'MANPOWER': return {
            role:    $('#l_role_MANPOWER').val().trim(),
            persons: $('#l_persons_MANPOWER').val() || 1,
            days:    $('#l_days_MANPOWER').val(),
            rate:    $('#l_rate_MANPOWER').val(),
            notes:   $('#l_notes_MANPOWER').val(),
        };
        case 'MATERIALS': return {
            description: $('#l_desc_MATERIALS').val().trim(),
            qty:         $('#l_qty_MATERIALS').val(),
            unit:        $('#l_unit_MATERIALS').val(),
            unit_cost:   $('#l_uc_MATERIALS').val(),
            notes:       $('#l_notes_MATERIALS').val(),
        };
        case 'EQUIPMENT': return {
            description:   $('#l_desc_EQUIPMENT').val().trim(),
            hours:         $('#l_hrs_EQUIPMENT').val(),
            rate:          $('#l_rate_EQUIPMENT').val(),
            in_house_flag: $('#l_in_house_EQUIPMENT').val(),
            notes:         $('#l_notes_EQUIPMENT').val(),
        };
        case 'TOOLS': return {
            description: $('#l_desc_TOOLS').val().trim(),
            qty:         $('#l_qty_TOOLS').val(),
            unit:        $('#l_unit_TOOLS').val(),
            unit_cost:   $('#l_uc_TOOLS').val(),
            notes:       $('#l_notes_TOOLS').val(),
        };
        case 'SUBCONTRACTS': return {
            subcontractor_name: $('#l_name_SUBCONTRACTS').val().trim(),
            scope:              $('#l_scope_SUBCONTRACTS').val(),
            lump_sum:           $('#l_lump_SUBCONTRACTS').val(),
            notes:              $('#l_notes_SUBCONTRACTS').val(),
        };
        case 'OVERHEADS': return {
            category:    $('#l_cat_OVERHEADS').val(),
            description: $('#l_desc_OVERHEADS').val().trim(),
            amount:      $('#l_amt_OVERHEADS').val(),
            notes:       $('#l_notes_OVERHEADS').val(),
        };
    }
    return {};
}

function crAddLine(pillar) {
    var payload = pillarPayload(pillar);
    payload.cr_id = CR_ID;
    payload.pillar = pillar;
    // minimal validation
    if (pillar === 'MANPOWER' && !payload.role) { rsToast('Role required.', 'error'); return; }
    if (pillar === 'SUBCONTRACTS' && !payload.subcontractor_name) { rsToast('Sub-contractor name required.', 'error'); return; }
    if (['PRELIMINARIES','MATERIALS','EQUIPMENT','TOOLS','OVERHEADS'].indexOf(pillar) !== -1 && !payload.description) {
        rsToast('Description required.', 'error'); return;
    }
    $.post('<?= PROOT; ?>WorksCrs/addLineAj', payload, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}

function crDelLine(pillar, id) {
    if (!confirm('Delete this line?')) return;
    $.post('<?= PROOT; ?>WorksCrs/deleteLineAj', { cr_id: CR_ID, pillar: pillar, line_id: id }, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}

function crAddActivity() {
    var payload = {
        cr_id:                    CR_ID,
        title:                    $('#ac_title').val().trim(),
        unit:                     $('#ac_unit').val(),
        planned_qty:              $('#ac_qty').val() || 0,
        linked_phase_activity_id: $('#ac_link').val() || 0,
        linked_boq_item_id:       $('#ac_boq').val() || 0,
    };
    if (!payload.title) { rsToast('Title required.', 'error'); return; }
    $.post('<?= PROOT; ?>WorksCrs/addActivityAj', payload, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}

function crSubmit() {
    if (!confirm('Submit this CR for approval? PC → PM → FM → Exec. Cannot edit lines after submission.')) return;
    $.post('<?= PROOT; ?>WorksCrs/submitAj', { id: CR_ID }, 'json')
        .done(function (r) {
            if (r && r.ok) { rsToast('Submitted (approval #' + r.approval_id + ')', 'success'); setTimeout(function () { location.reload(); }, 700); }
            else rsToast('Failed: ' + (r.msg || 'unknown'), 'error');
        });
}
</script>
<?php $this->end(); ?>
