<?php $this->start('body');
    $p        = $this->data['project'];
    $phases   = $this->data['phases'] ?? [];
    $preferred = (int)($this->data['preferred_phase_id'] ?? 0);
    $existing = $this->data['existing'] ?? [];
    $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'],
    ];
?>
<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>
            New Consolidated Request · <?= htmlspecialchars($p['project_no']); ?>
        </h5>
        <div class="text-muted" style="font-size:.72rem;">
            <?= htmlspecialchars($p['project_customer']); ?> · <?= htmlspecialchars($p['project_name']); ?>
        </div>
    </div>
    <a href="<?= PROOT; ?>WorksPhases/plan/<?= (int)$p['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Phases</a>
</div>

<?php if (empty($phases)): ?>
    <div class="alert py-3" style="background:#FEF3C7;border:1px solid #F59E0B;color:#78350F;">
        <i class="fas fa-exclamation-triangle me-1"></i>
        <strong>No phases available.</strong> Create at least one PLANNED or ACTIVE phase first · <a href="<?= PROOT; ?>WorksPhases/plan/<?= (int)$p['c0d']; ?>">go to phase planner →</a>
    </div>
<?php else: ?>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Draft a new CR</strong>
        <span class="text-muted small ms-2">The CR is the phase's execution package + budget across 7 pillars</span>
    </div>
    <div class="card-body p-3" style="background:#F8FAFC;">
        <div class="row g-2">
            <div class="col-md-4">
                <label class="form-label" style="font-size:.78rem;">Phase</label>
                <select id="cr_phase" class="form-select form-select-sm">
                    <?php foreach ($phases as $ph): ?>
                        <option value="<?= (int)$ph['c0d']; ?>" <?= $preferred === (int)$ph['c0d'] ? 'selected' : ''; ?>>
                            <?= (int)$ph['phase_no']; ?> · <?= htmlspecialchars($ph['title']); ?> (<?= htmlspecialchars($ph['status']); ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-8">
                <label class="form-label" style="font-size:.78rem;">Title</label>
                <input id="cr_title" class="form-control form-control-sm" placeholder="e.g. Phase 1 execution package v1">
            </div>
            <div class="col-12">
                <label class="form-label" style="font-size:.78rem;">Notes (optional)</label>
                <textarea id="cr_notes" class="form-control form-control-sm" rows="2"></textarea>
            </div>
        </div>
    </div>
    <div class="card-footer bg-white text-end">
        <button type="button" id="btn_create" class="btn btn-sm btn-primary" style="background:#7A9E7E;border-color:#7A9E7E;">
            <i class="fas fa-plus me-1"></i> Create draft
        </button>
    </div>
</div>

<?php endif; ?>

<?php if (!empty($existing)): ?>
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white"><strong>CRs on this project · <?= count($existing); ?></strong></div>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th>Ref</th><th>Phase</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:80px;" class="text-end">Open</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($existing as $c):
                    $sp = $statusPill[$c['status']] ?? ['#94a3b8', $c['status']];
                ?>
                    <tr>
                        <td><code><?= htmlspecialchars($c['cr_no']); ?></code></td>
                        <td class="small">Ph.<?= (int)$c['phase_no']; ?> · <?= htmlspecialchars($c['phase_title']); ?></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:<?= $sp[0]; ?>;color:#fff;"><?= htmlspecialchars($sp[1]); ?></span></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>
    </div>
</div>
<?php endif; ?>

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

<?php $this->start('section_js'); ?>
<script>
$('#btn_create').on('click', function () {
    var payload = {
        project_id: <?= (int)$p['c0d']; ?>,
        phase_id:   $('#cr_phase').val(),
        title:      $('#cr_title').val().trim(),
        notes:      $('#cr_notes').val(),
    };
    if (!payload.title) { rsToast('Title required.', 'error'); return; }
    $.post('<?= PROOT; ?>WorksCrs/createAj', payload, 'json')
        .done(function (r) {
            if (r && r.ok) location.href = '<?= PROOT; ?>WorksCrs/view/' + r.id;
            else rsToast('Failed: ' + (r.msg || 'unknown'), 'error');
        });
});
</script>
<?php $this->end(); ?>
