class FuelManager {
    constructor() {
        this.fuelReferenceData = {
            vehicles: [],
            drivers: [],
            fuel_types: [],
            fuel_vehicle_types: [],
            states: [],
            offices: [],
            companies: [],
            users: [],
            supervisors: [],
            filling_stations: [],
            fuel_cards: []
        };
        this.fuelCanApprove = false;
        this.fuelEntryCache = new Map();
        this.init();
    }

    init() {
        const now = new Date();
        const monthValue = now.toISOString().slice(0, 7);
        const dateValue = now.toISOString().slice(0, 10);
        const timeValue = now.toTimeString().slice(0, 5);

        $('#fuel_month_year').val(monthValue);
        $('#fuel_record_date').val(dateValue);
        $('#fuel_mileage_date').val(dateValue);
        $('#fuel_fueling_time').val(timeValue);
        $('#fuel_mileage_time').val(timeValue);
        $('#fuelFilterMonth').val(monthValue);
        $('#fuel_fueling_status').val('Completed');
        $('#fuel_approval_status').val('Pending');

        this.loadFuelReferenceData().always(() => {
            this.loadFuelPriceCount();
            this.loadFuelEntriesTable();
        });

        this.bindEvents();
    }

    bindEvents() {
        $('#fuel_vehicle_id').on('change', () => this.populateVehicleDetails());
        $('#fuel_state_id, #fuel_type_id, #fuel_record_date').on('change', () => this.lookupLatestFuelPrice());
        $('#fuel_state_id').on('change', () => this.filterFillingStationsByState());
        $('#fuel_card_id').on('change', () => this.autoFillCardBalance());
        $('#btnUseLatestPrice').on('click', () => this.lookupLatestFuelPrice());
        $('#fuel_record_date').on('change', () => this.syncFuelDates());
        $('#fuel_company_id').on('change', () => this.syncCompanyName());
        $('#fuel_filling_station_id').on('change', () => this.syncFillingStationName());

        $('#fuel_purchase_liters, #fuel_dispensed_litres, #fuel_naira_per_liter, #fuel_actual_mileage, #fuel_begin_km, #fuel_end_km, #fuel_monthly_mileage_km').on('input', () => this.recalculateFuelForm());

        $('#saveFuelEntry, #btnOpenFuelFormSaved').on('click', () => this.saveFuelEntry());
        $('#btnOpenFuelForm, #btnResetFuelFormAlt').on('click', () => this.openCreateModal());
        $('#btnRefreshFuelEntries').on('click', () => this.loadFuelEntriesTable());
        $('#fuelFilterVehicle').on('change', () => this.loadFuelEntriesTable());
        $('#fuelFilterVehicleSearch').on('input', () => this.loadFuelEntriesTable());
        let searchTimeout;
        $('#fuelFilterSearch').on('input', () => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => this.loadFuelEntriesTable(), 300);
        });

        $('#fuelEditLiters, #fuelEditRate').on('input', () => this.recalculateEditModal());
        $('#btnSaveFuelEdit').on('click', () => this.saveFuelEditEntry());

        $('#fuelFormModal').on('shown.bs.modal', () => this.resetFuelForm());
        $('#fuelFormModal').on('hide.bs.modal', (e) => {
            if (this._formDirty && !confirm('You have unsaved changes. Discard them?')) {
                e.preventDefault();
            }
        });
        $('#fuelEntryForm').on('change input', () => { this._formDirty = true; });

        $(document).on('click', '.btn-edit-fuel-entry', (event) => {
            const id = $(event.currentTarget).data('id');
            this.openEditModal(id);
        });
        $(document).on('click', '.btn-approve-fuel-entry', (event) => {
            const id = $(event.currentTarget).data('id');
            this.updateFuelApproval(id, 'Approved');
        });
        $(document).on('click', '.btn-reject-fuel-entry', (event) => {
            const id = $(event.currentTarget).data('id');
            this.updateFuelApproval(id, 'Rejected');
        });
        $(document).on('click', '.btn-delete-fuel-entry', (event) => {
            const id = $(event.currentTarget).data('id');
            this.deleteFuelEntry(id);
        });
        $('#btnExportFuelCsv, #btnExportFuelXlsx, #btnExportFuelPdf').on('click', (event) => {
            const id = event.currentTarget.id;
            const format = id === 'btnExportFuelCsv' ? 'csv' : id === 'btnExportFuelXlsx' ? 'xlsx' : 'pdf';
            this.exportFuel(format);
        });
    }

    loadFuelReferenceData() {
        return $.get('api/fuel.php', { action: 'reference_data' }, (res) => {
            if (res.status !== 'success') {
                alert(res.message || 'Unable to load fuel reference data');
                return;
            }

            this.fuelReferenceData = res.data || this.fuelReferenceData;
            this.fuelCanApprove = Boolean((res.data || {}).can_approve);
            if (!this.fuelCanApprove) {
                $('#fuel_approval_status option[value="Approved"], #fuel_approval_status option[value="Rejected"]').remove();
            }
            this.populateSelect('#fuel_vehicle_id', this.fuelReferenceData.vehicles || [], 'Select vehicle');
            this.populateSelect('#fuelFilterVehicle', this.fuelReferenceData.vehicles || [], 'All vehicles');
            this.populateSelect('#fuelEditVehicleId', this.fuelReferenceData.vehicles || [], 'Select vehicle');
            this.populateSelect('#fuel_driver_id', this.fuelReferenceData.drivers || [], 'Select driver');
            this.populateSelect('#fuelEditDriverId', this.fuelReferenceData.drivers || [], 'Select driver');
            this.populateSelect('#fuel_type_id', this.fuelReferenceData.fuel_types || [], 'Select fuel type');
            this.populateSelect('#fuelEditFuelTypeId', this.fuelReferenceData.fuel_types || [], 'Select fuel type');
            this.populateSelect('#fuel_state_id', this.fuelReferenceData.states || [], 'Select state');
            this.populateSelect('#fuel_office_id', this.fuelReferenceData.offices || [], 'Select office');
            this.populateSelect('#fuel_company_id', this.fuelReferenceData.companies || [], 'Select company');
            this.populateSelect('#fuel_fleet_supervisor_user_id', this.fuelReferenceData.users || [], 'Select fleet supervisor');
            this.populateSelect('#fuel_approved_by_user_id', this.fuelReferenceData.supervisors || [], 'Select approver');
            this.populateSelect('#fuelEditApprovedBy', this.fuelReferenceData.supervisors || [], 'Select approver');
            this.populateSelect('#fuel_filling_station_id', this.fuelReferenceData.filling_stations || [], 'Select filling station');
            this.filterFillingStationsByState();
            this.populateSelect('#fuel_card_id', this.fuelReferenceData.fuel_cards || [], 'No card used');
            $('#fuelCompanyCount').text((this.fuelReferenceData.companies || []).length);
        }, 'json');
    }

    loadFuelEntriesTable(append = false) {
        if (!append) {
            $('#fuelEntriesTable').html('<tr><td colspan="7" class="text-center py-4"><div class="spinner-border spinner-border-sm me-2" role="status"></div>Loading fuel entries...</td></tr>');
        }

        const params = {
            action: 'fuel_entries',
            vehicle_id: $('#fuelFilterVehicle').val(),
            vehicle_search: $('#fuelFilterVehicleSearch').val(),
            search: $('#fuelFilterSearch').val(),
            start_date: $('#fuelDateFrom').val(),
            end_date: $('#fuelDateTo').val()
        };

        if (append && this._fuelLastDate && this._fuelLastId) {
            params.last_date = this._fuelLastDate;
            params.last_id = this._fuelLastId;
        }

        $.get('api/fuel.php', params, (res) => {
            if (res.status !== 'success') {
                if (!append) $('#fuelEntriesTable').html('<tr><td colspan="7" class="text-center text-danger">Unable to load fuel entries.</td></tr>');
                return;
            }

            const rows = res.data || [];
            let html = append ? '' : '';

            if (!append) {
                this.fuelEntryCache.clear();
                this._fuelLastDate = null;
                this._fuelLastId = null;
                $(document).off('click', '#btnFuelLoadMore');
            }

            if (!rows.length && !append) {
                html = '<tr><td colspan="7" class="text-center text-muted py-4">No fueling vouchers found.</td></tr>';
            } else {
                $.each(rows, (_, row) => {
                    this.fuelEntryCache.set(String(row.id), row);
                    const diff = parseFloat(row.baseline_difference);
                    const baselineClass = diff > 0 ? 'text-danger' : diff < 0 ? 'text-success' : '';
                    html += `
                        <tr>
                            <td>
                                <div class="fw-semibold">${this.escapeHtml(this.formatDate(row.record_date))}</div>
                                <div class="text-muted small" title="${this.escapeHtml(row.voucher_id || '')}">${this.escapeHtml((row.voucher_id || '').substring(0, 18))}</div>
                                <div class="text-muted small">${this.escapeHtml(this.formatTime(row.fueling_time))}</div>
                            </td>
                            <td>
                                <div class="fw-semibold">${this.escapeHtml(row.vehicle_no || row.plate_number || '-')}</div>
                                <div class="text-muted small">${this.escapeHtml(row.driver_name || 'Unassigned')}</div>
                                <div class="text-muted small">${this.escapeHtml(row.vehicle_type_label || row.vehicle_name || '')}</div>
                            </td>
                            <td>
                                <div>${this.escapeHtml(row.fuel_type_name || '-')}</div>
                                <div class="text-muted small">${this.escapeHtml(this.formatNumber(row.quantity_litres || row.fuel_purchase_liters))} L</div>
                                <div class="text-muted small">@ ${this.escapeHtml(this.formatNumber(row.naira_per_liter))}/L</div>
                            </td>
                            <td class="text-end">
                                <div class="fw-semibold">${this.escapeHtml(this.formatCurrency(row.total_amount))}</div>
                                <div class="text-muted small">${this.escapeHtml(this.renderFillingStation(row))}</div>
                                <div class="text-muted small">Card: ${this.escapeHtml(this.formatCurrency(row.card_balance))}</div>
                            </td>
                            <td>
                                <div>${this.escapeHtml(this.formatConsumption(row))}</div>
                                <div class="${baselineClass} fw-semibold small">${this.escapeHtml(this.formatSignedNumber(row.baseline_difference))}</div>
                                <div class="${baselineClass} small">${this.escapeHtml(this.formatPercent(row.over_baseline_rate))}</div>
                            </td>
                            <td>
                                <div>${this.renderApprovalStatus(row.approval_status)}</div>
                                <div class="text-muted small mt-1">${this.escapeHtml(row.fueling_status || '-')}</div>
                                <div class="text-muted small">${this.escapeHtml(row.approved_by_name || '')}</div>
                            </td>
                            <td class="text-end">
                                <div class="d-flex flex-wrap gap-1 justify-content-end">
                                    <button type="button" class="btn btn-sm btn-outline-secondary btn-edit-fuel-entry" title="Edit" data-id="${this.escapeHtml(row.id)}"><i class="bi bi-pencil"></i></button>
                                    <button type="button" class="btn btn-sm btn-outline-danger btn-delete-fuel-entry" title="Delete" data-id="${this.escapeHtml(row.id)}"><i class="bi bi-trash"></i></button>
                                    ${this.buildApprovalButtons(row)}
                                </div>
                            </td>
                        </tr>
                    `;

                    this._fuelLastDate = row.record_date;
                    this._fuelLastId = row.id;
                });
            }

            if (append) {
                $('#fuelEntriesTable').append(html);
            } else {
                $('#fuelEntriesTable').html(html);
            }

            const totalRows = $('#fuelEntriesTable tr').length - ($('#fuelEntriesTable tr td[colspan]').length ? 1 : 0);
            $('#fuelEntryCount').text(totalRows);

            const hasMore = res.has_more;
            let loadMoreHtml = '';
            if (hasMore) {
                loadMoreHtml = '<tr id="fuelLoadMoreRow"><td colspan="7" class="text-center py-2"><button type="button" class="btn btn-sm btn-outline-primary" id="btnFuelLoadMore">Load more</button></td></tr>';
            }
            const existing = $('#fuelLoadMoreRow');
            if (hasMore && !existing.length) {
                $('#fuelEntriesTable').append(loadMoreHtml);
            } else if (!hasMore && existing.length) {
                existing.remove();
            }

            $(document).off('click', '#btnFuelLoadMore').on('click', '#btnFuelLoadMore', () => {
                this.loadFuelEntriesTable(true);
            });

            $('#fuelCurrentMonthLabel').text($('#fuelFilterMonth').val() || 'All Months');
        }, 'json');
    }

    loadFuelPriceCount() {
        $.get('api/fuel.php', { action: 'fuel_price_count' }, (res) => {
            if (res.status !== 'success' || !res.data) {
                $('#fuelPriceCount').text('-');
                return;
            }

            $('#fuelPriceCount').text(res.data.count);
        }, 'json');
    }

    populateVehicleDetails() {
        const vehicleId = $('#fuel_vehicle_id').val();
        const vehicle = (this.fuelReferenceData.vehicles || []).find(item => String(item.id) === String(vehicleId));

        if (!vehicle) {
            $('#fuel_vehicle_type').val('');
            $('#fuel_driver_id').val('');
            $('#fuel_office_id').val('');
            $('#fuel_company_id').val('');
            $('#fuel_company_name').val('');
            $('#fuel_begin_km').val('');
            $('#fuelQuickVehicle').html('Select a vehicle to see details');
            return;
        }

        $('#fuel_vehicle_type').val(vehicle.vehicle_model || vehicle.vehicle_name || vehicle.vehicle_type || '');
        $('#fuel_driver_id').val(vehicle.driver_id || '');
        $('#fuel_office_id').val(vehicle.office_id || '');
        $('#fuel_company_id').val(vehicle.company_id || '');
        $('#fuel_company_name').val(vehicle.company_name || '');
        this.syncCompanyName();

        const lines = [
            vehicle.plate_number ? `<strong>${this.escapeHtml(vehicle.plate_number)}</strong>` : null,
            vehicle.vehicle_model ? this.escapeHtml(vehicle.vehicle_model) : null,
            vehicle.driver_name ? `Driver: ${this.escapeHtml(vehicle.driver_name)}` : null,
            vehicle.office_name ? `Office: ${this.escapeHtml(vehicle.office_name)}` : null,
            vehicle.company_name ? `Company: ${this.escapeHtml(vehicle.company_name)}` : null
        ].filter(Boolean);
        $('#fuelQuickVehicle').html(lines.join('<br>') || 'Select a vehicle to see details');

        this.fetchLastOdometer(vehicleId);
    }

    fetchLastOdometer(vehicleId) {
        if (!vehicleId) {
            $('#fuel_begin_km').val('');
            return;
        }
        $.get('api/fuel.php', { action: 'last_vehicle_fuel_entry', vehicle_id: vehicleId }, (res) => {
            if (res.status === 'success' && res.data) {
                $('#fuel_begin_km').val(res.data.end_km);
            } else {
                $('#fuel_begin_km').val('');
            }
        }, 'json');
    }

    syncFuelDates() {
        const dateValue = $('#fuel_record_date').val();
        $('#fuel_month_year').val(String(dateValue || '').slice(0, 7));
        if (!$('#fuel_mileage_date').val()) {
            $('#fuel_mileage_date').val(dateValue);
        }
        this.lookupLatestFuelPrice();
    }

    lookupLatestFuelPrice() {
        const payload = {
            action: 'price_lookup',
            fuel_type_id: $('#fuel_type_id').val(),
            state_id: $('#fuel_state_id').val(),
            effective_date: $('#fuel_record_date').val()
        };

        if (!payload.fuel_type_id) {
            return;
        }

        $.get('api/fuel.php', payload, (res) => {
            if (res.status !== 'success') {
                return;
            }

            const row = res.data;
            if (!row) {
                $('#fuel_price_history_id').val('');
                $('#fuelQuickPrice').html('No price record found for selected fuel type, state, and date.');
                return;
            }

            $('#fuel_price_history_id').val(row.id || '');
            $('#fuel_naira_per_liter').val(row.price_per_liter || '');
            this.recalculateFuelForm();

            const priceLines = [
                `Rate: ₦${this.escapeHtml(Number(row.price_per_liter || 0).toFixed(2))}/L`,
                row.fuel_type_name ? `Type: ${this.escapeHtml(row.fuel_type_name)}` : null,
                row.state_name ? `State: ${this.escapeHtml(row.state_name)}` : null,
                row.effective_date ? `Effective: ${this.escapeHtml(row.effective_date)}` : null,
                row.vendor_name ? `Vendor: ${this.escapeHtml(row.vendor_name)}` : null
            ].filter(Boolean);
            $('#fuelQuickPrice').html(priceLines.join('<br>'));
        }, 'json');
    }

    recalculateFuelForm() {
        const liters = parseFloat($('#fuel_purchase_liters').val() || '0');
        const dispensedLitres = parseFloat($('#fuel_dispensed_litres').val() || '0');
        const rate = parseFloat($('#fuel_naira_per_liter').val() || '0');
        const actualMileage = parseInt($('#fuel_actual_mileage').val() || '0', 10);
        const beginKm = parseInt($('#fuel_begin_km').val() || '0', 10);
        const endKm = parseInt($('#fuel_end_km').val() || '0', 10);
        let monthlyMileage = parseInt($('#fuel_monthly_mileage_km').val() || '0', 10);

        if (actualMileage > 0) {
            $('#fuel_end_km').val(actualMileage);
            if (monthlyMileage > 0) {
                $('#fuel_begin_km').val(Math.max(0, actualMileage - monthlyMileage));
            }
        }

        const normalizedBeginKm = parseInt($('#fuel_begin_km').val() || '0', 10);
        const normalizedEndKm = parseInt($('#fuel_end_km').val() || '0', 10);

        if ((!monthlyMileage || monthlyMileage < 0) && normalizedEndKm && normalizedEndKm >= normalizedBeginKm) {
            monthlyMileage = normalizedEndKm - normalizedBeginKm;
            $('#fuel_monthly_mileage_km').val(monthlyMileage);
        }

        const totalAmount = liters > 0 && rate > 0 ? (liters * rate).toFixed(2) : '';
        $('#fuel_total_amount').val(totalAmount);
        $('#fuel_total_consumption').val((dispensedLitres || liters) ? (dispensedLitres || liters).toFixed(2) : '');

        const vehicleId = $('#fuel_vehicle_id').val();
        const vehicle = (this.fuelReferenceData.vehicles || []).find(item => String(item.id) === String(vehicleId));

        let baseline = null;
        if (vehicle && vehicle.standard_fuel_consumption_l_per_100km) {
            baseline = parseFloat(vehicle.standard_fuel_consumption_l_per_100km);
        }

        let diff = null;
        let ratePct = null;

        if (baseline && monthlyMileage > 0 && (dispensedLitres || liters) > 0) {
            const actualLitres = dispensedLitres || liters;
            const expected = (monthlyMileage * baseline) / 100;
            diff = actualLitres - expected;
            ratePct = expected > 0 ? ((diff / expected) * 100) : 0;
            $('#fuel_baseline_difference').val(diff.toFixed(2));
            $('#fuel_over_baseline_rate').val(ratePct.toFixed(2) + '%');
        } else {
            $('#fuel_baseline_difference').val('');
            $('#fuel_over_baseline_rate').val('');
        }

        $('#fuelQuickTotal').text(totalAmount ? this.formatCurrency(totalAmount) : '—');
        $('#fuelQuickConsumption').text((dispensedLitres || liters) ? (dispensedLitres || liters).toFixed(2) : '—');

        if (diff !== null && ratePct !== null) {
            $('#fuelQuickDiff').text(this.formatSignedNumber(diff));
            $('#fuelQuickOverRate').text(this.formatPercent(ratePct));
        } else {
            $('#fuelQuickDiff').text('—');
            $('#fuelQuickOverRate').text('—');
        }
    }

    openCreateModal() {
        const modal = new bootstrap.Modal(document.getElementById('fuelFormModal'));
        modal.show();
        const vehicleId = $('#fuel_vehicle_id').val();
        if (vehicleId) {
            this.fetchLastOdometer(vehicleId);
        }
    }

    openEditModal(id) {
        const cached = this.fuelEntryCache.get(String(id));
        if (cached) {
            this.populateEditModal(cached);
            const modal = new bootstrap.Modal(document.getElementById('fuelEntryModal'));
            modal.show();
            return;
        }

        $.get('api/fuel.php', { action: 'fuel_entry', id: id }, (res) => {
            if (res.status !== 'success' || !res.data) {
                alert('Fuel entry not found. It may have been deleted.');
                return;
            }
            this.fuelEntryCache.set(String(id), res.data);
            this.populateEditModal(res.data);
            const modal = new bootstrap.Modal(document.getElementById('fuelEntryModal'));
            modal.show();
        }, 'json');
    }

    populateEditModal(record) {
        $('#fuelEditEntryId').val(record.id || '');
        $('#fuelEditVehicleId').val(record.vehicle_id || '');
        $('#fuelEditDriverId').val(record.driver_id || '');
        $('#fuelEditRecordDate').val(this.normalizeDateInput(record.record_date));
        $('#fuelEditFuelTypeId').val(record.fuel_type_id || '');
        $('#fuelEditFuelingType').val(record.fueling_type || '');
        $('#fuelEditFuelingStatus').val(record.fueling_status || 'Completed');
        $('#fuelEditLiters').val(record.quantity_litres || record.fuel_purchase_liters || '');
        $('#fuelEditRate').val(record.naira_per_liter || '');
        $('#fuelEditActualMileage').val(record.actual_mileage || record.end_km || '');
        $('#fuelEditBeginKm').val(record.begin_km || '');
        $('#fuelEditEndKm').val(record.end_km || '');
        $('#fuelEditCardBalance').val(record.card_balance || '');
        $('#fuelEditTotalAmount').val(record.total_amount || '');
        $('#fuelEditApprovalStatus').val(record.approval_status || 'Pending');
        $('#fuelEditApprovedBy').val(record.approved_by_user_id || '');
        $('#fuelEditNotes').val(record.comment_text || record.notes || '');
    }

    saveFuelEditEntry() {
        if (this._submittingEdit) return;
        if (!this.validateFuelForm(true)) return;
        const id = $('#fuelEditEntryId').val();
        const cached = this.fuelEntryCache.get(String(id)) || {};

        const payload = {
            id: id,
            voucher_id: cached.voucher_id || '',
            record_date: $('#fuelEditRecordDate').val(),
            fueling_time: cached.fueling_time || '',
            fueling_type: $('#fuelEditFuelingType').val() || cached.fueling_type || '',
            fueling_status: $('#fuelEditFuelingStatus').val() || cached.fueling_status || 'Completed',
            approval_status: $('#fuelEditApprovalStatus').val(),
            approved_by_user_id: $('#fuelEditApprovedBy').val() || cached.approved_by_user_id || '',
            vehicle_id: $('#fuelEditVehicleId').val(),
            driver_id: $('#fuelEditDriverId').val(),
            fuel_type_id: $('#fuelEditFuelTypeId').val(),
            fuel_level: cached.fuel_level || '',
            quantity_litres: $('#fuelEditLiters').val(),
            dispensed_litres: cached.dispensed_litres || '',
            filling_station_id: cached.filling_station_id || '',
            filling_station: cached.filling_station || '',
            state_id: cached.state_id || '',
            price_history_id: cached.price_history_id || '',
            naira_per_liter: $('#fuelEditRate').val(),
            actual_mileage: $('#fuelEditActualMileage').val(),
            mileage_km: cached.mileage_km || cached.monthly_mileage_km || '',
            mileage_date: cached.mileage_date || cached.record_date || '',
            mileage_time: cached.mileage_time || '',
            begin_km: $('#fuelEditBeginKm').val() || cached.begin_km || '',
            end_km: $('#fuelEditEndKm').val() || cached.end_km || '',
            card_balance: $('#fuelEditCardBalance').val() || cached.card_balance || '',
            notes: $('#fuelEditNotes').val(),
            comment_text: $('#fuelEditNotes').val(),
            office_id: cached.office_id || '',
            company_id: cached.company_id || '',
            company_name: cached.company_name || '',
            fleet_supervisor_user_id: cached.fleet_supervisor_user_id || '',
            driver_name: cached.driver_name || '',
            vehicle_type_label: cached.vehicle_type_label || '',
            monthly_mileage_km: cached.monthly_mileage_km || ''
        };

        if (!payload.record_date || !payload.vehicle_id) {
            alert('Fueling date and vehicle are required');
            return;
        }

        this._submittingEdit = true;
        $('#btnSaveFuelEdit').prop('disabled', true);

        $.ajax({
            url: 'api/fuel.php?action=save_fuel_entry',
            method: 'POST',
            dataType: 'json',
            data: payload,
            success: (res) => {
                this._submittingEdit = false;
                $('#btnSaveFuelEdit').prop('disabled', false);
                if (res.status !== 'success') {
                    alert(res.message || 'Unable to save fuel entry');
                    return;
                }
                const modal = bootstrap.Modal.getInstance(document.getElementById('fuelEntryModal'));
                if (modal) modal.hide();
                this.showFuelAlert('Fuel entry updated successfully.');
                this.loadFuelEntriesTable();
            },
            error: () => {
                this._submittingEdit = false;
                $('#btnSaveFuelEdit').prop('disabled', false);
                alert('Server error while saving fuel entry');
            }
        });
    }

    recalculateEditModal() {
        const liters = parseFloat($('#fuelEditLiters').val() || '0');
        const rate = parseFloat($('#fuelEditRate').val() || '0');
        const total = liters > 0 && rate > 0 ? (liters * rate).toFixed(2) : '';
        $('#fuelEditTotalAmount').val(total);
    }

    validateFuelForm(isEdit = false) {
        const prefix = isEdit ? 'fuelEdit' : 'fuel_';
        const fields = {
            'Quantity (Litres)': $(`#${prefix === 'fuelEdit' ? 'fuelEditLiters' : 'fuel_purchase_liters'}`).val(),
            'Naira / Liter': $(`#${isEdit ? 'fuelEditRate' : 'fuel_naira_per_liter'}`).val(),
            'Actual Mileage': $(`#${isEdit ? 'fuelEditActualMileage' : 'fuel_actual_mileage'}`).val()
        };

        if (!isEdit) {
            fields['Monthly Mileage'] = $('#fuel_monthly_mileage_km').val();
            fields['Begin KM'] = $('#fuel_begin_km').val();
            fields['End KM'] = $('#fuel_end_km').val();
        } else {
            fields['Begin KM'] = $('#fuelEditBeginKm').val();
            fields['End KM'] = $('#fuelEditEndKm').val();
        }

        for (const [label, value] of Object.entries(fields)) {
            const num = parseFloat(value);
            if (value !== '' && value !== null && !isNaN(num) && num < 0) {
                alert(`${label} cannot be negative`);
                return false;
            }
        }
        return true;
    }

    saveFuelEntry() {
        if (this._submitting) return;
        if (!this.validateFuelForm()) return;
        const payload = {
            id: $('#fuel_entry_id').val(),
            voucher_id: $('#fuel_voucher_id').val(),
            record_date: $('#fuel_record_date').val(),
            fueling_time: $('#fuel_fueling_time').val(),
            fueling_type: $('#fuel_fueling_type').val(),
            fueling_status: $('#fuel_fueling_status').val(),
            approval_status: $('#fuel_approval_status').val(),
            approved_by_user_id: $('#fuel_approved_by_user_id').val(),
            vehicle_id: $('#fuel_vehicle_id').val(),
            driver_id: $('#fuel_driver_id').val(),
            driver_name: $('#fuel_driver_id option:selected').text() === 'Select driver' ? '' : $('#fuel_driver_id option:selected').text(),
            office_id: $('#fuel_office_id').val(),
            office_name: $('#fuel_office_id option:selected').text() === 'Select office' ? '' : $('#fuel_office_id option:selected').text(),
            company_id: $('#fuel_company_id').val(),
            company_name: $('#fuel_company_name').val().trim(),
            fleet_supervisor_user_id: $('#fuel_fleet_supervisor_user_id').val(),
            fleet_supervisor_name: $('#fuel_fleet_supervisor_user_id option:selected').text() === 'Select fleet supervisor' ? '' : $('#fuel_fleet_supervisor_user_id option:selected').text(),
            vehicle_type_setup_id: '',
            vehicle_type_label: $('#fuel_vehicle_type').val().trim(),
            fuel_type_id: $('#fuel_type_id').val(),
            fuel_level: $('#fuel_fuel_level').val(),
            quantity_litres: $('#fuel_purchase_liters').val(),
            dispensed_litres: $('#fuel_dispensed_litres').val(),
            filling_station_id: $('#fuel_filling_station_id').val(),
            filling_station: $('#fuel_filling_station_id option:selected').text() === 'Select filling station' ? '' : $('#fuel_filling_station_id option:selected').text(),
            state_id: $('#fuel_state_id').val(),
            price_history_id: $('#fuel_price_history_id').val(),
            naira_per_liter: $('#fuel_naira_per_liter').val(),
            actual_mileage: $('#fuel_actual_mileage').val(),
            mileage_km: $('#fuel_monthly_mileage_km').val(),
            mileage_date: $('#fuel_mileage_date').val(),
            mileage_time: $('#fuel_mileage_time').val(),
            begin_km: $('#fuel_begin_km').val(),
            end_km: $('#fuel_end_km').val(),
            fuel_card_id: $('#fuel_card_id').val(),
            card_balance: $('#fuel_card_balance').val(),
            comment_text: $('#fuel_notes').val().trim(),
            notes: $('#fuel_notes').val().trim()
        };

        if (!payload.record_date || !payload.vehicle_id) {
            alert('Fueling date and vehicle are required');
            return;
        }

        this._submitting = true;
        $('#saveFuelEntry, #btnOpenFuelFormSaved').prop('disabled', true);

        $.ajax({
            url: 'api/fuel.php?action=save_fuel_entry',
            method: 'POST',
            dataType: 'json',
            data: payload,
            success: (res) => {
                this._submitting = false;
                $('#saveFuelEntry, #btnOpenFuelFormSaved').prop('disabled', false);
                if (res.status !== 'success') {
                    alert(res.message || 'Unable to save fuel entry');
                    return;
                }

                this._formDirty = false;
                this.showFuelAlert('Fuel entry created successfully.');
                this.resetFuelForm();
                const formModal = bootstrap.Modal.getInstance(document.getElementById('fuelFormModal'));
                if (formModal) formModal.hide();
                this.loadFuelReferenceData().always(() => {
                    this.loadFuelEntriesTable();
                });
            },
            error: () => {
                this._submitting = false;
                $('#saveFuelEntry, #btnOpenFuelFormSaved').prop('disabled', false);
                alert('Server error while saving fuel entry');
            }
        });
    }

    populateFuelEntryForm(record) {
        $('#fuel_entry_id').val(record.id || '');
        $('#fuel_voucher_id').val(record.voucher_id || '');
        $('#fuel_record_date').val(this.normalizeDateInput(record.record_date));
        $('#fuel_fueling_time').val(this.normalizeTimeInput(record.fueling_time));
        $('#fuel_month_year').val(record.month_year || '');
        $('#fuel_created_at').val(this.formatDateTime(record.created_at));
        $('#fuel_updated_at').val(this.formatDateTime(record.updated_at));
        $('#fuel_approval_status').val(record.approval_status || 'Pending');
        $('#fuel_approved_by_user_id').val(record.approved_by_user_id || '');
        $('#fuel_vehicle_id').val(record.vehicle_id || '');
        this.populateVehicleDetails();

        $('#fuel_driver_id').val(record.driver_id || '');
        if (!record.driver_id && record.driver_name) {
            const matchedDriver = this.findOptionByText(this.fuelReferenceData.drivers || [], record.driver_name);
            $('#fuel_driver_id').val(matchedDriver ? String(matchedDriver.id) : '');
        }
        $('#fuel_vehicle_type').val(record.vehicle_type_label || record.vehicle_name || '');
        $('#fuel_type_id').val(record.fuel_type_id || '');
        $('#fuel_fueling_type').val(record.fueling_type || '');
        $('#fuel_fueling_status').val(record.fueling_status || 'Completed');
        $('#fuel_fuel_level').val(record.fuel_level || '');
        $('#fuel_office_id').val(record.office_id || '');
        $('#fuel_company_id').val(record.company_id || '');
        $('#fuel_company_name').val(record.company_name || '');
        $('#fuel_fleet_supervisor_user_id').val(record.fleet_supervisor_user_id || '');
        $('#fuel_state_id').val(record.state_id || '');
        this.filterFillingStationsByState();
        $('#fuel_price_history_id').val(record.price_history_id || '');
        $('#fuel_purchase_liters').val(record.quantity_litres || record.fuel_purchase_liters || '');
        $('#fuel_dispensed_litres').val(record.dispensed_litres || record.total_fuel_consumption_ltr_month || '');
        $('#fuel_filling_station_id').val(record.filling_station_id || '');
        $('#fuel_filling_station').val(record.filling_station_name || record.filling_station || '');
        $('#fuel_naira_per_liter').val(record.naira_per_liter || '');
        $('#fuel_actual_mileage').val(record.actual_mileage || record.end_km || '');
        $('#fuel_mileage_date').val(this.normalizeDateInput(record.mileage_date || record.record_date));
        $('#fuel_mileage_time').val(this.normalizeTimeInput(record.mileage_time));
        $('#fuel_begin_km').val(record.begin_km || '');
        $('#fuel_end_km').val(record.end_km || '');
        $('#fuel_monthly_mileage_km').val(record.mileage_km || record.monthly_mileage_km || '');
        $('#fuel_total_amount').val(record.total_amount || '');
        $('#fuel_total_consumption').val(record.dispensed_litres || record.total_fuel_consumption_ltr_month || '');
        $('#fuel_baseline_difference').val(record.baseline_difference || '');
        $('#fuel_over_baseline_rate').val(record.over_baseline_rate ? record.over_baseline_rate + '%' : '');
        $('#fuel_card_id').val(record.fuel_card_id || '');
        $('#fuel_card_balance').val(record.card_balance || '');
        $('#fuel_notes').val(record.comment_text || record.notes || '');
    }

    resetFuelForm() {
        this._formDirty = false;
        const today = new Date();
        const dateValue = today.toISOString().slice(0, 10);
        const monthValue = today.toISOString().slice(0, 7);
        const timeValue = today.toTimeString().slice(0, 5);
        $('#fuelEntryForm')[0].reset();
        $('#fuel_entry_id').val('');
        $('#fuel_voucher_id').val('');
        $('#fuel_price_history_id').val('');
        $('#fuel_record_date').val(dateValue);
        $('#fuel_month_year').val(monthValue);
        $('#fuel_mileage_date').val(dateValue);
        $('#fuel_fueling_time').val(timeValue);
        $('#fuel_mileage_time').val(timeValue);
        $('#fuel_created_at').val('');
        $('#fuel_updated_at').val('');
        $('#fuel_approval_status').val('Pending');
        $('#fuel_fueling_status').val('Completed');
        $('#fuel_total_amount').val('');
        $('#fuel_total_consumption').val('');
        $('#fuel_baseline_difference').val('');
        $('#fuel_over_baseline_rate').val('');

        $('#fuelQuickTotal').text('—');
        $('#fuelQuickConsumption').text('—');
        $('#fuelQuickDiff').text('—');
        $('#fuelQuickOverRate').text('—');
        $('#fuelQuickVehicle').html('Select a vehicle to see details');
        $('#fuelQuickPrice').html('Select fuel type, state, and date then click "Lookup Price"');
    }

    autoFillCardBalance() {
        var cardId = $('#fuel_card_id').val();
        if (!cardId) { $('#fuel_card_balance').val(''); return; }
        var cards = this.fuelReferenceData.fuel_cards || [];
        var match = cards.find(function (c) { return String(c.id) === String(cardId); });
        if (match) $('#fuel_card_balance').val(match.current_balance || 0);
    }

    filterFillingStationsByState() {
        const selectedStateId = $('#fuel_state_id').val();
        const allRows = this.fuelReferenceData.filling_stations || [];
        let rows = allRows;

        if (selectedStateId) {
            rows = allRows.filter(row => !row.state_id || String(row.state_id) === String(selectedStateId));
            if (!rows.length) {
                rows = allRows;
            }
        }

        this.populateSelect('#fuel_filling_station_id', rows, 'Select filling station');
        this.syncFillingStationName();
    }

    syncCompanyName() {
        const text = $('#fuel_company_id option:selected').text();
        $('#fuel_company_name').val(text === 'Select company' ? '' : text);
    }

    syncFillingStationName() {
        const text = $('#fuel_filling_station_id option:selected').text();
        $('#fuel_filling_station').val(text === 'Select filling station' ? '' : text);
    }

    renderFillingStation(row) {
        if (row.filling_station_name || row.filling_station) return this.escapeHtml(row.filling_station_name || row.filling_station);
        if (row.state_name) return this.escapeHtml(row.state_name);
        return '';
    }

    formatConsumption(row) {
        const val = row.dispensed_litres || row.total_fuel_consumption_ltr_month || row.quantity_litres || row.fuel_purchase_liters;
        if (!val) return '-';
        return this.formatNumber(val) + ' L';
    }

    buildFuelInfo(row) {
        const parts = [
            row.state_name,
            row.filling_station_name || row.filling_station,
            row.quantity_litres || row.fuel_purchase_liters ? this.formatNumber(row.quantity_litres || row.fuel_purchase_liters) + ' Ltr' : null
        ].filter(Boolean);
        return parts.join(' | ') || '-';
    }

    formatMileageSummary(row) {
        const parts = [];
        if (row.actual_mileage) parts.push('Actual: ' + row.actual_mileage);
        if (row.mileage_km || row.monthly_mileage_km) parts.push('Km: ' + (row.mileage_km || row.monthly_mileage_km));
        if (row.begin_km || row.end_km) parts.push('Range: ' + (row.begin_km || '-') + ' - ' + (row.end_km || '-'));
        return parts.join(' | ') || '-';
    }

    renderApprovalStatus(status) {
        const normalized = String(status || 'Pending').toLowerCase();

        if (normalized === 'approved') return '<span class="badge bg-success">Approved</span>';
        if (normalized === 'rejected') return '<span class="badge bg-danger">Rejected</span>';
        return '<span class="badge bg-warning text-dark">Pending</span>';
    }

    buildApprovalButtons(row) {
        if (!this.fuelCanApprove || String(row.approval_status || '').toLowerCase() === 'approved') {
            return '';
        }

        return `
            <button type="button" class="btn btn-sm btn-outline-success btn-approve-fuel-entry" title="Approve" data-id="${row.id}"><i class="bi bi-check-lg"></i></button>
            <button type="button" class="btn btn-sm btn-outline-danger btn-reject-fuel-entry" title="Reject" data-id="${row.id}"><i class="bi bi-x-lg"></i></button>
        `;
    }

    updateFuelApproval(id, approvalStatus) {
        if (!id) {
            return;
        }

        if (!confirm(`Are you sure you want to ${approvalStatus.toLowerCase()} this fuel request?`)) {
            return;
        }

        $.ajax({
            url: 'api/fuel.php?action=approve_fuel_request',
            method: 'POST',
            dataType: 'json',
            data: {
                id: id,
                approval_status: approvalStatus
            },
            success: (res) => {
                if (res.status !== 'success') {
                    alert(res.message || 'Unable to update fuel approval');
                    return;
                }

                this.showFuelAlert('Fuel request ' + approvalStatus.toLowerCase() + ' successfully.');
                this.loadFuelEntriesTable();
            },
            error: () => {
                alert('Server error while updating fuel approval');
            }
        });
    }

    showFuelAlert(message, type = 'success') {
        const box = $('#fuelAlertBox');
        box.removeClass('d-none alert-success alert-danger alert-warning')
            .addClass('alert-' + type)
            .html(message)
            .show();
        clearTimeout(this._alertTimeout);
        this._alertTimeout = setTimeout(() => box.addClass('d-none'), 4000);
    }

    deleteFuelEntry(id) {
        if (!id) return;
        if (!confirm('Are you sure you want to delete this fuel entry? This action cannot be undone.')) return;

        $.ajax({
            url: 'api/fuel.php?action=delete_fuel_entry',
            method: 'POST',
            dataType: 'json',
            data: { id: id },
            success: (res) => {
                if (res.status !== 'success') {
                    alert(res.message || 'Unable to delete fuel entry');
                    return;
                }
                this.showFuelAlert('Fuel entry deleted successfully.');
                this.loadFuelEntriesTable();
            },
            error: () => {
                alert('Server error while deleting fuel entry');
            }
        });
    }

    exportFuel(format) {
        const params = {
            type: 'fuel',
            format: format,
            vehicle_id: $('#fuelFilterVehicle').val(),
            search: $('#fuelFilterSearch').val(),
            vehicle_search: $('#fuelFilterVehicleSearch').val(),
            approval_status: '',
            start_date: $('#fuelDateFrom').val(),
            end_date: $('#fuelDateTo').val()
        };
        var qs = Object.keys(params).map(function(k) { return encodeURIComponent(k)+'='+encodeURIComponent(params[k]); }).join('&');
        window.open('api/data_export.php?' + qs, '_blank');
    }

    findOptionByText(rows, text) {
        if (!text) {
            return null;
        }
        return (rows || []).find(row => String(row.label || row.name || '').toLowerCase() === String(text).toLowerCase()) || null;
    }

    populateSelect(selector, rows, placeholder) {
        const currentValue = $(selector).val();
        let html = `<option value="">${this.escapeHtml(placeholder)}</option>`;

        $.each(rows, (_, row) => {
            html += `<option value="${this.escapeHtml(row.id)}">${this.escapeHtml(row.label || row.name || '-')}</option>`;
        });

        $(selector).html(html);
        if (currentValue) {
            $(selector).val(String(currentValue));
        }
    }

    formatDate(value) {
        if (!value) return '-';
        const date = new Date(value);
        if (Number.isNaN(date.getTime())) return value;
        return date.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
    }

    formatTime(value) {
        if (!value) return '-';
        return String(value).slice(0, 5);
    }

    formatDateTime(value) {
        if (!value) return '';
        const normalized = String(value).replace(' ', 'T');
        const date = new Date(normalized);
        if (Number.isNaN(date.getTime())) return value;
        return date.toLocaleString();
    }

    formatCurrency(value) {
        if (value === null || value === undefined || value === '') return '-';
        return Number(value).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }

    formatNumber(value) {
        if (value === null || value === undefined || value === '') return '-';
        return Number(value).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }

    formatSignedNumber(value) {
        if (value === null || value === undefined || value === '') return '-';
        const number = Number(value);
        return (number > 0 ? '+' : '') + number.toFixed(2);
    }

    formatPercent(value) {
        if (value === null || value === undefined || value === '') return '-';
        return Number(value).toFixed(2) + '%';
    }

    normalizeDateInput(value) {
        if (!value) return '';
        return String(value).slice(0, 10);
    }

    normalizeTimeInput(value) {
        if (!value) return '';
        return String(value).slice(0, 5);
    }

    safeJson(value) {
        return this.escapeHtml(JSON.stringify(value));
    }

    escapeHtml(text) {
        return $('<div>').text(text || '').html();
    }
}

$(function () {
    new FuelManager();
});


