$(function () {
    loadSuppliers();
    $('#searchBox, #statusFilter').on('change', loadSuppliers);
    $('#searchBox').on('input', debounce(loadSuppliers, 300));
    $('#btnAddSupplier').on('click', function () { clearForm(); $('#supplierModalTitle').text('Add Supplier'); $('#supplier_id').val(0); new bootstrap.Modal(document.getElementById('supplierModal')).show(); });
    $('#btnSaveSupplier').on('click', saveSupplier);
    $(document).on('click', '.btn-edit-supplier', function () {
        var r = _cache.find(x => String(x.id) === String($(this).data('id')));
        if (!r) return;
        $('#supplier_id').val(r.id);
        $('#supplier_name').val(r.name);
        $('#supplier_contact_person').val(r.contact_person||'');
        $('#supplier_phone').val(r.phone||'');
        $('#supplier_email').val(r.email||'');
        $('#supplier_address').val(r.address||'');
        $('#supplier_status').val(r.status||'active');
        $('#supplierModalTitle').text('Edit Supplier');
        new bootstrap.Modal(document.getElementById('supplierModal')).show();
    });
    $(document).on('click', '.btn-delete-supplier', function () {
        if (!confirm('Delete this supplier?')) return;
        $.post('api/suppliers.php?action=delete', { id: $(this).data('id'), csrf_token: window.CSRF_TOKEN }, function (r) {
            if (r.status === 'success') { loadSuppliers(); showAlert('Supplier deleted','success'); } else showAlert(r.message,'danger');
        },'json');
    });
});

var _cache = [];

function clearForm() {
    $('#supplier_id').val(0);
    $('#supplier_name, #supplier_contact_person, #supplier_phone, #supplier_email, #supplier_address').val('');
    $('#supplier_status').val('active');
}

function loadSuppliers() {
    $.get('api/suppliers.php', { action: 'list', search: $('#searchBox').val(), status: $('#statusFilter').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.status === 'active') active++; else inactive++; });
        $('#kpiTotal').text(total);
        $('#kpiActive').text(active);
        $('#kpiInactive').text(inactive);
        $.get('api/parts.php?action=list', function (pr) {
            var parts = (pr.data||[]).filter(function(p){ return p.supplier_id; });
            var count = {};
            parts.forEach(function(p){ count[p.supplier_id] = (count[p.supplier_id]||0) + 1; });
            var html = '';
            if (!data.length) html = '<tr><td colspan="6" class="text-center py-4 text-muted">No suppliers</td></tr>';
            else data.forEach(function (x) {
                var c = count[x.id] || 0;
                html += '<tr><td class="fw-semibold">' + esc(x.name) + '</td><td>' + esc(x.contact_person||'-') + '</td><td>' + esc(x.phone||'-') + '</td><td>' + esc(x.email||'-') + '</td>' +
                    '<td>' + (x.status === 'active' ? '<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-supplier" data-id="' + x.id + '"><i class="bi bi-pencil"></i></button>' +
                    '<button class="btn btn-sm btn-outline-danger btn-delete-supplier" data-id="' + x.id + '"><i class="bi bi-trash3"></i></button></div></td></tr>';
            });
            $('#kpiParts').text(parts.length);
            $('#supplierTableBody').html(html);
        },'json');
    },'json');
}

function saveSupplier() {
    var p = {
        id: $('#supplier_id').val(),
        name: $('#supplier_name').val(),
        contact_person: $('#supplier_contact_person').val(),
        phone: $('#supplier_phone').val(),
        email: $('#supplier_email').val(),
        address: $('#supplier_address').val(),
        status: $('#supplier_status').val(),
        csrf_token: window.CSRF_TOKEN
    };
    if (!p.name) { showAlert('Supplier name is required','danger'); return; }
    $.post('api/suppliers.php?action=save', p, function (r) {
        if (r.status !== 'success') { showAlert(r.message,'danger'); return; }
        bootstrap.Modal.getInstance(document.getElementById('supplierModal')).hide();
        loadSuppliers();
        showAlert('Supplier 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);};}
