<?php $this->start('body');
    $pb          = $this->data['pb'];
    $slas        = $this->data['slas']        ?? [];
    $escalations = $this->data['escalations'] ?? [];
    $severities  = $this->data['severities']  ?? ['P1','P2','P3','P4'];

    $slaBySeverity = [];
    foreach ($slas as $s) $slaBySeverity[$s['severity']] = $s;

    $severityColor = ['P1'=>'#dc2626','P2'=>'#f59e0b','P3'=>'#0ea5e9','P4'=>'#94a3b8'];
    $severityLabel = ['P1'=>'P1 · Critical','P2'=>'P2 · Major','P3'=>'P3 · Minor','P4'=>'P4 · Cosmetic'];
?>
<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-shield-alt me-1 text-muted"></i>
            <?= htmlspecialchars($pb['code']); ?> · <?= htmlspecialchars($pb['name']); ?>
            <?php if ((int)$pb['is_active'] === 0): ?><span class="badge ms-2" style="background:#94a3b8;color:#fff;">Retired</span><?php endif; ?>
        </h5>
        <?php if (!empty($pb['description'])): ?><div class="text-muted" style="font-size:.72rem;"><?= htmlspecialchars($pb['description']); ?></div><?php endif; ?>
    </div>
    <div>
        <a href="<?= PROOT; ?>CalloutPlaybooks" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Back</a>
        <?php if ((int)$pb['is_active'] === 1): ?>
            <button type="button" class="btn btn-sm btn-outline-warning" onclick="cpToggleActive(0)"><i class="fas fa-pause me-1"></i> Retire</button>
        <?php else: ?>
            <button type="button" class="btn btn-sm btn-outline-success" onclick="cpToggleActive(1)"><i class="fas fa-play me-1"></i> Reactivate</button>
        <?php endif; ?>
    </div>
</div>

<!-- SLA matrix -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>SLA targets by severity</strong>
        <span class="text-muted small ms-2">Response = arrive/acknowledge · Resolution = fault fixed / workaround in place</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:140px;">Severity</th>
                    <th style="width:180px;">Response target (hours)</th>
                    <th style="width:180px;">Resolution target (hours)</th>
                    <th>Notes</th>
                    <th style="width:80px;" class="text-end">Save</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($severities as $sev):
                    $row = $slaBySeverity[$sev] ?? null;
                    $col = $severityColor[$sev] ?? '#94A3B8';
                ?>
                    <tr data-sev="<?= $sev; ?>">
                        <td><span class="badge" style="background:<?= $col; ?>;color:#fff;"><?= htmlspecialchars($severityLabel[$sev] ?? $sev); ?></span></td>
                        <td><input type="number" step="0.25" min="0" class="form-control form-control-sm sla-resp" value="<?= $row ? (float)$row['response_target_hours'] : ''; ?>"></td>
                        <td><input type="number" step="0.25" min="0" class="form-control form-control-sm sla-res"  value="<?= $row ? (float)$row['resolution_target_hours'] : ''; ?>"></td>
                        <td><input type="text" class="form-control form-control-sm sla-notes" value="<?= htmlspecialchars($row['notes'] ?? ''); ?>"></td>
                        <td class="text-end"><button type="button" class="btn btn-sm btn-outline-primary sla-save"><i class="fas fa-save"></i></button></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Escalation chain -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <strong>Escalation chain</strong>
        <button type="button" class="btn btn-sm btn-outline-primary" onclick="cpAddEsc()"><i class="fas fa-plus me-1"></i> Add step</button>
    </div>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th style="width:100px;">Severity</th>
                    <th style="width:60px;">Step</th>
                    <th>Role to notify</th>
                    <th style="width:150px;">After (hours)</th>
                    <th>Notes</th>
                    <th style="width:60px;"></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($escalations as $e):
                    $col = $severityColor[$e['severity']] ?? '#94A3B8';
                ?>
                    <tr>
                        <td><span class="badge" style="background:<?= $col; ?>;color:#fff;"><?= htmlspecialchars($e['severity']); ?></span></td>
                        <td class="text-center small"><?= (int)$e['step_no']; ?></td>
                        <td><?= htmlspecialchars($e['role']); ?></td>
                        <td class="small"><?= number_format((float)$e['notify_after_hours'], 2); ?>h</td>
                        <td class="text-muted small"><?= htmlspecialchars($e['notes']); ?></td>
                        <td class="text-end">
                            <button type="button" class="btn btn-sm btn-outline-danger" onclick="cpDelEsc(<?= (int)$e['c0d']; ?>)"><i class="fas fa-trash"></i></button>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($escalations)): ?>
                    <tr><td colspan="6" class="text-center text-muted py-3">No escalation steps yet.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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

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

$('.sla-save').on('click', function () {
    const tr = $(this).closest('tr');
    const payload = {
        playbook_id:      PB_ID,
        severity:         tr.data('sev'),
        response_hours:   tr.find('.sla-resp').val() || 0,
        resolution_hours: tr.find('.sla-res').val()  || 0,
        notes:            tr.find('.sla-notes').val() || '',
    };
    $.post('<?= PROOT; ?>CalloutPlaybooks/upsertSlaAj', payload, 'json')
        .done(function (r) { if (r && r.ok) rsToast('Saved.', 'success'); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
});

function cpAddEsc() {
    $.confirm({
        title: 'Add escalation step',
        content: `
            <div class="row g-2">
                <div class="col-md-4"><label class="form-label small">Severity</label>
                    <select id="es_sev" class="form-select form-select-sm">
                        <option value="P1">P1 · Critical</option>
                        <option value="P2">P2 · Major</option>
                        <option value="P3">P3 · Minor</option>
                        <option value="P4">P4 · Cosmetic</option>
                    </select>
                </div>
                <div class="col-md-4"><label class="form-label small">Step no</label><input type="number" id="es_step" min="1" value="1" class="form-control form-control-sm"></div>
                <div class="col-md-4"><label class="form-label small">Notify after (hours)</label><input type="number" id="es_after" step="0.25" min="0" value="0" class="form-control form-control-sm"></div>
                <div class="col-md-8"><label class="form-label small">Role</label><input type="text" id="es_role" class="form-control form-control-sm" placeholder="e.g. Project Manager"></div>
                <div class="col-md-4"><label class="form-label small">Notes</label><input type="text" id="es_notes" class="form-control form-control-sm"></div>
            </div>`,
        type: 'green',
        buttons: {
            save: { text: 'Add', btnClass: 'btn-success', action: function () {
                var payload = {
                    playbook_id:        PB_ID,
                    severity:           $('#es_sev').val(),
                    step_no:            $('#es_step').val(),
                    role:               $('#es_role').val().trim(),
                    notify_after_hours: $('#es_after').val(),
                    notes:              $('#es_notes').val(),
                };
                if (!payload.role) { rsToast('Role required.', 'error'); return false; }
                $.post('<?= PROOT; ?>CalloutPlaybooks/addEscalationAj', payload, 'json')
                    .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
            }},
            cancel: { text: 'Cancel', btnClass: 'btn-light' }
        }
    });
}
function cpDelEsc(id) {
    if (!confirm('Delete this escalation step?')) return;
    $.post('<?= PROOT; ?>CalloutPlaybooks/deleteEscalationAj', { id: id }, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
function cpToggleActive(active) {
    $.post('<?= PROOT; ?>CalloutPlaybooks/setActiveAj', { id: PB_ID, active: active }, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
</script>
<?php $this->end(); ?>
