$(function () {
    loadTemplates();
    loadModules();
    $('#btnNewTemplate').on('click', function () { clearForm(); $('#templateModalTitle').text('New Template'); new bootstrap.Modal(document.getElementById('templateModal')).show(); });
    $('#btnSaveTemplate').on('click', saveTemplate);
    $('#btnAddStep').on('click', function () { addStepRow('', '', true); });
    $(document).on('click', '.btn-edit-template', function () { editTemplate($(this).data('id')); });
    $(document).on('click', '.btn-delete-template', function () { deleteTemplate($(this).data('id')); });
    // Module handlers
    $('#btnNewModule').on('click', function () { clearModuleForm(); $('#moduleModalTitle').text('Register Module'); new bootstrap.Modal(document.getElementById('moduleModal')).show(); });
    $('#btnSaveModule').on('click', saveModule);
    $(document).on('click', '.btn-edit-module', function () { editModule($(this).data('id')); });
    $(document).on('click', '.btn-delete-module', function () { deleteModule($(this).data('id')); });
});

var _roles = [];
var _modules = [];

function loadTemplates() {
    $.get('api/workflows.php?action=list_templates', function (r) {
        if (r.status !== 'success') return;
        var h = '';
        (r.data || []).forEach(function (t) {
            h += '<tr><td>' + esc(t.name) + '</td><td>' + esc(t.module) + '</td><td>' + (t.step_count || 0) + '</td><td>' + (t.is_active == 1 ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>') + '</td><td class="text-end"><button class="btn btn-sm btn-outline-primary btn-edit-template me-1" data-id="' + t.id + '"><i class="bi bi-pencil"></i> Edit</button><button class="btn btn-sm btn-outline-danger btn-delete-template" data-id="' + t.id + '"><i class="bi bi-trash"></i> Delete</button></td></tr>';
        });
        $('#templateTableBody').html(h || '<tr><td colspan="5" class="text-center text-muted py-4">No templates defined</td></tr>');
    }, 'json');
    loadRoles();
}

function loadModules() {
    $.get('api/workflows.php?action=list_modules', function (r) {
        if (r.status !== 'success') return;
        _modules = r.data || [];
        var h = '';
        (_modules).forEach(function (m) {
            h += '<tr><td>' + esc(m.display_name) + '</td><td><code>' + esc(m.module) + '</code></td><td><code>' + esc(m.table_name) + '</code></td><td><code>' + esc(m.creator_column) + '</code></td><td><code>' + esc(m.status_column) + '</code></td><td>' + (m.is_active == 1 ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-secondary">No</span>') + '</td><td class="text-end"><button class="btn btn-sm btn-outline-success btn-edit-module me-1" data-id="' + m.id + '"><i class="bi bi-pencil"></i> Edit</button><button class="btn btn-sm btn-outline-danger btn-delete-module" data-id="' + m.id + '"><i class="bi bi-trash"></i> Delete</button></td></tr>';
        });
        $('#moduleTableBody').html(h || '<tr><td colspan="7" class="text-center text-muted py-4">No modules registered</td></tr>');
        // Populate template module dropdown
        var opts = '<option value="">-- Select module --</option>';
        (_modules).forEach(function (m) { opts += '<option value="' + esc(m.module) + '">' + esc(m.display_name) + '</option>'; });
        $('#templateModule').html(opts);
    }, 'json');
}

function loadRoles() {
    $.get('api/permissions.php?action=roles', function (r) {
        if (r.status === 'success') _roles = r.data || [];
    }, 'json');
}

function clearForm() {
    $('#templateId').val(0);
    $('#templateName, #templateDescription').val('');
    $('#templateModule').val('');
    $('#templateActive').prop('checked', true);
    $('#stepsContainer').empty();
    addStepRow('', '', true);
}

function addStepRow(label, roleId, canDelegate) {
    var opts = '<option value="">Select role</option>';
    (_roles || []).forEach(function (r) { opts += '<option value="' + r.id + '"' + (String(r.id) === String(roleId) ? ' selected' : '') + '>' + esc(r.name) + '</option>'; });
    var checked = canDelegate ? ' checked' : '';
    var html = '<div class="step-row row g-2 mb-2 align-items-center"><div class="col-4"><input type="text" class="form-control form-control-sm step-label" placeholder="Label" value="' + esc(label) + '"></div><div class="col-4"><select class="form-select form-select-sm step-role">' + opts + '</select></div><div class="col-2"><div class="form-check"><input type="checkbox" class="form-check-input step-delegate"' + checked + '><label class="form-check-label small">Delegate</label></div></div><div class="col-2"><button type="button" class="btn btn-sm btn-outline-danger btn-remove-step"><i class="bi bi-x"></i></button></div></div>';
    $('#stepsContainer').append(html);
}

$(document).on('click', '.btn-remove-step', function () { $(this).closest('.step-row').remove(); });

function editTemplate(id) {
    $.get('api/workflows.php?action=get_template&id=' + id, function (r) {
        if (r.status !== 'success') { showAlert(r.message, 'danger'); return; }
        var t = r.data;
        $('#templateId').val(t.id);
        $('#templateName').val(t.name);
        $('#templateModule').val(t.module);
        $('#templateDescription').val(t.description || '');
        $('#templateActive').prop('checked', t.is_active == 1);
        $('#stepsContainer').empty();
        (t.steps || []).forEach(function (s) { addStepRow(s.label, s.role_id, s.can_delegate == 1); });
        if (!t.steps || t.steps.length === 0) addStepRow('', '', true);
        $('#templateModalTitle').text('Edit Template');
        new bootstrap.Modal(document.getElementById('templateModal')).show();
    }, 'json');
}

function saveTemplate() {
    var steps = [];
    $('#stepsContainer .step-row').each(function () {
        var label = $(this).find('.step-label').val().trim();
        var roleId = $(this).find('.step-role').val();
        var canDelegate = $(this).find('.step-delegate').is(':checked') ? 1 : 0;
        if (label && roleId) steps.push({ label: label, role_id: parseInt(roleId), can_delegate: canDelegate });
    });
    if (steps.length === 0) { showAlert('At least one step is required', 'warning'); return; }
    $.post('api/workflows.php?action=save_template', {
        id: $('#templateId').val(),
        name: $('#templateName').val().trim(),
        module: $('#templateModule').val(),
        description: $('#templateDescription').val().trim(),
        is_active: $('#templateActive').is(':checked') ? 1 : 0,
        steps: JSON.stringify(steps),
        csrf_token: window.CSRF_TOKEN
    }, function (r) {
        if (r.status !== 'success') { showAlert(r.message, 'danger'); return; }
        showAlert(r.message, 'success');
        bootstrap.Modal.getInstance(document.getElementById('templateModal')).hide();
        loadTemplates();
    }, 'json').fail(function () { showAlert('Server error', 'danger'); });
}

function deleteTemplate(id) {
    if (!confirm('Delete this template?')) return;
    $.post('api/workflows.php?action=delete_template', { id: id, csrf_token: window.CSRF_TOKEN }, function (r) {
        if (r.status !== 'success') { showAlert(r.message, 'danger'); return; }
        showAlert(r.message, 'success');
        loadTemplates();
    }, 'json');
}

function clearModuleForm() {
    $('#moduleId').val(0);
    $('#moduleKey, #moduleDisplayName, #moduleTable, #moduleCreatorCol, #moduleStatusCol, #moduleApprovedVal, #moduleRejectedVal, #moduleReturnedVal').val('');
    $('#moduleCreatorCol').val('created_by');
    $('#moduleStatusCol').val('status');
    $('#moduleApprovedVal').val('approved');
    $('#moduleRejectedVal').val('rejected');
    $('#moduleReturnedVal').val('returned');
    $('#moduleActive').prop('checked', true);
}

function editModule(id) {
    var m = _modules.find(function (x) { return x.id == id; });
    if (!m) return;
    $('#moduleId').val(m.id);
    $('#moduleKey').val(m.module);
    $('#moduleDisplayName').val(m.display_name);
    $('#moduleTable').val(m.table_name);
    $('#moduleCreatorCol').val(m.creator_column);
    $('#moduleStatusCol').val(m.status_column);
    $('#moduleApprovedVal').val(m.approved_value);
    $('#moduleRejectedVal').val(m.rejected_value);
    $('#moduleReturnedVal').val(m.returned_value);
    $('#moduleActive').prop('checked', m.is_active == 1);
    $('#moduleModalTitle').text('Edit Module');
    new bootstrap.Modal(document.getElementById('moduleModal')).show();
}

function saveModule() {
    var data = {
        id: $('#moduleId').val(),
        module: $('#moduleKey').val().trim(),
        display_name: $('#moduleDisplayName').val().trim(),
        table_name: $('#moduleTable').val().trim(),
        creator_column: $('#moduleCreatorCol').val().trim(),
        status_column: $('#moduleStatusCol').val().trim(),
        approved_value: $('#moduleApprovedVal').val().trim(),
        rejected_value: $('#moduleRejectedVal').val().trim(),
        returned_value: $('#moduleReturnedVal').val().trim(),
        is_active: $('#moduleActive').is(':checked') ? 1 : 0,
        csrf_token: window.CSRF_TOKEN
    };
    if (!data.module || !data.display_name || !data.table_name) { showAlert('Module ID, Display Name, and Table are required', 'warning'); return; }
    $.post('api/workflows.php?action=save_module', data, function (r) {
        if (r.status !== 'success') { showAlert(r.message, 'danger'); return; }
        showAlert(r.message, 'success');
        bootstrap.Modal.getInstance(document.getElementById('moduleModal')).hide();
        loadModules();
        loadTemplates();
    }, 'json').fail(function () { showAlert('Server error', 'danger'); });
}

function deleteModule(id) {
    if (!confirm('Delete this module registration?')) return;
    $.post('api/workflows.php?action=delete_module', { id: id, csrf_token: window.CSRF_TOKEN }, function (r) {
        if (r.status !== 'success') { showAlert(r.message, 'danger'); return; }
        showAlert(r.message, 'success');
        loadModules();
        loadTemplates();
    }, 'json');
}

function showAlert(msg, type) {
    var $a = $('#alertBox');
    $a.removeClass('d-none alert-success alert-danger alert-warning').addClass('alert-' + (type || 'success')).text(msg);
}

function esc(s) { return $('<span>').text(s).html(); }
