let _partCache = [];

$(function () {
    loadParts(); loadPartCategories(); loadSuppliersList(); loadCatalogList(); loadBinLocationsList();
    $('#partCategoryFilter, #partLowStockFilter').on('change', loadParts);
    $('#partSearch').on('input', debounce(loadParts, 300));
    $('#btnRefreshParts').on('click', loadParts);
    $('#btnAddPart').on('click', function () { clearPartForm(); new bootstrap.Modal(document.getElementById('partModal')).show(); });
    $('#savePart').on('click', savePart);
    $(document).on('click', '.btn-edit-part', function () { var r = _partCache.find(x => String(x.id) === String($(this).data('id'))); if (r) populatePartForm(r); });
    $(document).on('click', '.btn-delete-part', function () { if (!confirm('Delete part?')) return; $.post('api/parts.php?action=delete', { id: $(this).data('id'), csrf_token: window.CSRF_TOKEN }, function (r) { if (r.status==='success') { loadParts(); showToast('Deleted','success'); } else showToast(r.message,'danger'); }, 'json'); });
    $(document).on('click', '.btn-transaction-part', function () { $('#trans_part_id').val($(this).data('id')); $('#transPartName').text($(this).data('name')); new bootstrap.Modal(document.getElementById('transactionModal')).show(); });
    $('#saveTransaction').on('click', saveTransaction);
    $('#part_catalog_id').on('change', function () {
        var id = $(this).val();
        if (!id) return;
        var c = _catalogCache.find(x => String(x.id) === String(id));
        if (!c) return;
        if (!$('#part_name').val()) $('#part_name').val(c.name);
        if (!$('#part_part_number').val()) $('#part_part_number').val(c.part_number||'');
        if (c.category_id) $('#part_category_id').val(c.category_id);
        if (c.unit_of_measure) $('#part_unit_of_measure').val(c.unit_of_measure);
        if (c.default_unit_cost && !$('#part_unit_cost').val()) $('#part_unit_cost').val(c.default_unit_cost);
        if (c.default_reorder_level && !$('#part_reorder_level').val()) $('#part_reorder_level').val(c.default_reorder_level);
    });
    $('#part_supplier_id').on('change', function () {
        var id = $(this).val(), s = _supplierCache.find(x => String(x.id) === String(id));
        if (s && !$('#part_supplier_name').val()) $('#part_supplier_name').val(s.name);
    });
    $('#part_bin_location_id').on('change', function () {
        var id = $(this).val(), b = _binLocationCache.find(x => String(x.id) === String(id));
        if (b && !$('#part_bin_location').val()) $('#part_bin_location').val(b.name);
    });
    $('#btnExportPartsCsv').on('click', function () { window.location.href = 'api/data_export.php?type=parts&format=csv'; });
    $('#btnExportPartsXlsx').on('click', function () { window.location.href = 'api/data_export.php?type=parts&format=xlsx'; });
    $('#btnExportPartsPdf').on('click', function () { window.location.href = 'api/data_export.php?type=parts&format=pdf'; });
});

var _supplierCache = [], _catalogCache = [], _binLocationCache = [];

function loadSuppliersList() {
    $.get('api/parts.php', { action: 'suppliers' }, function (r) {
        if (r.status!=='success') return;
        _supplierCache = r.data||[];
        var h = '<option value="">Select supplier</option>';
        (r.data||[]).forEach(function(x){ h+='<option value="'+x.id+'">'+escapeHtml(x.name)+'</option>'; });
        $('#part_supplier_id').html(h);
    },'json');
}

function loadCatalogList() {
    $.get('api/parts.php', { action: 'catalog' }, function (r) {
        if (r.status!=='success') return;
        _catalogCache = r.data||[];
        var h = '<option value="">-- Select from catalog --</option>';
        (r.data||[]).forEach(function(x){ h+='<option value="'+x.id+'">'+escapeHtml(x.name)+' ('+escapeHtml(x.part_number||'no#')+')</option>'; });
        $('#part_catalog_id').html(h);
    },'json');
}

function loadBinLocationsList() {
    $.get('api/parts.php', { action: 'bin_locations' }, function (r) {
        if (r.status!=='success') return;
        _binLocationCache = r.data||[];
        var h = '<option value="">Select bin location</option>';
        (r.data||[]).forEach(function(x){ h+='<option value="'+x.id+'">'+escapeHtml(x.name)+'</option>'; });
        $('#part_bin_location_id').html(h);
    },'json');
}

function loadPartCategories() {
    $.get('api/parts.php', { action: 'categories' }, function (r) {
        if (r.status!=='success') return;
        populateSelect('#partCategoryFilter', r.data, 'All');
        populateSelect('#part_category_id', r.data, 'Select category');
    },'json');
}

function loadParts() {
    $.get('api/parts.php', {
        action: 'list', search: $('#partSearch').val(), category_id: $('#partCategoryFilter').val(),
        low_stock: $('#partLowStockFilter').val()
    }, function (res) {
        if (res.status!=='success') return;
        var rows = res.data||[]; _partCache = rows;
        var totalVal = 0, lowStock = 0;
        rows.forEach(function(r){ totalVal += (r.quantity_in_stock||0)*(r.unit_cost||0); if (r.reorder_level !== null && r.quantity_in_stock <= r.reorder_level) lowStock++; });
        $('#kpiTotalParts').text(rows.length);
        $('#kpiLowStock').text(lowStock);
        $('#kpiStockValue').text('₦' + totalVal.toLocaleString());

        var html = '';
        if (!rows.length) html = '<tr><td colspan="10" class="text-center py-4 text-muted">No parts</td></tr>';
        else rows.forEach(function(r){
            var isLow = r.reorder_level !== null && r.quantity_in_stock <= r.reorder_level;
            var stockClass = isLow ? 'text-danger fw-bold' : '';
            html += '<tr><td class="fw-semibold">' + escapeHtml(r.name) + '</td><td>' + escapeHtml(r.part_number||'-') + '</td><td>' + escapeHtml(r.category_name||'-') + '</td>' +
                '<td class="' + stockClass + '">' + Number(r.quantity_in_stock).toLocaleString() + ' ' + escapeHtml(r.unit_of_measure) + '</td><td>' + (r.reorder_level!==null?Number(r.reorder_level).toLocaleString():'-') + '</td>' +
                '<td>₦' + Number(r.unit_cost||0).toLocaleString() + '</td><td>' + escapeHtml(r.supplier_name||'-') + '</td><td>' + escapeHtml(r.bin_location_name||'-') + '</td>' +
                '<td>' + (r.is_active ? '<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-info btn-transaction-part" data-id="' + r.id + '" data-name="' + escapeHtml(r.name) + '"><i class="bi bi-arrow-left-right"></i></button>' +
                '<button class="btn btn-sm btn-outline-primary btn-edit-part" data-id="' + r.id + '"><i class="bi bi-pencil"></i></button>' +
                '<button class="btn btn-sm btn-outline-danger btn-delete-part" data-id="' + r.id + '"><i class="bi bi-trash3"></i></button></div></td></tr>';
        });
        $('#partTable').html(html);
    },'json');
}

function savePart() {
    var p = { id: $('#part_id').val(), name: $('#part_name').val(), part_number: $('#part_part_number').val(), category_id: $('#part_category_id').val(), unit_of_measure: $('#part_unit_of_measure').val(), quantity_in_stock: $('#part_quantity_in_stock').val(), reorder_level: $('#part_reorder_level').val(), unit_cost: $('#part_unit_cost').val(), supplier_id: $('#part_supplier_id').val(), supplier_name: $('#part_supplier_name').val(), catalog_id: $('#part_catalog_id').val(), bin_location_id: $('#part_bin_location_id').val(), bin_location: $('#part_bin_location').val(), description: $('#part_description').val(), csrf_token: window.CSRF_TOKEN };
    if (!p.name) { showToast('Part name required','danger'); return; }
    $.post('api/parts.php?action=save', p, function (r) {
        if (r.status!=='success') { showToast(r.message,'danger'); return; }
        bootstrap.Modal.getInstance(document.getElementById('partModal')).hide(); loadParts(); showToast('Part saved!','success');
    },'json').fail(function(){showToast('Server error','danger');});
}

function saveTransaction() {
    var p = { part_id: $('#trans_part_id').val(), transaction_type: $('#trans_type').val(), quantity: $('#trans_quantity').val(), unit_cost: $('#trans_unit_cost').val(), notes: $('#trans_notes').val(), csrf_token: window.CSRF_TOKEN };
    if (!p.part_id||!p.quantity||p.quantity<=0) { showToast('Part and quantity required','danger'); return; }
    $.post('api/parts.php?action=save_transaction', p, function (r) {
        if (r.status!=='success') { showToast(r.message,'danger'); return; }
        bootstrap.Modal.getInstance(document.getElementById('transactionModal')).hide(); loadParts(); showToast('Transaction recorded!','success');
    },'json').fail(function(){showToast('Server error','danger');});
}

function clearPartForm() { $('#partForm')[0].reset(); $('#part_id').val(''); $('#part_quantity_in_stock').val('0'); $('#part_unit_of_measure').val('piece'); }
function populatePartForm(r) {
    clearPartForm(); $('#part_id').val(r.id); $('#part_name').val(r.name); $('#part_part_number').val(r.part_number||''); $('#part_category_id').val(r.category_id||'');
    $('#part_unit_of_measure').val(r.unit_of_measure||'piece'); $('#part_quantity_in_stock').val(r.quantity_in_stock||0); $('#part_reorder_level').val(r.reorder_level||'');
    $('#part_unit_cost').val(r.unit_cost||''); $('#part_supplier_id').val(r.supplier_id||''); $('#part_supplier_name').val(r.supplier_name||''); $('#part_catalog_id').val(r.catalog_id||''); $('#part_bin_location_id').val(r.bin_location_id||''); $('#part_bin_location').val(r.bin_location||''); $('#part_description').val(r.description||'');
    new bootstrap.Modal(document.getElementById('partModal')).show();
}

function populateSelect(s,rows,p){var h='<option value="">'+escapeHtml(p)+'</option>';(rows||[]).forEach(function(r){h+='<option value="'+escapeHtml(r.id)+'">'+escapeHtml(r.label||r.name||'-')+'</option>';});$(s).html(h);}
function showToast(m,t){var e=document.createElement('div');e.className='position-fixed top-0 end-0 p-3';e.style.zIndex='9999';e.innerHTML='<div class="alert alert-'+t+' alert-dismissible fade show" role="alert">'+escapeHtml(m)+'<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>';document.body.appendChild(e);setTimeout(function(){e.remove()},5000);}
function escapeHtml(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);};}
