<?php $this->start('body');
    $rows   = $this->data['rows']   ?? [];
    $scopes = $this->data['scopes'] ?? [];
    $scopeColor = [
        'PM' => '#7A9E7E', 'INSPECTION' => '#6b8fbe', 'HANDOVER' => '#a78bfa',
        'RECEIVING' => '#D4A574', 'SAFETY' => '#dc2626', 'CHECKLIST' => '#94A3B8',
    ];
?>
<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> Work Templates</h5>
        <div class="text-muted" style="font-size:.72rem;">
            Reusable checklists consumed by Services PM plans, Works inspections, and Goods receiving.
        </div>
    </div>
    <button type="button" class="btn btn-sm btn-primary" onclick="wtNewTemplate()"
            style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
        <i class="fas fa-plus me-1"></i> New template
    </button>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-body p-0">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th>Code</th>
                    <th>Title</th>
                    <th>Scope</th>
                    <th>Target</th>
                    <th>Cadence</th>
                    <th>v.</th>
                    <th>Status</th>
                    <th class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rows as $t):
                    $col = $scopeColor[$t['scope']] ?? '#94A3B8';
                ?>
                    <tr>
                        <td><code><?= htmlspecialchars($t['code']); ?></code></td>
                        <td><strong><?= htmlspecialchars($t['title']); ?></strong></td>
                        <td><span class="badge" style="background:<?= $col; ?>;color:#fff;text-transform:capitalize;"><?= htmlspecialchars($t['scope']); ?></span></td>
                        <td class="text-muted small"><?= htmlspecialchars($t['target_entity_type']); ?></td>
                        <td class="text-muted small" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ',$t['cadence']))); ?></td>
                        <td class="text-muted small">v<?= (int)$t['version']; ?></td>
                        <td>
                            <?php if ((int)$t['is_active'] === 1): ?>
                                <span class="badge" style="background:#22c55e;color:#fff;">Active</span>
                            <?php else: ?>
                                <span class="badge" style="background:#94a3b8;color:#fff;">Retired</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end">
                            <a href="<?= PROOT; ?>WorkTemplates/edit/<?= (int)$t['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-pen"></i> Edit</a>
                            <?php if ((int)$t['is_active'] === 1): ?>
                                <button type="button" class="btn btn-sm btn-outline-warning" onclick="wtFork(<?= (int)$t['c0d']; ?>)"><i class="fas fa-code-branch"></i> New version</button>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($rows)): ?>
                    <tr><td colspan="8" class="text-center text-muted py-4">No templates yet. Click "New template" to author your first one.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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

<?php $this->start('section_js'); ?>
<script>
function wtNewTemplate() {
    $.confirm({
        title: 'New work template',
        content: `
            <div class="row g-2">
                <div class="col-md-4"><label class="form-label small">Code</label><input id="wt_code" class="form-control form-control-sm" placeholder="e.g. PM_GEN_5KVA"></div>
                <div class="col-md-8"><label class="form-label small">Title</label><input id="wt_title" class="form-control form-control-sm" placeholder="e.g. Monthly PM · 5kVA generator"></div>
                <div class="col-md-4"><label class="form-label small">Scope</label>
                    <select id="wt_scope" class="form-select form-select-sm">
                        <?php foreach ($scopes as $s): ?><option value="<?= $s; ?>"><?= $s; ?></option><?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4"><label class="form-label small">Target entity</label>
                    <select id="wt_target" class="form-select form-select-sm">
                        <option value="c_projects">c_projects (project)</option>
                        <option value="assets">assets (equipment)</option>
                        <option value="lpos">lpos (LPO)</option>
                        <option value="goods_client_pos">goods_client_pos (client PO)</option>
                    </select>
                </div>
                <div class="col-md-4"><label class="form-label small">Cadence (PM only)</label>
                    <select id="wt_cadence" class="form-select form-select-sm">
                        <option value="ON_DEMAND">On demand</option>
                        <option value="DAILY">Daily</option>
                        <option value="WEEKLY">Weekly</option>
                        <option value="MONTHLY">Monthly</option>
                        <option value="QUARTERLY">Quarterly</option>
                        <option value="YEARLY">Yearly</option>
                    </select>
                </div>
                <div class="col-12"><label class="form-label small">Description</label><textarea id="wt_desc" class="form-control form-control-sm" rows="2"></textarea></div>
            </div>`,
        type: 'green',
        buttons: {
            save: { text: 'Create', btnClass: 'btn-success', action: function () {
                var payload = {
                    code:  $('#wt_code').val().trim(),
                    title: $('#wt_title').val().trim(),
                    scope: $('#wt_scope').val(),
                    target_entity_type: $('#wt_target').val(),
                    cadence: $('#wt_cadence').val(),
                    description: $('#wt_desc').val(),
                };
                if (!payload.code || !payload.title) { rsToast('Code + title required.', 'error'); return false; }
                $.post('<?= PROOT; ?>WorkTemplates/createAj', payload, 'json')
                    .done(function (r) {
                        if (r && r.ok) location.href = '<?= PROOT; ?>WorkTemplates/edit/' + r.id;
                        else rsToast('Failed: ' + (r.msg || 'unknown'), 'error');
                    });
            }},
            cancel: { text: 'Cancel', btnClass: 'btn-light' }
        }
    });
}
function wtFork(id) {
    $.confirm({
        title: 'Fork a new version?',
        content: 'The current version will be retired and a fresh editable copy (v+1) created. Live instances keep pointing at the retired version.',
        type: 'orange',
        buttons: {
            fork: { text: 'Fork', btnClass: 'btn-warning', action: function () {
                $.post('<?= PROOT; ?>WorkTemplates/newVersionAj', { id: id }, 'json')
                    .done(function (r) {
                        if (r && r.ok) location.href = '<?= PROOT; ?>WorkTemplates/edit/' + r.id;
                        else rsToast('Failed: ' + (r.msg || 'unknown'), 'error');
                    });
            }},
            cancel: { text: 'Cancel', btnClass: 'btn-light' }
        }
    });
}
</script>
<?php $this->end(); ?>
