<?php $this->start('body');
    $tpl        = $this->data['tpl'];
    $items      = $this->data['items'] ?? [];
    $editable   = !empty($this->data['editable']);
    $inputTypes = $this->data['input_types'] ?? [];
?>
<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-clipboard-list me-1 text-muted"></i>
            <?= htmlspecialchars($tpl['code']); ?> v<?= (int)$tpl['version']; ?>
            <?php if (!$editable): ?><span class="badge ms-2" style="background:#dc2626;color:#fff;font-size:.65rem;">Locked (in-flight instances)</span><?php endif; ?>
        </h5>
        <div class="text-muted" style="font-size:.72rem;">
            <span style="text-transform:capitalize;"><?= htmlspecialchars($tpl['scope']); ?></span> ·
            target <?= htmlspecialchars($tpl['target_entity_type']); ?> ·
            cadence <?= htmlspecialchars(strtolower(str_replace('_',' ',$tpl['cadence']))); ?>
        </div>
    </div>
    <a href="<?= PROOT; ?>WorkTemplates" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Back</a>
</div>

<?php if (!$editable): ?>
    <div class="alert py-2 mb-3" style="background:#FEF3C7;border:1px solid #F59E0B;color:#78350F;">
        <i class="fas fa-lock me-1"></i>
        This template has live instances (DRAFT / SUBMITTED). To change items, click <strong>New version</strong> on the list — that forks a fresh copy without disturbing in-flight work.
    </div>
<?php endif; ?>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong><?= htmlspecialchars($tpl['title']); ?></strong></div>
    <div class="card-body p-3" style="background:#F8FAFC;">
        <?php if (!empty($tpl['description'])): ?>
            <div class="text-muted small mb-2"><?= htmlspecialchars($tpl['description']); ?></div>
        <?php endif; ?>
        <div class="row g-2 small text-muted">
            <div class="col-md-3">Expected minutes: <strong style="color:#334155;"><?= (int)$tpl['expected_minutes']; ?></strong></div>
            <div class="col-md-3">Reviewer role: <strong style="color:#334155;"><?= htmlspecialchars($tpl['reviewer_role'] ?: '—'); ?></strong></div>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <strong>Items · <?= count($items); ?></strong>
        <?php if ($editable): ?>
            <button type="button" class="btn btn-sm btn-outline-primary" onclick="wtAddItem()"><i class="fas fa-plus me-1"></i> Add item</button>
        <?php endif; ?>
    </div>
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th style="width:80px;">Order</th>
                    <th style="width:150px;">Section</th>
                    <th>Prompt</th>
                    <th style="width:110px;">Type</th>
                    <th style="width:80px;">Required</th>
                    <th style="width:100px;" class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($items as $it): ?>
                    <tr>
                        <td class="text-muted small"><?= (int)$it['sort_order']; ?></td>
                        <td class="text-muted small"><?= htmlspecialchars($it['section']); ?></td>
                        <td>
                            <div><?= htmlspecialchars($it['prompt']); ?></div>
                            <?php if (!empty($it['help_text'])): ?><div class="text-muted small"><?= htmlspecialchars($it['help_text']); ?></div><?php endif; ?>
                        </td>
                        <td><code class="small"><?= htmlspecialchars($it['input_type']); ?></code></td>
                        <td>
                            <?php if ((int)$it['is_required'] === 1): ?>
                                <span class="badge" style="background:#dc2626;color:#fff;">Required</span>
                            <?php else: ?>
                                <span class="text-muted small">—</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end">
                            <?php if ($editable): ?>
                                <button type="button" class="btn btn-sm btn-outline-danger" onclick="wtDeleteItem(<?= (int)$it['c0d']; ?>)"><i class="fas fa-trash"></i></button>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($items)): ?>
                    <tr><td colspan="6" class="text-center text-muted py-4">No items yet.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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

<?php $this->start('section_js'); ?>
<script>
const WT_ID = <?= (int)$tpl['c0d']; ?>;
function wtAddItem() {
    $.confirm({
        title: 'Add item',
        content: `
            <div class="row g-2">
                <div class="col-md-4"><label class="form-label small">Section</label><input id="it_sec" class="form-control form-control-sm" placeholder="e.g. Exterior"></div>
                <div class="col-md-8"><label class="form-label small">Prompt</label><input id="it_prompt" class="form-control form-control-sm" placeholder="e.g. Enclosure locked and undamaged?"></div>
                <div class="col-md-4"><label class="form-label small">Type</label>
                    <select id="it_type" class="form-select form-select-sm">
                        <?php foreach ($inputTypes as $t): ?><option value="<?= $t; ?>"><?= $t; ?></option><?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3"><label class="form-label small">Required?</label>
                    <select id="it_req" class="form-select form-select-sm"><option value="0">No</option><option value="1">Yes</option></select>
                </div>
                <div class="col-md-5"><label class="form-label small">Help text (optional)</label><input id="it_help" class="form-control form-control-sm"></div>
            </div>`,
        type: 'green',
        buttons: {
            save: { text: 'Add', btnClass: 'btn-success', action: function () {
                var payload = {
                    template_id: WT_ID,
                    section:  $('#it_sec').val().trim(),
                    prompt:   $('#it_prompt').val().trim(),
                    input_type: $('#it_type').val(),
                    is_required: $('#it_req').val(),
                    help_text: $('#it_help').val(),
                };
                if (!payload.prompt) { rsToast('Prompt required.', 'error'); return false; }
                $.post('<?= PROOT; ?>WorkTemplates/addItemAj', 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 wtDeleteItem(id) {
    if (!confirm('Delete this item?')) return;
    $.post('<?= PROOT; ?>WorkTemplates/deleteItemAj', { id: id }, 'json')
        .done(function (r) { if (r && r.ok) location.reload(); else rsToast('Failed: ' + (r.msg || 'unknown'), 'error'); });
}
</script>
<?php $this->end(); ?>
