$(function () {
    loadItems();
    $('#searchBox').on('input', debounce(loadItems, 300));
    $('#btnAdd').on('click', function () { clearForm(); $('#itemModalTitle').text('Add Location'); $('#item_id').val(0); new bootstrap.Modal(document.getElementById('itemModal')).show(); });
    $('#btnSave').on('click', saveItem);
    $(document).on('click', '.btn-edit', function () {
        var r = _cache.find(x => String(x.id) === String($(this).data('id')));
        if (!r) return;
        $('#item_id').val(r.id); $('#item_name').val(r.name); $('#item_description').val(r.description||'');
        $('#itemModalTitle').text('Edit Location');
        new bootstrap.Modal(document.getElementById('itemModal')).show();
    });
    $(document).on('click', '.btn-delete', function () {
        if (!confirm('Delete this bin location?')) return;
        $.post('api/bin_locations.php?action=delete', { id: $(this).data('id'), csrf_token: window.CSRF_TOKEN }, function (r) {
            if (r.status === 'success') { loadItems(); showAlert('Deleted','success'); } else showAlert(r.message,'danger');
        },'json');
    });
});

var _cache = [];

function clearForm() { $('#item_id, #item_name, #item_description').val(''); }

function loadItems() {
    $.get('api/bin_locations.php', { action: 'list', search: $('#searchBox').val() }, function (r) {
        if (r.status !== 'success') return;
        var data = r.data || []; _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 locations</td></tr>';
        else data.forEach(function(x){
            html += '<tr><td class="fw-semibold"><code>' + esc(x.name) + '</code></td><td>' + esc(x.description||'-') + '</td>' +
                '<td>' + (x.is_active == 1 ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>') + '</td>' +
                '<td><div class="d-flex gap-1"><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 btn-outline-danger btn-delete" data-id="' + x.id + '"><i class="bi bi-trash3"></i></button></div></td></tr>';
        });
        $('#tableBody').html(html);
    },'json');
}

function saveItem() {
    var p = { id: $('#item_id').val(), name: $('#item_name').val(), description: $('#item_description').val(), csrf_token: window.CSRF_TOKEN };
    if (!p.name) { showAlert('Name is required','danger'); return; }
    $.post('api/bin_locations.php?action=save', p, function (r) {
        if (r.status !== 'success') { showAlert(r.message,'danger'); return; }
        bootstrap.Modal.getInstance(document.getElementById('itemModal')).hide();
        loadItems(); showAlert('Saved!','success');
    },'json').fail(function(){showAlert('Server error','danger');});
}

function showAlert(msg, type) {
    var box = $('#alertBox');
    box.removeClass('d-none alert-success alert-danger').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);};}
