$(function () {
    loadStates();
    loadItems();
    $('#searchBox, #stateFilter').on('change', loadItems);
    $('#searchBox').on('input', debounce(loadItems, 300));
    $('#btnAdd').on('click', function () { clearForm(); $('#modalTitle').text('Add LGA'); $('#itemId').val(0); new bootstrap.Modal(document.getElementById('itemModal')).show(); });
    $('#btnSave').on('click', saveItem);
    $(document).on('click', '.btn-edit', function () {
        var r = _cache.find(function (x) { return String(x.id) === String($(this).data('id')); });
        if (!r) return;
        $('#itemId').val(r.id); $('#itemName').val(r.name);
        var stateMatch = r.context && r.context.match(/State: (.+)/);
        var stateName = stateMatch ? stateMatch[1] : '';
        var stateOpt = _states.find(function (s) { return s.label === stateName; });
        $('#itemStateId').val(stateOpt ? stateOpt.id : '');
        $('#modalTitle').text('Edit LGA');
        new bootstrap.Modal(document.getElementById('itemModal')).show();
    });
    $(document).on('click', '.btn-toggle', function () {
        var r = _cache.find(function (x) { return String(x.id) === String($(this).data('id')); });
        if (!r) return;
        var newState = (r.is_active == 1) ? 0 : 1;
        $.post('api/compliance.php?action=toggle_setup_item', { setup_type: 'lgas', id: r.id, is_active: newState, csrf_token: window.CSRF_TOKEN }, function (res) {
            if (res.status === 'success') { loadItems(); showAlert('LGA ' + (newState ? 'activated' : 'deactivated'), 'success'); }
            else showAlert(res.message, 'danger');
        }, 'json');
    });
});
var _cache = [], _states = [];
function clearForm() { $('#itemId, #itemName').val(''); $('#itemStateId').val(''); }
function loadStates() {
    $.get('api/compliance.php?action=setup_options', function (r) {
        if (r.status !== 'success') return;
        _states = r.data.states || [];
        var html = '<option value="">All states</option>';
        _states.forEach(function (s) { html += '<option value="' + s.id + '">' + esc(s.label) + '</option>'; });
        $('#stateFilter').html(html);
        var html2 = '<option value="">Select state</option>';
        _states.forEach(function (s) { html2 += '<option value="' + s.id + '">' + esc(s.label) + '</option>'; });
        $('#itemStateId').html(html2);
    }, 'json');
}
function loadItems() {
    $.get('api/compliance.php', { action: 'setup_list', setup_type: 'lgas', search: $('#searchBox').val() }, function (r) {
        if (r.status !== 'success') return;
        var data = r.data || [];
        var filterState = $('#stateFilter').val();
        if (filterState) data = data.filter(function (x) { return x.context && x.context.indexOf('State: ') === 0; });
        _cache = data;
        var total = data.length, active = 0, inactive = 0;
        data.forEach(function (x) { if (x.is_active == 1) active++; else inactive++; });
        $('#kpiTotal').text(total); $('#kpiActive').text(active); $('#kpiInactive').text(inactive);
        var html = '';
        if (!data.length) html = '<tr><td colspan="4" class="text-center py-4 text-muted">No LGAs</td></tr>';
        else data.forEach(function (x) {
            var stateLabel = x.context || '-';
            html += '<tr><td class="fw-semibold">' + esc(x.name) + '</td><td>' + esc(stateLabel) + '</td>'
                + '<td>' + (x.is_active == 1 ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>') + '</td>'
                + '<td class="text-end"><div class="d-flex gap-1 justify-content-end">'
                + '<button class="btn btn-sm btn-outline-primary btn-edit" data-id="' + x.id + '"><i class="bi bi-pencil"></i></button>'
                + '<button class="btn btn-sm ' + (x.is_active == 1 ? 'btn-outline-warning' : 'btn-outline-success') + ' btn-toggle" data-id="' + x.id + '" title="' + (x.is_active == 1 ? 'Deactivate' : 'Activate') + '"><i class="bi bi-power"></i></button>'
                + '</div></td></tr>';
        });
        $('#tableBody').html(html);
    }, 'json');
}
function saveItem() {
    var p = { setup_type: 'lgas', name: $('#itemName').val().trim(), state_id: $('#itemStateId').val(), csrf_token: window.CSRF_TOKEN };
    if (!p.name) { showAlert('LGA name is required', 'danger'); return; }
    if (!p.state_id) { showAlert('State is required', 'danger'); return; }
    $.post('api/compliance.php?action=save_setup_item', p, function (r) {
        if (r.status !== 'success') { showAlert(r.message, 'danger'); return; }
        bootstrap.Modal.getInstance(document.getElementById('itemModal')).hide(); loadItems(); showAlert('LGA saved!', 'success');
    }, 'json').fail(function () { showAlert('Server error', 'danger'); });
}
function showAlert(msg, type) { var box = $('#alertBox'); box.removeClass('d-none alert-success alert-danger alert-warning alert-info').addClass('alert-' + type).text(msg); setTimeout(function () { box.addClass('d-none'); }, 5000); }
function esc(t) { return $('<div>').text(t || '').html(); }
function debounce(fn, ms) { var t; return function () { var c = this, a = arguments; clearTimeout(t); t = setTimeout(function () { fn.apply(c, a); }, ms); }; }
