let _tyreCache = [], _brandCache = [], _modelCache = [];

$(function () {
    loadTyres(); loadTyreVehicles(); loadTyreBrands();
    $('#tyreSearch').on('input', debounce(loadTyres, 300));
    $('#tyreVehicleFilter, #tyreStatusFilter').on('change', loadTyres);
    $('#btnRefreshTyres').on('click', loadTyres);
    $('#btnAddTyre').on('click', function () { clearTyreForm(); new bootstrap.Modal(document.getElementById('tyreModal')).show(); });
    $('#saveTyre').on('click', saveTyre);
    $(document).on('click', '.btn-edit-tyre', function () { var r = _tyreCache.find(x => String(x.id) === String($(this).data('id'))); if (r) populateTyreForm(r); });
    $(document).on('click', '.btn-delete-tyre', function () { if (!confirm('Delete tyre?')) return; $.post('api/tyres.php?action=delete', { id: $(this).data('id'), csrf_token: window.CSRF_TOKEN }, function (r) { if (r.status==='success') { loadTyres(); showToast('Deleted','success'); } else showToast(r.message,'danger'); }, 'json'); });
    $(document).on('click', '.btn-fit-tyre', function () { fitTyre($(this).data('id')); });
    $(document).on('click', '.btn-remove-tyre', function () { if (!confirm('Remove this tyre from vehicle?')) return; var odo = prompt('Removal odometer (km):'); $.post('api/tyres.php?action=remove', { id: $(this).data('id'), odometer: odo, csrf_token: window.CSRF_TOKEN }, function (r) { if (r.status==='success') { loadTyres(); showToast('Tyre removed','success'); } else showToast(r.message,'danger'); }, 'json'); });
    $(document).on('click', '.btn-scrap-tyre', function () { if (!confirm('Scrap this tyre?')) return; $.post('api/tyres.php?action=scrap', { id: $(this).data('id'), csrf_token: window.CSRF_TOKEN }, function (r) { if (r.status==='success') { loadTyres(); showToast('Tyre scrapped','success'); } else showToast(r.message,'danger'); }, 'json'); });
    $(document).on('click', '.btn-retread-tyre', function () { $('#retread_tyre_id').val($(this).data('id')); $('#retread_date').val(new Date().toISOString().slice(0,10)); new bootstrap.Modal(document.getElementById('retreadModal')).show(); });
    $('#saveRetread').on('click', function () {
        $.post('api/tyres.php?action=save_retread', { tyre_id: $('#retread_tyre_id').val(), retread_date: $('#retread_date').val(), retread_cost: $('#retread_cost').val(), vendor_name: $('#retread_vendor_name').val(), notes: $('#retread_notes').val(), csrf_token: window.CSRF_TOKEN }, function (r) {
            if (r.status==='success') { bootstrap.Modal.getInstance(document.getElementById('retreadModal')).hide(); loadTyres(); showToast('Retread recorded!','success'); } else showToast(r.message,'danger');
        },'json').fail(function(){showToast('Server error','danger');});
    });
    // Brand cascade to models
    $('#tyre_brand_id').on('change', function () {
        var bid = $(this).val();
        loadTyreModels(bid);
        if (!bid) return;
        var b = _brandCache.find(x => String(x.id) === String(bid));
        if (b && !$('#tyre_brand').val()) $('#tyre_brand').val(b.name);
    });
    $('#tyre_model_id').on('change', function () {
        var mid = $(this).val();
        if (!mid) return;
        var m = _modelCache.find(x => String(x.id) === String(mid));
        if (m && !$('#tyre_model').val()) $('#tyre_model').val(m.name);
    });
    $('#btnExportTyresCsv').on('click', function () { window.location.href = 'api/data_export.php?type=tyres&format=csv'; });
    $('#btnExportTyresXlsx').on('click', function () { window.location.href = 'api/data_export.php?type=tyres&format=xlsx'; });
    $('#btnExportTyresPdf').on('click', function () { window.location.href = 'api/data_export.php?type=tyres&format=pdf'; });
});

function loadTyreVehicles() {
    $.get('api/compliance.php', { action: 'vehicles' }, function (r) {
        if (r.status==='success') {
            populateSelect('#tyreVehicleFilter', r.data, 'All');
            populateSelect('#tyre_vehicle_id', [{id:'',label:'Not fitted'}].concat(r.data||[]), '');
        }
    },'json');
}

function loadTyreBrands() {
    $.get('api/tyres.php', { action: 'tyre_brands' }, function (r) {
        if (r.status!=='success') return;
        _brandCache = r.data||[];
        var h = '<option value="">Select brand</option>';
        (r.data||[]).forEach(function(x){ h+='<option value="'+x.id+'">'+escapeHtml(x.name)+'</option>'; });
        $('#tyre_brand_id').html(h);
    },'json');
}

function loadTyreModels(brandId) {
    var params = { action: 'tyre_models' };
    if (brandId) params.brand_id = brandId;
    $.get('api/tyres.php', params, function (r) {
        if (r.status!=='success') return;
        _modelCache = r.data||[];
        var h = '<option value="">Select model</option>';
        (r.data||[]).forEach(function(x){ h+='<option value="'+x.id+'">'+escapeHtml(x.name)+'</option>'; });
        $('#tyre_model_id').html(h);
    },'json');
}

function loadTyres() {
    $.get('api/tyres.php', { action: 'list', search: $('#tyreSearch').val(), vehicle_id: $('#tyreVehicleFilter').val(), status: $('#tyreStatusFilter').val() }, function (res) {
        if (res.status!=='success') return;
        var rows = res.data||[]; _tyreCache = rows;
        var inStock=0, fitted=0, retreaded=0, scrapped=0, totalCost=0;
        rows.forEach(function(r){ if (r.status==='in_stock') inStock++; else if (r.status==='fitted') fitted++; else if (r.status==='retreaded') retreaded++; else if (r.status==='scrapped') scrapped++; totalCost += r.purchase_cost||0; });
        $('#kpiInStock').text(inStock); $('#kpiFitted').text(fitted); $('#kpiRetreaded').text(retreaded); $('#kpiScrapped').text(scrapped); $('#kpiTotalTyres').text(rows.length); $('#kpiTyreCost').text('₦'+totalCost.toLocaleString());

        var html = '';
        if (!rows.length) html = '<tr><td colspan="9" class="text-center py-4 text-muted">No tyres</td></tr>';
        else rows.forEach(function(r){
            var statusBadge = r.status==='in_stock'?'<span class="badge bg-secondary">In Stock</span>':r.status==='fitted'?'<span class="badge bg-success">Fitted</span>':r.status==='retreaded'?'<span class="badge bg-info">Retreaded</span>':'<span class="badge bg-danger">Scrapped</span>';
            var actions = '<div class="d-flex gap-1 justify-content-end">';
            if (r.status==='in_stock') actions += '<button class="btn btn-sm btn-outline-success btn-fit-tyre" data-id="'+r.id+'" title="Fit to vehicle"><i class="bi bi-plus-circle"></i></button>';
            if (r.status==='fitted') actions += '<button class="btn btn-sm btn-outline-warning btn-remove-tyre" data-id="'+r.id+'" title="Remove"><i class="bi bi-dash-circle"></i></button>';
            if (r.status==='fitted'||r.status==='in_stock') actions += '<button class="btn btn-sm btn-outline-info btn-retread-tyre" data-id="'+r.id+'" title="Retread"><i class="bi bi-arrow-repeat"></i></button>';
            actions += '<button class="btn btn-sm btn-outline-danger btn-scrap-tyre" data-id="'+r.id+'" title="Scrap"><i class="bi bi-trash3"></i></button>';
            actions += '<button class="btn btn-sm btn-outline-primary btn-edit-tyre" data-id="'+r.id+'" title="Edit"><i class="bi bi-pencil"></i></button>';
            actions += '<button class="btn btn-sm btn-outline-danger btn-delete-tyre" data-id="'+r.id+'" title="Delete"><i class="bi bi-x-circle"></i></button></div>';
            html += '<tr><td class="fw-semibold">'+escapeHtml(r.brand||'-')+'</td><td>'+escapeHtml(r.size||'-')+'</td><td>'+escapeHtml(r.serial_number||'-')+'</td><td>'+escapeHtml(r.plate_number||'-')+'</td><td>'+escapeHtml(r.position||'-')+'</td><td>'+(r.purchase_date||'-')+'</td><td>'+formatDate(r.fitted_date)+'</td><td>'+statusBadge+'</td><td class="text-end">'+actions+'</td></tr>';
        });
        $('#tyreTable').html(html);
    },'json');
}

function fitTyre(id) {
    $.get('api/compliance.php', { action: 'vehicles' }, function (r) {
        if (r.status!=='success') return;
        var opts = ''; (r.data||[]).forEach(function(v){ opts += '<option value="'+escapeHtml(v.id)+'">'+escapeHtml(v.label||v.name)+'</option>'; });
        var vId = prompt('Enter vehicle ID:\nAvailable:\n'+(r.data||[]).map(function(v){return v.id+': '+v.label;}).join('\n'));
        if (!vId) return;
        var pos = prompt('Position (front_left, front_right, rear_left, rear_right, spare):');
        var odo = prompt('Fitted odometer (km):');
        $.post('api/tyres.php?action=fit', { id: id, vehicle_id: vId, position: pos, odometer: odo, csrf_token: window.CSRF_TOKEN }, function (res) {
            if (res.status==='success') { loadTyres(); showToast('Tyre fitted!','success'); } else showToast(res.message,'danger');
        },'json');
    },'json');
}

function saveTyre() {
    var p = { id: $('#tyre_id').val(), brand_id: $('#tyre_brand_id').val(), model_id: $('#tyre_model_id').val(), brand: $('#tyre_brand').val(), model: $('#tyre_model').val(), size: $('#tyre_size').val(), serial_number: $('#tyre_serial_number').val(), vehicle_id: $('#tyre_vehicle_id').val(), position: $('#tyre_position').val(), purchase_date: $('#tyre_purchase_date').val(), purchase_cost: $('#tyre_purchase_cost').val(), fitted_date: $('#tyre_fitted_date').val(), fitted_odometer: $('#tyre_fitted_odometer').val(), status: $('#tyre_status').val(), notes: $('#tyre_notes').val(), csrf_token: window.CSRF_TOKEN };
    if (!p.brand&&!p.serial_number) { showToast('Brand or serial number required','danger'); return; }
    $.post('api/tyres.php?action=save', p, function (r) {
        if (r.status!=='success') { showToast(r.message,'danger'); return; }
        bootstrap.Modal.getInstance(document.getElementById('tyreModal')).hide(); loadTyres(); showToast('Tyre saved!','success');
    },'json').fail(function(){showToast('Server error','danger');});
}

function clearTyreForm() { $('#tyreForm')[0].reset(); $('#tyre_id').val(''); }
function populateTyreForm(r) {
    clearTyreForm(); $('#tyre_id').val(r.id);
    $('#tyre_brand_id').val(r.brand_id||''); if (r.brand_id) loadTyreModels(r.brand_id);
    $('#tyre_brand').val(r.brand||'');
    $('#tyre_model_id').val(r.model_id||'');
    $('#tyre_model').val(r.model||'');
    $('#tyre_size').val(r.size||'');
    $('#tyre_serial_number').val(r.serial_number||''); $('#tyre_vehicle_id').val(r.vehicle_id||''); $('#tyre_position').val(r.position||'');
    $('#tyre_purchase_date').val(normalizeDate(r.purchase_date)); $('#tyre_purchase_cost').val(r.purchase_cost||'');
    $('#tyre_fitted_date').val(normalizeDate(r.fitted_date)); $('#tyre_fitted_odometer').val(r.fitted_odometer||''); $('#tyre_status').val(r.status||'in_stock');
    $('#tyre_notes').val(r.notes||''); new bootstrap.Modal(document.getElementById('tyreModal')).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||r.plate_number||'-')+'</option>';});$(s).html(h);}
function formatDate(d){if(!d)return'-';var dt=new Date(d);return Number.isNaN(dt.getTime())?d:dt.toLocaleDateString(undefined,{year:'numeric',month:'short',day:'numeric'});}
function normalizeDate(d){return d?String(d).slice(0,10):'';}
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);};}
