$(function () {
    loadItems(); loadFilters();
    $('#searchBox, #categoryFilter').on('change', loadItems);
    $('#searchBox').on('input', debounce(loadItems, 300));
    $('#btnAddItem').on('click', function () { clearForm(); $('#itemModalTitle').text('Add Catalog Item'); $('#item_id').val(0); new bootstrap.Modal(document.getElementById('itemModal')).show(); });
    $('#btnSaveItem').on('click', saveItem);
    $(document).on('click', '.btn-edit-item', 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_part_number').val(r.part_number||'');
        $('#item_category_id').val(r.category_id||'');
        $('#item_unit_of_measure').val(r.unit_of_measure||'');
        $('#item_default_unit_cost').val(r.default_unit_cost||'');
        $('#item_default_reorder_level').val(r.default_reorder_level||'');
        $('#itemModalTitle').text('Edit Catalog Item');
        new bootstrap.Modal(document.getElementById('itemModal')).show();
    });
    $(document).on('click', '.btn-delete-item', function () {
        if (!confirm('Deactivate this catalog item?')) return;
        $.post('api/part_catalog.php?action=delete', { id: $(this).data('id'), csrf_token: window.CSRF_TOKEN }, function (r) {
            if (r.status === 'success') { loadItems(); showAlert('Item deactivated','success'); } else showAlert(r.message,'danger');
        },'json');
    });
});

var _cache = [];

function clearForm() {
    $('#item_id, #item_name, #item_part_number, #item_unit_of_measure, #item_default_unit_cost, #item_default_reorder_level').val('');
    $('#item_category_id').val('');
}

function loadFilters() {
    $.get('api/part_catalog.php', { action: 'categories' }, function (r) {
        if (r.status !== 'success') return;
        var h = '<option value="">All Categories</option>';
        (r.data||[]).forEach(function(x){ h += '<option value="' + x.id + '">' + esc(x.name) + '</option>'; });
        $('#categoryFilter').html(h);
        $('#item_category_id').html('<option value="">Select category</option>' + h.substring(45));
    },'json');
}

function loadItems() {
    $.get('api/part_catalog.php', { action: 'list', search: $('#searchBox').val(), category_id: $('#categoryFilter').val() }, function (r) {
        if (r.status !== 'success') return;
        var data = r.data || []; _cache = data;
        var total = data.length, active = 0;
        var cats = {};
        data.forEach(function (x) { if (x.is_active == 1 || x.is_active === '1') active++; if (x.category_name) cats[x.category_name] = true; });
        $('#kpiTotal').text(total);
        $('#kpiActive').text(active);
        $('#kpiCategories').text(Object.keys(cats).length);
        var html = '';
        if (!data.length) html = '<tr><td colspan="8" class="text-center py-4 text-muted">No catalog items</td></tr>';
        else data.forEach(function (x) {
            var status = (x.is_active == 1 || x.is_active === '1') ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>';
            html += '<tr><td class="fw-semibold">' + esc(x.name) + '</td><td><code>' + esc(x.part_number||'-') + '</code></td><td>' + esc(x.category_name||'-') + '</td>' +
                '<td>' + esc(x.unit_of_measure||'-') + '</td><td>' + (x.default_unit_cost ? '₦' + Number(x.default_unit_cost).toLocaleString() : '-') + '</td>' +
                '<td>' + (x.default_reorder_level ? Number(x.default_reorder_level).toLocaleString() : '-') + '</td><td>' + status + '</td>' +
                '<td><div class="d-flex gap-1"><button class="btn btn-sm btn-outline-primary btn-edit-item" data-id="' + x.id + '"><i class="bi bi-pencil"></i></button>' +
                '<button class="btn btn-sm btn-outline-danger btn-delete-item" data-id="' + x.id + '"><i class="bi bi-trash3"></i></button></div></td></tr>';
        });
        $('#catalogTableBody').html(html);
    },'json');
}

function saveItem() {
    var p = {
        id: $('#item_id').val(),
        name: $('#item_name').val(),
        part_number: $('#item_part_number').val(),
        category_id: $('#item_category_id').val(),
        unit_of_measure: $('#item_unit_of_measure').val(),
        default_unit_cost: $('#item_default_unit_cost').val(),
        default_reorder_level: $('#item_default_reorder_level').val(),
        csrf_token: window.CSRF_TOKEN
    };
    if (!p.name) { showAlert('Item name is required','danger'); return; }
    $.post('api/part_catalog.php?action=save', p, function (r) {
        if (r.status !== 'success') { showAlert(r.message,'danger'); return; }
        bootstrap.Modal.getInstance(document.getElementById('itemModal')).hide();
        loadItems();
        showAlert('Catalog item 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);};}
