$(function () {
    loadApprovals('pending');
    $('#btnPending').on('click', function () { loadApprovals('pending'); });
    $('#btnApproved').on('click', function () { loadApprovals('approved'); });
    $('#btnRejected').on('click', function () { loadApprovals('rejected'); });
    $('#btnReturned').on('click', function () { loadApprovals('returned'); });
    $(document).on('click', '.btn-action', function () { openAction($(this).data('id'), $(this).data('status')); });
    $('#btnApproveAction').on('click', function () { doAction('approve'); });
    $('#btnRejectAction').on('click', function () { doAction('reject'); });
    $('#btnReturnAction').on('click', function () { doAction('return'); });
});

function loadApprovals(filter) {
    $.get('api/workflows.php?action=my_pending&status=' + filter, function (r) {
        if (r.status !== 'success') return;
        var h = '';
        var list = r.data || [];
        list.forEach(function (s) {
            h += '<tr><td>' + esc(s.module || '-') + '</td><td>' + esc(s.label || '-') + '</td><td>' + esc(s.assigned_user_name || 'Unassigned') + '</td><td>' + (s.created_at || '-') + '</td><td class="text-end">';
            if (s.status === 'pending') h += '<button class="btn btn-sm btn-outline-success btn-action me-1" data-id="' + s.id + '" data-status="pending"><i class="bi bi-check-lg"></i> Act</button>';
            else h += '<span class="badge bg-' + (s.status === 'approved' ? 'success' : s.status === 'rejected' ? 'danger' : 'info') + '">' + esc(s.status) + '</span>';
            h += '</td></tr>';
        });
        $('#approvalTableBody').html(h || '<tr><td colspan="5" class="text-center text-muted py-4">No items</td></tr>');
    }, 'json');
}

function openAction(stepId, status) {
    $('#actionStepId').val(stepId);
    $('#actionComment').val('');
    $('#actionInfo').text('Step #' + stepId);
    $('#btnApproveAction, #btnRejectAction, #btnReturnAction').show();
    $('#actionModalTitle').text('Approval Action');
    new bootstrap.Modal(document.getElementById('actionModal')).show();
}

function doAction(action) {
    var stepId = $('#actionStepId').val();
    var comment = $('#actionComment').val().trim();
    if ((action === 'reject' || action === 'return') && !comment) { showAlert('Comment is required for ' + action, 'warning'); return; }
    if ((action === 'reject' || action === 'return') && !confirm('Are you sure you want to ' + action + ' this step?')) return;
    $.post('api/workflows.php?action=' + action, { step_id: stepId, comment: comment, 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('actionModal')).hide();
        loadApprovals('pending');
    }, 'json').fail(function () { showAlert('Server error', 'danger'); });
}

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(); }
