let fuelSetupReferenceData = {
    fuel_types: [],
    states: [],
    users: []
};

$(function () {
    const today = new Date().toISOString().slice(0, 10);
    $('#setup_price_effective_date').val(today);

    loadFuelSetupReferenceData().always(function () {
        loadFuelTypesTable();
        loadFuelOfficesTable();
        loadFuelCompaniesTable();
        loadFuelStationsTable();
        loadFuelApprovalUsersTable();
        loadFuelPricesTable();
    });

    $('#saveFuelType').on('click', saveFuelType);
    $('#saveFuelOffice').on('click', saveFuelOffice);
    $('#saveFuelCompany').on('click', saveFuelCompany);
    $('#saveFuelStation').on('click', saveFuelStation);
    $('#saveFuelApprovalUser').on('click', saveFuelApprovalUser);
    $('#saveFuelPrice').on('click', saveFuelPrice);

    $(document).on('click', '.delete-fuel-type', deleteFuelType);
    $(document).on('click', '.delete-fuel-office', deleteFuelOffice);
    $(document).on('click', '.delete-fuel-company', deleteFuelCompany);
    $(document).on('click', '.delete-fuel-station', deleteFuelStation);
    $(document).on('click', '.delete-fuel-approval-user', deleteFuelApprovalUser);
    $(document).on('click', '.delete-fuel-price', deleteFuelPrice);
});

let _setupAlertTimeout;

function showSetupAlert(message, type) {
    const box = $('#fuelSetupAlertBox');
    box.removeClass('d-none alert-success alert-danger alert-warning')
        .addClass('alert-' + (type || 'success'))
        .html(message);
    clearTimeout(_setupAlertTimeout);
    _setupAlertTimeout = setTimeout(function () { box.addClass('d-none'); }, 4000);
}

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

        fuelSetupReferenceData = res.data || fuelSetupReferenceData;
        populateSelect('#setup_price_fuel_type_id', fuelSetupReferenceData.fuel_types || [], 'Select fuel type');
        populateSelect('#setup_price_state_id', fuelSetupReferenceData.states || [], 'Select state');
        populateSelect('#setup_station_state_id', fuelSetupReferenceData.states || [], 'Select state');
        populateSelect('#setup_approval_user_id', fuelSetupReferenceData.users || [], 'Select user');
    }, 'json');
}

function loadFuelTypesTable() {
    $.get('api/fuel.php', { action: 'fuel_types' }, function (res) {
        if (res.status !== 'success') {
            $('#fuelTypeTable').html('<tr><td colspan="4" class="text-center text-danger">Unable to load fuel types.</td></tr>');
            return;
        }

        const rows = res.data || [];
        let html = '';
        if (!rows.length) {
            html = '<tr><td colspan="4" class="text-center text-muted">No fuel types configured.</td></tr>';
        } else {
            $.each(rows, function (_, row) {
                html += `<tr><td>${escapeHtml(row.name || '-')}</td><td>${escapeHtml(row.code || '-')}</td><td>${escapeHtml(row.unit_label || '-')}</td><td><button class="btn btn-outline-danger btn-sm delete-fuel-type" data-id="${escapeHtml(row.id)}"><i class="bi bi-trash"></i></button></td></tr>`;
            });
        }
        $('#fuelTypeTable').html(html);
    }, 'json');
}

function loadFuelCompaniesTable() {
    $.get('api/fuel.php', { action: 'fuel_companies' }, function (res) {
        if (res.status !== 'success') {
            $('#fuelCompanyTable').html('<tr><td colspan="3" class="text-center text-danger">Unable to load companies.</td></tr>');
            return;
        }

        const rows = res.data || [];
        let html = '';
        if (!rows.length) {
            html = '<tr><td colspan="3" class="text-center text-muted">No companies configured.</td></tr>';
        } else {
            $.each(rows, function (_, row) {
                html += `<tr><td>${escapeHtml(row.name || '-')}</td><td>${escapeHtml(row.code || '-')}</td><td><button class="btn btn-outline-danger btn-sm delete-fuel-company" data-id="${escapeHtml(row.id)}"><i class="bi bi-trash"></i></button></td></tr>`;
            });
        }
        $('#fuelCompanyTable').html(html);
    }, 'json');
}

function loadFuelOfficesTable() {
    $.get('api/fuel.php', { action: 'fuel_offices' }, function (res) {
        if (res.status !== 'success') {
            $('#fuelOfficeTable').html('<tr><td colspan="2" class="text-center text-danger">Unable to load offices.</td></tr>');
            return;
        }

        const rows = res.data || [];
        let html = '';
        if (!rows.length) {
            html = '<tr><td colspan="2" class="text-center text-muted">No offices configured.</td></tr>';
        } else {
            $.each(rows, function (_, row) {
                html += `<tr><td>${escapeHtml(row.name || '-')}</td><td><button class="btn btn-outline-danger btn-sm delete-fuel-office" data-id="${escapeHtml(row.id)}"><i class="bi bi-trash"></i></button></td></tr>`;
            });
        }
        $('#fuelOfficeTable').html(html);
    }, 'json');
}

function loadFuelStationsTable() {
    $.get('api/fuel.php', { action: 'fuel_filling_stations' }, function (res) {
        if (res.status !== 'success') {
            $('#fuelStationTable').html('<tr><td colspan="3" class="text-center text-danger">Unable to load filling stations.</td></tr>');
            return;
        }

        const rows = res.data || [];
        let html = '';
        if (!rows.length) {
            html = '<tr><td colspan="3" class="text-center text-muted">No filling stations configured.</td></tr>';
        } else {
            $.each(rows, function (_, row) {
                html += `<tr><td>${escapeHtml(row.name || '-')}</td><td>${escapeHtml(row.state_name || '-')}</td><td><button class="btn btn-outline-danger btn-sm delete-fuel-station" data-id="${escapeHtml(row.id)}"><i class="bi bi-trash"></i></button></td></tr>`;
            });
        }
        $('#fuelStationTable').html(html);
    }, 'json');
}

function loadFuelApprovalUsersTable() {
    $.get('api/fuel.php', { action: 'fuel_approval_users' }, function (res) {
        if (res.status !== 'success') {
            $('#fuelApprovalUserTable').html('<tr><td colspan="3" class="text-center text-danger">Unable to load approval users.</td></tr>');
            return;
        }

        const rows = res.data || [];
        let html = '';
        if (!rows.length) {
            html = '<tr><td colspan="3" class="text-center text-muted">No approval users configured.</td></tr>';
        } else {
            $.each(rows, function (_, row) {
                html += `<tr><td>${escapeHtml(row.user_name || '-')}</td><td>${escapeHtml(row.email || '-')}</td><td><button class="btn btn-outline-danger btn-sm delete-fuel-approval-user" data-id="${escapeHtml(row.id)}"><i class="bi bi-trash"></i></button></td></tr>`;
            });
        }
        $('#fuelApprovalUserTable').html(html);
    }, 'json');
}

function loadFuelPricesTable() {
    $.get('api/fuel.php', { action: 'fuel_prices' }, function (res) {
        if (res.status !== 'success') {
            $('#fuelPriceTable').html('<tr><td colspan="6" class="text-center text-danger">Unable to load fuel prices.</td></tr>');
            return;
        }

        const rows = res.data || [];
        let html = '';
        if (!rows.length) {
            html = '<tr><td colspan="6" class="text-center text-muted">No fuel price history found.</td></tr>';
        } else {
            $.each(rows, function (_, row) {
                html += `
                    <tr>
                        <td>${escapeHtml(formatDate(row.effective_date))}</td>
                        <td>${escapeHtml(row.fuel_type_name || '-')}</td>
                        <td>${escapeHtml(row.state_name || 'National')}</td>
                        <td>${escapeHtml(formatCurrency(row.price_per_liter))}</td>
                        <td>${escapeHtml(row.vendor_name || '-')}</td>
                        <td><button class="btn btn-outline-danger btn-sm delete-fuel-price" data-id="${escapeHtml(row.id)}"><i class="bi bi-trash"></i></button></td>
                    </tr>
                `;
            });
        }
        $('#fuelPriceTable').html(html);
    }, 'json');
}

function saveFuelType() {
    const payload = {
        name: $('#setup_fuel_type_name').val().trim(),
        code: $('#setup_fuel_type_code').val().trim(),
        unit_label: $('#setup_fuel_unit').val().trim()
    };

    if (!payload.name) {
        alert('Fuel type name is required');
        return;
    }

    $.post('api/fuel.php?action=save_fuel_type', payload, function (res) {
        if (res.status !== 'success') {
            alert(res.message || 'Unable to save fuel type');
            return;
        }
        showSetupAlert('Fuel type saved.');
        $('#fuelTypeForm')[0].reset();
        $('#setup_fuel_unit').val('Litre');
        loadFuelSetupReferenceData().always(loadFuelTypesTable);
    }, 'json');
}

function saveFuelCompany() {
    const payload = {
        name: $('#setup_company_name').val().trim(),
        code: $('#setup_company_code').val().trim()
    };

    if (!payload.name) {
        alert('Company name is required');
        return;
    }

    $.post('api/fuel.php?action=save_fuel_company', payload, function (res) {
        if (res.status !== 'success') {
            alert(res.message || 'Unable to save company');
            return;
        }
        showSetupAlert('Company saved.');
        $('#fuelCompanyForm')[0].reset();
        loadFuelCompaniesTable();
        loadFuelSetupReferenceData();
    }, 'json');
}

function saveFuelOffice() {
    const payload = {
        name: $('#setup_office_name').val().trim()
    };

    if (!payload.name) {
        alert('Office name is required');
        return;
    }

    $.post('api/fuel.php?action=save_fuel_office', payload, function (res) {
        if (res.status !== 'success') {
            alert(res.message || 'Unable to save office');
            return;
        }
        showSetupAlert('Office saved.');
        $('#fuelOfficeForm')[0].reset();
        loadFuelOfficesTable();
        loadFuelSetupReferenceData();
    }, 'json');
}

function saveFuelStation() {
    const payload = {
        name: $('#setup_station_name').val().trim(),
        state_id: $('#setup_station_state_id').val(),
        contact_phone: $('#setup_station_phone').val().trim(),
        address: $('#setup_station_address').val().trim()
    };

    if (!payload.name) {
        alert('Filling station name is required');
        return;
    }

    $.post('api/fuel.php?action=save_fuel_filling_station', payload, function (res) {
        if (res.status !== 'success') {
            alert(res.message || 'Unable to save filling station');
            return;
        }
        showSetupAlert('Filling station saved.');
        $('#fuelStationForm')[0].reset();
        loadFuelStationsTable();
        loadFuelSetupReferenceData();
    }, 'json');
}

function saveFuelApprovalUser() {
    const payload = {
        user_id: $('#setup_approval_user_id').val()
    };

    if (!payload.user_id) {
        alert('User is required');
        return;
    }

    $.post('api/fuel.php?action=save_fuel_approval_user', payload, function (res) {
        if (res.status !== 'success') {
            alert(res.message || 'Unable to save approval user');
            return;
        }
        showSetupAlert('Approval user saved.');
        $('#fuelApprovalForm')[0].reset();
        loadFuelApprovalUsersTable();
        loadFuelSetupReferenceData();
    }, 'json');
}

function saveFuelPrice() {
    const payload = {
        fuel_type_id: $('#setup_price_fuel_type_id').val(),
        effective_date: $('#setup_price_effective_date').val(),
        state_id: $('#setup_price_state_id').val(),
        price_per_liter: $('#setup_price_per_liter').val(),
        vendor_name: $('#setup_price_vendor').val().trim(),
        remarks: $('#setup_price_remarks').val().trim()
    };

    if (!payload.fuel_type_id || !payload.effective_date || !payload.price_per_liter) {
        alert('Fuel type, effective date, and price are required');
        return;
    }

    $.post('api/fuel.php?action=save_fuel_price', payload, function (res) {
        if (res.status !== 'success') {
            alert(res.message || 'Unable to save fuel price');
            return;
        }
        showSetupAlert('Fuel price saved.');
        $('#fuelPriceForm')[0].reset();
        $('#setup_price_effective_date').val(new Date().toISOString().slice(0, 10));
        loadFuelPricesTable();
    }, 'json');
}

function populateSelect(selector, rows, placeholder) {
    const currentValue = $(selector).val();
    let html = `<option value="">${escapeHtml(placeholder)}</option>`;
    $.each(rows, function (_, row) {
        html += `<option value="${escapeHtml(row.id)}">${escapeHtml(row.label || row.name || '-')}</option>`;
    });
    $(selector).html(html);
    if (currentValue) {
        $(selector).val(String(currentValue));
    }
}

function 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' });
}

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

function deleteFuelType() {
    const id = $(this).data('id');
    if (!confirm('Delete this fuel type?')) return;
    $.post('api/fuel.php?action=delete_fuel_type', { id }, function (res) {
        if (res.status !== 'success') { alert(res.message || 'Unable to delete'); return; }
        showSetupAlert('Fuel type deleted.');
        loadFuelTypesTable();
    }, 'json');
}

function deleteFuelOffice() {
    const id = $(this).data('id');
    if (!confirm('Delete this office?')) return;
    $.post('api/fuel.php?action=delete_fuel_office', { id }, function (res) {
        if (res.status !== 'success') { alert(res.message || 'Unable to delete'); return; }
        showSetupAlert('Office deleted.');
        loadFuelOfficesTable();
    }, 'json');
}

function deleteFuelCompany() {
    const id = $(this).data('id');
    if (!confirm('Delete this company?')) return;
    $.post('api/fuel.php?action=delete_fuel_company', { id }, function (res) {
        if (res.status !== 'success') { alert(res.message || 'Unable to delete'); return; }
        showSetupAlert('Company deleted.');
        loadFuelCompaniesTable();
    }, 'json');
}

function deleteFuelStation() {
    const id = $(this).data('id');
    if (!confirm('Delete this filling station?')) return;
    $.post('api/fuel.php?action=delete_fuel_filling_station', { id }, function (res) {
        if (res.status !== 'success') { alert(res.message || 'Unable to delete'); return; }
        showSetupAlert('Filling station deleted.');
        loadFuelStationsTable();
    }, 'json');
}

function deleteFuelApprovalUser() {
    const id = $(this).data('id');
    if (!confirm('Remove this approval user?')) return;
    $.post('api/fuel.php?action=delete_fuel_approval_user', { id }, function (res) {
        if (res.status !== 'success') { alert(res.message || 'Unable to delete'); return; }
        showSetupAlert('Approval user removed.');
        loadFuelApprovalUsersTable();
    }, 'json');
}

function deleteFuelPrice() {
    const id = $(this).data('id');
    if (!confirm('Delete this fuel price record?')) return;
    $.post('api/fuel.php?action=delete_fuel_price', { id }, function (res) {
        if (res.status !== 'success') { alert(res.message || 'Unable to delete'); return; }
        showSetupAlert('Fuel price record deleted.');
        loadFuelPricesTable();
    }, 'json');
}

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