<?php $this->start('body');
    $tpl   = $this->data['tpl'];
    $items = $this->data['items'] ?? [];
    $types = $this->data['asset_types'] ?? [];
    // Group items by section for display
    $bySection = [];
    foreach ($items as $it) { $bySection[$it['section'] ?: '(no section)'][] = $it; }
?>
<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-2 text-muted"></i><?= htmlspecialchars($tpl['code']); ?> <span class="text-muted small">v<?= (int)$tpl['version']; ?></span></h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            <?= htmlspecialchars($tpl['name']); ?>
            <?php if (!empty($tpl['asset_type_code'])): ?> &middot; <i class="fas <?= htmlspecialchars((string)$tpl['asset_icon']); ?>"></i> <?= htmlspecialchars($tpl['asset_type_code']); ?><?php endif; ?>
            &middot; <?= htmlspecialchars(strtolower($tpl['scope'])); ?>
            <?php if (!empty($tpl['cadence_value'])): ?> &middot; every <?= (int)$tpl['cadence_value']; ?> <?= htmlspecialchars(strtolower($tpl['cadence_type'])); ?><?php endif; ?>
            &middot; <?= count($items); ?> item<?= count($items) === 1 ? '' : 's'; ?>
        </div>
    </div>
    <div class="d-flex gap-2">
        <button type="button" id="btn_clone" class="btn btn-sm btn-outline-secondary"><i class="fas fa-clone me-1"></i>Clone v<?= (int)$tpl['version'] + 1; ?></button>
        <button type="button" id="btn_add_item" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;"><i class="fas fa-plus me-1"></i>Add item</button>
        <a href="<?= PROOT; ?>PmTemplates" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
    </div>
</div>

<?php if (!empty($tpl['description'])): ?>
<div class="card border-0 shadow-sm mb-3"><div class="card-body p-2 small text-muted"><?= nl2br(htmlspecialchars((string)$tpl['description'])); ?></div></div>
<?php endif; ?>

<?php foreach ($bySection as $section => $rows): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header py-2 small" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-weight:600;color:#334155;">
        <?= htmlspecialchars($section); ?> <span class="text-muted" style="font-weight:400;">(<?= count($rows); ?>)</span>
    </div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light"><tr><th style="width:40px;">#</th><th>Task</th><th style="width:110px;">Input</th><th>Unit</th><th>Required</th><th>Tracks qty</th><th style="width:60px;" class="text-end"></th></tr></thead>
            <tbody>
                <?php foreach ($rows as $it): ?>
                    <tr data-id="<?= (int)$it['c0d']; ?>" data-json='<?= htmlspecialchars(json_encode($it), ENT_QUOTES); ?>'>
                        <td class="text-muted small"><?= (int)$it['sort_order']; ?></td>
                        <td class="small"><?= htmlspecialchars($it['task']); ?></td>
                        <td class="small"><span class="badge bg-light text-muted" style="font-size:.6rem;"><?= htmlspecialchars(strtolower($it['input_type'])); ?></span></td>
                        <td class="small text-muted"><?= htmlspecialchars((string)($it['unit'] ?? '')); ?></td>
                        <td class="small"><?= (int)$it['is_required'] === 1 ? '<i class="fas fa-check text-success"></i>' : ''; ?></td>
                        <td class="small"><?= (int)$it['tracks_qty'] === 1 ? '<i class="fas fa-check text-success"></i>' : ''; ?></td>
                        <td class="text-end">
                            <button type="button" class="btn btn-sm btn-link p-0 me-2 tpl_edit"><i class="fas fa-pen" style="color:#7A8BA1;"></i></button>
                            <button type="button" class="btn btn-sm btn-link p-0 tpl_del text-danger"><i class="fas fa-times"></i></button>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endforeach; ?>

<?php if (empty($items)): ?>
<div class="card border-0 shadow-sm"><div class="card-body p-4 text-center text-muted small">No items yet — click <strong>Add item</strong>.</div></div>
<?php endif; ?>

<script>
(function () {
    var TPL_ID = <?= (int)$tpl['c0d']; ?>;
    var PROOT  = '<?= PROOT; ?>';
    function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]); }); }
    function itemForm(d) {
        d = d || {};
        var typeOpts = ['CHECK','NUMBER','TEXT','PHOTO','SIGNATURE'].map(function (t) {
            return '<option value="' + t + '"' + ((d.input_type||'CHECK') === t ? ' selected' : '') + '>' + t + '</option>';
        }).join('');
        return '<form id="it_form">' +
            '<input type="hidden" name="c0d" value="' + (d.c0d || '') + '">' +
            '<input type="hidden" name="template_id" value="' + TPL_ID + '">' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-3"><label class="form-label small">Order</label><input name="sort_order" type="number" class="form-control form-control-sm" value="' + (d.sort_order || 0) + '"></div>' +
              '<div class="col-9"><label class="form-label small">Section</label><input name="section" class="form-control form-control-sm" value="' + esc(d.section||'') + '" placeholder="e.g. Engine, Cooling, Safety"></div>' +
            '</div>' +
            '<div class="mb-2"><label class="form-label small">Task *</label><input name="task" class="form-control form-control-sm" value="' + esc(d.task||'') + '" required></div>' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-3"><label class="form-label small">Input</label><select name="input_type" class="form-select form-select-sm">' + typeOpts + '</select></div>' +
              '<div class="col-3"><label class="form-label small">Unit</label><input name="unit" class="form-control form-control-sm" value="' + esc(d.unit||'') + '" placeholder="hrs, %, L"></div>' +
              '<div class="col-3 pt-4"><div class="form-check"><input type="checkbox" name="is_required" class="form-check-input" ' + (parseInt(d.is_required||1)===1?'checked':'') + '><label class="form-check-label small">Required</label></div></div>' +
              '<div class="col-3 pt-4"><div class="form-check"><input type="checkbox" name="tracks_qty" class="form-check-input" ' + (parseInt(d.tracks_qty||0)===1?'checked':'') + '><label class="form-check-label small">Tracks qty</label></div></div>' +
            '</div>' +
        '</form>';
    }
    function saveItem(d) {
        $.confirm({ title: d && d.c0d ? 'Edit item' : 'Add item', columnClass:'col-md-7', content: itemForm(d), type:'green', buttons: {
            save: { text:'Save', btnClass:'btn-success', action: function () {
                var f = document.getElementById('it_form');
                var p = { c0d: f.c0d.value, template_id: f.template_id.value, sort_order: f.sort_order.value, section: f.section.value, task: f.task.value, input_type: f.input_type.value, unit: f.unit.value, is_required: f.is_required.checked ? 1 : 0, tracks_qty: f.tracks_qty.checked ? 1 : 0 };
                $.post(PROOT + 'PmTemplates/saveItemAj', p, function (r) {
                    if (r && r.ok) { rsToast('Saved.','success'); setTimeout(function(){location.reload();}, 400); }
                    else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                }, 'json');
            }}, cancel: function () {}
        }});
    }
    document.getElementById('btn_add_item').addEventListener('click', function () { saveItem({}); });
    document.querySelectorAll('.tpl_edit, .tpl_del').forEach(function (b) {
        b.addEventListener('click', function () {
            var tr = b.closest('tr'); var data = JSON.parse(tr.getAttribute('data-json'));
            if (b.classList.contains('tpl_edit')) { saveItem(data); return; }
            $.confirm({ title:'Remove item?', type:'red', content: esc(data.task), buttons: {
                yes: { text:'Remove', btnClass:'btn-danger', action: function () {
                    $.post(PROOT + 'PmTemplates/deleteItemAj', { id: data.c0d }, function (r) {
                        if (r && r.ok) { rsToast('Removed.','success'); setTimeout(function(){location.reload();}, 300); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }}, cancel: function () {}
            }});
        });
    });
    document.getElementById('btn_clone').addEventListener('click', function () {
        $.confirm({ title:'Clone as new version?', type:'orange', content:'A fresh version will be created with all current items. Original stays intact.', buttons: {
            yes: { text:'Clone', btnClass:'btn-warning', action: function () {
                $.post(PROOT + 'PmTemplates/cloneAj', { id: TPL_ID }, function (r) {
                    if (r && r.ok) { rsToast('Cloned.','success'); setTimeout(function(){window.location.href = PROOT + 'PmTemplates/view/' + r.new_id;}, 500); }
                    else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                }, 'json');
            }}, cancel: function () {}
        }});
    });
})();
</script>
<?php $this->end(); ?>
