$(function () {
    loadItems(); loadBrands();
    $('#searchBox, #brandFilter').on('change', loadItems);
    $('#searchBox').on('input', debounce(loadItems, 300));
    $('#btnAdd').on('click', function () { clearForm(); $('#itemModalTitle').text('Add Model'); $('#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_brand_id').val(r.brand_id); $('#item_name').val(r.name); $('#item_description').val(r.description||'');
        $('#itemModalTitle').text('Edit Model');
        new bootstrap.Modal(document.getElementById('itemModal')).show();
    });
    $(document).on('click', '.btn-delete', function () {
        if (!confirm('Delete this model?')) return;
        $.post('api/tyre_models.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(''); $('#item_brand_id').val(''); }
function loadBrands() {
    $.get('api/tyre_models.php', { action: 'brands' }, function (r) {
        if (r.status !== 'success') return;
        var h = '<option value="">All Brands</option>', h2 = '<option value="">Select brand</option>';
        (r.data||[]).forEach(function(x){ var o = '<option value="'+x.id+'">'+esc(x.name)+'</option>'; h += o; h2 += o; });
        $('#brandFilter').html(h); $('#item_brand_id').html(h2);
    },'json');
}
function loadItems() {
    $.get('api/tyre_models.php', { action: 'list', search: $('#searchBox').val(), brand_id: $('#brandFilter').val() }, function (r) {
        if (r.status !== 'success') return;
        var data = r.data || []; _cache = data;
        $('#kpiTotal').text(data.length);
        var brands = {}; data.forEach(function(x){ if (x.brand_name) brands[x.brand_name] = true; });
        $('#kpiBrands').text(Object.keys(brands).length);
        var html = '';
        if (!data.length) html = '<tr><td colspan="5" class="text-center py-4 text-muted">No models</td></tr>';
        else data.forEach(function(x){
            html += '<tr><td class="fw-semibold">' + esc(x.name) + '</td><td class="text-primary">' + esc(x.brand_name||'-') + '</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(), brand_id: $('#item_brand_id').val(), name: $('#item_name').val(), description: $('#item_description').val(), csrf_token: window.CSRF_TOKEN };
    if (!p.name) { showAlert('Model name is required','danger'); return; }
    if (!p.brand_id) { showAlert('Brand is required','danger'); return; }
    $.post('api/tyre_models.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);};}
