<?php $this->start('body');
    $ph        = $this->data['phase'];
    $prj       = $this->data['project'] ?? [];
    $boqItems  = $this->data['boq_items']       ?? [];
    $available = $this->data['available_items'] ?? [];
    $activities = $this->data['activities']     ?? [];
    $crs       = $this->data['crs'] ?? [];
    $canEdit = in_array($ph['status'], ['PLANNED','ACTIVE'], true);

    $statusPill = [
        'PLANNED'   => ['#f59e0b', 'Planned'],
        'ACTIVE'    => ['#22c55e', 'Active'],
        'CLOSED'    => ['#7A8BA1', 'Closed'],
        'CANCELLED' => ['#dc2626', 'Cancelled'],
    ];
    $sp = $statusPill[$ph['status']] ?? ['#94a3b8', $ph['status']];

    $crStatusPill = [
        'DRAFT'      => ['#f59e0b', 'Draft'],
        'SUBMITTED'  => ['#0ea5e9', 'Submitted'],
        'APPROVED'   => ['#22c55e', 'Approved'],
        'ACTIVE'     => ['#166534', 'Active'],
        'SUPERSEDED' => ['#94a3b8', 'Superseded'],
        'CLOSED'     => ['#7A8BA1', 'Closed'],
        'DECLINED'   => ['#dc2626', 'Declined'],
        'CANCELLED'  => ['#94a3b8', 'Cancelled'],
    ];
?>
<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-layer-group me-1 text-muted"></i>
            Phase <?= (int)$ph['phase_no']; ?> · <?= htmlspecialchars($ph['title']); ?>
            <span class="badge ms-2" style="background:<?= $sp[0]; ?>;color:#fff;"><?= htmlspecialchars($sp[1]); ?></span>
        </h5>
        <div class="text-muted" style="font-size:.72rem;">
            Project <?= htmlspecialchars($prj['project_no'] ?? '?'); ?> · <?= htmlspecialchars($prj['project_name'] ?? ''); ?>
            <?php if ($ph['planned_start']): ?>· planned <?= htmlspecialchars($ph['planned_start']); ?> → <?= htmlspecialchars($ph['planned_end'] ?? '—'); ?><?php endif; ?>
        </div>
    </div>
    <div>
        <?php if ($canEdit): ?>
        <a href="<?= PROOT; ?>WorksCrs/create/<?= (int)$ph['project_id']; ?>?phase_id=<?= (int)$ph['c0d']; ?>" class="btn btn-sm btn-primary" style="background:#7A9E7E;border-color:#7A9E7E;">
            <i class="fas fa-file-invoice me-1"></i> Draft CR
        </a>
        <button type="button" id="btn_close_phase" class="btn btn-sm" style="background:#B87A5A;border-color:#B87A5A;color:#fff;">
            <i class="fas fa-flag-checkered me-1"></i> Close phase
        </button>
        <?php endif; ?>
        <a href="<?= PROOT; ?>WorksPhases/plan/<?= (int)$ph['project_id']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> All phases</a>
    </div>
</div>

<?php if (!empty($ph['closed_on'])): ?>
<div class="alert py-2 mb-3" style="background:#EDEEF2;border:1px solid #C9CCD4;color:#3D4E5B;font-size:.82rem;">
    <i class="fas fa-flag-checkered me-1"></i>
    Phase closed <strong><?= htmlspecialchars(substr((string)$ph['closed_on'], 0, 10)); ?></strong>
    by <?= htmlspecialchars((string)$ph['closed_by_name']); ?>.
</div>
<?php endif; ?>

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

<!-- BOQ items attached to this phase -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>BOQ items in this phase · <?= count($boqItems); ?></strong>
        <span class="text-muted small ms-2">Which contract lines get delivered here (with planned qty ≤ contract qty)</span>
    </div>
    <?php if ($canEdit && !empty($available)): ?>
    <div class="card-body p-3" style="background:#F8FAFC;">
        <div class="row g-2 align-items-end">
            <div class="col-md-6">
                <label class="form-label" style="font-size:.78rem;">BOQ item</label>
                <select id="bi_item" class="form-select form-select-sm">
                    <option value="">— Pick —</option>
                    <?php foreach ($available as $it): ?>
                        <option value="<?= (int)$it['c0d']; ?>" data-qty="<?= (float)$it['contract_qty']; ?>" data-unit="<?= htmlspecialchars($it['unit']); ?>">
                            <?= htmlspecialchars($it['item_no']); ?> · <?= htmlspecialchars(mb_strimwidth($it['description'], 0, 80, '…')); ?> · qty <?= number_format((float)$it['contract_qty'], 2); ?> <?= htmlspecialchars($it['unit']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label" style="font-size:.78rem;">Planned qty for this phase</label>
                <input type="number" step="0.01" min="0" id="bi_qty" class="form-control form-control-sm">
            </div>
            <div class="col-md-2">
                <label class="form-label" style="font-size:.78rem;">Notes</label>
                <input id="bi_notes" class="form-control form-control-sm">
            </div>
            <div class="col-md-1 text-end">
                <button type="button" class="btn btn-sm btn-primary" onclick="phAttachBoq()"><i class="fas fa-plus"></i></button>
            </div>
        </div>
    </div>
    <?php endif; ?>
    <div class="card-body p-0">
        <?php if (!empty($boqItems)): ?>
            <table class="table table-sm mb-0 align-middle">
                <thead class="table-light">
                    <tr><th>#</th><th>Description</th><th style="width:80px;">Unit</th>
                        <th style="width:110px;" class="text-end">Contract qty</th>
                        <th style="width:110px;" class="text-end">Planned qty</th>
                        <th style="width:120px;" class="text-end">Value</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($boqItems as $it): ?>
                        <tr>
                            <td class="text-muted"><?= htmlspecialchars($it['item_no']); ?></td>
                            <td><?= htmlspecialchars($it['description']); ?><?php if (!empty($it['notes'])): ?><div class="text-muted small"><?= htmlspecialchars($it['notes']); ?></div><?php endif; ?></td>
                            <td class="small"><?= htmlspecialchars($it['unit']); ?></td>
                            <td class="text-end small"><?= number_format((float)$it['contract_qty'], 2); ?></td>
                            <td class="text-end"><strong><?= number_format((float)$it['planned_qty'], 2); ?></strong></td>
                            <td class="text-end small"><?= number_format((float)$it['planned_qty'] * (float)$it['contract_rate']); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <div class="p-3 text-center text-muted small">No BOQ items attached yet.</div>
        <?php endif; ?>
    </div>
</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">The tasks the site will do to deliver this phase's BOQ output</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-2">
                <label class="form-label" style="font-size:.78rem;">Code</label>
                <input id="ac_code" class="form-control form-control-sm" placeholder="A1">
            </div>
            <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="Bulk cut + haul">
            </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" min="0" id="ac_qty" class="form-control form-control-sm">
            </div>
            <div class="col-md-2">
                <label class="form-label" style="font-size:.78rem;">Linked BOQ item</label>
                <select id="ac_boq" class="form-select form-select-sm">
                    <option value="0">—</option>
                    <?php foreach ($boqItems as $it): ?>
                        <option value="<?= (int)$it['boq_item_id']; ?>"><?= htmlspecialchars($it['item_no']); ?> · <?= htmlspecialchars(mb_strimwidth($it['description'], 0, 50, '…')); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-1 text-end">
                <button type="button" class="btn btn-sm btn-primary" onclick="phAddActivity()"><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:60px;">#</th><th style="width:80px;">Code</th><th>Title</th>
                        <th style="width:60px;">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><code><?= htmlspecialchars($a['code'] ?: '—'); ?></code></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.</div>
        <?php endif; ?>
    </div>
</div>

<!-- CRs on this phase -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <strong>Consolidated Requests · <?= count($crs); ?></strong>
        <span class="text-muted small">Phase execution package + budget across 7 pillars</span>
    </div>
    <div class="card-body p-0">
        <?php if (!empty($crs)): ?>
            <table class="table table-sm mb-0 align-middle">
                <thead class="table-light">
                    <tr><th>Ref</th><th>Title</th><th style="width:80px;">Ver</th>
                        <th class="text-end">Grand total</th>
                        <th style="width:110px;">Status</th>
                        <th style="width:130px;">Submitted</th>
                        <th style="width:80px;" class="text-end">Open</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($crs as $c):
                        $csp = $crStatusPill[$c['status']] ?? ['#94a3b8', $c['status']];
                    ?>
                        <tr>
                            <td><code><?= htmlspecialchars($c['cr_no']); ?></code></td>
                            <td><?= htmlspecialchars($c['title']); ?></td>
                            <td class="small">v<?= (int)$c['version']; ?></td>
                            <td class="text-end"><strong><?= number_format((float)$c['grand_total']); ?></strong></td>
                            <td><span class="badge" style="background:<?= $csp[0]; ?>;color:#fff;"><?= htmlspecialchars($csp[1]); ?></span></td>
                            <td class="text-muted small"><?= htmlspecialchars($c['submitted_on'] ?? '—'); ?></td>
                            <td class="text-end"><a href="<?= PROOT; ?>WorksCrs/view/<?= (int)$c['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-right"></i></a></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <div class="p-3 text-center text-muted small">No CRs yet — <a href="<?= PROOT; ?>WorksCrs/create/<?= (int)$ph['project_id']; ?>?phase_id=<?= (int)$ph['c0d']; ?>">draft the first one →</a></div>
        <?php endif; ?>
    </div>
</div>
<?php $this->end(); ?>

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

$('#bi_item').on('change', function () {
    var qty = $(this).find(':selected').data('qty');
    if (qty && !$('#bi_qty').val()) $('#bi_qty').val(qty);
});

$('#btn_close_phase').on('click', function () {
    $.confirm({
        title: 'Close this phase?',
        content: '<p style="font-size:.85rem;color:#5B4F3C;">All CRs on the phase must be CLOSED / SUPERSEDED / CANCELLED. Closure freezes the phase from further planning.</p>',
        boxWidth: '420px', useBootstrap: false,
        buttons: {
            confirm: {
                text: 'Close phase', btnClass: 'btn-danger',
                action: function () {
                    $.post('<?= PROOT; ?>WorksPhases/closeAj', { id: PH_ID }, 'json')
                        .done(function (r) {
                            if (r && r.ok) { rsToast('Phase closed.', 'success'); location.reload(); }
                            else            { rsToast('Cannot close: ' + (r.msg || 'unknown'), 'error'); }
                        });
                }
            },
            cancel: { text: 'Cancel' }
        }
    });
});

function phAttachBoq() {
    var payload = {
        phase_id:    PH_ID,
        boq_item_id: $('#bi_item').val(),
        planned_qty: $('#bi_qty').val(),
        notes:       $('#bi_notes').val(),
    };
    if (!payload.boq_item_id) { rsToast('Pick a BOQ item.', 'error'); return; }
    if (!(parseFloat(payload.planned_qty) > 0)) { rsToast('Planned qty > 0.', 'error'); return; }
    $.post('<?= PROOT; ?>WorksPhases/attachBoqItemAj', payload, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}

function phAddActivity() {
    var payload = {
        phase_id:           PH_ID,
        code:               $('#ac_code').val(),
        title:              $('#ac_title').val().trim(),
        unit:               $('#ac_unit').val(),
        planned_qty:        $('#ac_qty').val() || 0,
        linked_boq_item_id: $('#ac_boq').val() || 0,
    };
    if (!payload.title) { rsToast('Activity title required.', 'error'); return; }
    $.post('<?= PROOT; ?>WorksPhases/addActivityAj', payload, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
</script>
<?php $this->end(); ?>
