let fuelApprovalReferenceData = {
    vehicles: []
};
let fuelApprovalCanApprove = false;
let _fuelApprovalLastDate = null;
let _fuelApprovalLastId = null;

$(function () {
    const now = new Date();
    $('#fuelApprovalMonthFilter').val(now.toISOString().slice(0, 7));

    loadFuelApprovalReferenceData().always(function () {
        loadFuelApprovalCounts();
        loadFuelApprovalQueue();
    });

    $('#fuelApprovalStatusFilter, #fuelApprovalVehicleFilter, #fuelApprovalMonthFilter').on('change', function () { loadFuelApprovalQueue(); });
    let approvalSearchTimeout;
    $('#fuelApprovalSearch').on('keyup', function () {
        clearTimeout(approvalSearchTimeout);
        approvalSearchTimeout = setTimeout(function () { loadFuelApprovalQueue(); }, 300);
    });
    $('#btnRefreshFuelApprovalQueue').on('click', function () {
        loadFuelApprovalCounts();
        loadFuelApprovalQueue();
    });

    $(document).on('click', '.btn-fuel-queue-approve', function () {
        updateFuelQueueApproval($(this).data('id'), 'Approved');
    });
    $(document).on('click', '.btn-fuel-queue-reject', function () {
        updateFuelQueueApproval($(this).data('id'), 'Rejected');
    });

    $('#fuelBatchSelectAll').on('change', function () {
        $('.fuel-batch-checkbox').prop('checked', this.checked);
        updateBatchActions();
    });
    $(document).on('change', '.fuel-batch-checkbox', updateBatchActions);
    $('#btnBatchClear').on('click', function () {
        $('.fuel-batch-checkbox, #fuelBatchSelectAll').prop('checked', false);
        updateBatchActions();
    });
    $('#btnBatchApprove').on('click', function () {
        batchFuelApproval('Approved');
    });
    $('#btnBatchReject').on('click', function () {
        batchFuelApproval('Rejected');
    });
    $('#btnExportFuelApprovalCsv').on('click', function () {
        const params = new URLSearchParams({ action: 'fuel_export_csv' });
        const vehicleId = $('#fuelApprovalVehicleFilter').val();
        const approvalStatus = $('#fuelApprovalStatusFilter').val();
        const monthYear = $('#fuelApprovalMonthFilter').val();
        const search = $('#fuelApprovalSearch').val();
        if (vehicleId) params.set('vehicle_id', vehicleId);
        if (approvalStatus) params.set('approval_status', approvalStatus);
        if (monthYear) params.set('month_year', monthYear);
        if (search) params.set('search', search);
        window.location.href = 'api/fuel.php?' + params.toString();
    });
});

function updateFuelQueueApproval(id, approvalStatus, callback) {
    if (!fuelApprovalCanApprove) {
        alert('You are not allowed to approve fuel requests');
        if (callback) callback();
        return;
    }

    if (!callback) {
        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: function (res) {
            if (res.status !== 'success') {
                alert(res.message || 'Unable to update fuel approval');
                if (callback) { callback(); }
                return;
            }
            showApprovalAlert('Fuel request ' + approvalStatus.toLowerCase() + ' successfully.');
            if (callback) {
                callback();
            } else {
                loadFuelApprovalCounts();
                loadFuelApprovalQueue();
            }
        },
        error: function () {
            alert('Server error while updating fuel approval');
            if (callback) callback();
        }
    });
}

let _approvalAlertTimeout;

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

function updateBatchActions() {
    const checked = $('.fuel-batch-checkbox:checked');
    const count = checked.length;
    $('#fuelBatchCount').text(count + ' selected');
    $('#fuelBatchActions').toggleClass('d-none', count === 0);
}

function batchFuelApproval(status) {
    const ids = $('.fuel-batch-checkbox:checked').map(function () { return $(this).data('id'); }).get();
    if (!ids.length) return;
    if (!confirm('Are you sure you want to ' + status.toLowerCase() + ' ' + ids.length + ' fuel request(s)?')) return;

    let completed = 0;
    function processNext() {
        if (completed >= ids.length) {
            loadFuelApprovalCounts();
            loadFuelApprovalQueue();
            return;
        }
        updateFuelQueueApproval(ids[completed], status, processNext);
        completed++;
    }
    processNext();
}

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

        fuelApprovalReferenceData = res.data || fuelApprovalReferenceData;
        fuelApprovalCanApprove = Boolean((res.data || {}).can_approve);
        populateSelect('#fuelApprovalVehicleFilter', fuelApprovalReferenceData.vehicles || [], 'All vehicles');
    }, 'json');
}

function loadFuelApprovalQueue(append) {
    if (!append) {
        $('#fuelApprovalQueueTable').html('<tr><td colspan="9" class="text-center py-4"><div class="spinner-border spinner-border-sm me-2" role="status"></div>Loading approval queue...</td></tr>');
    }

    const params = {
        action: 'fuel_entries',
        approval_status: $('#fuelApprovalStatusFilter').val(),
        vehicle_id: $('#fuelApprovalVehicleFilter').val(),
        month_year: $('#fuelApprovalMonthFilter').val(),
        search: $('#fuelApprovalSearch').val()
    };

    if (append && _fuelApprovalLastDate && _fuelApprovalLastId) {
        params.last_date = _fuelApprovalLastDate;
        params.last_id = _fuelApprovalLastId;
    }

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

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

        if (!append) {
            _fuelApprovalLastDate = null;
            _fuelApprovalLastId = null;
            $(document).off('click', '#btnFuelApprovalLoadMore');
        }

        if (!rows.length && !append) {
            html = '<tr><td colspan="9" class="text-center text-muted">No fuel requests found for this filter.</td></tr>';
        } else {
            $.each(rows, function (_, row) {
                const canCheck = String(row.approval_status || '').toLowerCase() === 'pending';
                html += `
                    <tr>
                        <td>${canCheck ? '<input type="checkbox" class="fuel-batch-checkbox" data-id="' + row.id + '">' : ''}</td>
                        <td>
                            <div class="fw-semibold">${escapeHtml(row.voucher_id || '-')}</div>
                            <div class="text-muted small">${escapeHtml(row.created_by_name || 'System')}</div>
                        </td>
                        <td>
                            <div>${escapeHtml(formatDate(row.record_date))}</div>
                            <div class="text-muted small">${escapeHtml(formatTime(row.fueling_time))}</div>
                        </td>
                        <td>
                            <div class="fw-semibold">${escapeHtml(row.vehicle_no || row.plate_number || '-')}</div>
                            <div class="text-muted small">${escapeHtml(row.vehicle_type_label || row.vehicle_name || '-')}</div>
                        </td>
                        <td>
                            <div>${escapeHtml(row.driver_name || '-')}</div>
                            <div class="text-muted small">${escapeHtml([row.office_name, row.company_name].filter(Boolean).join(' | ') || '-')}</div>
                        </td>
                        <td>
                            <div>${escapeHtml(row.fuel_type_name || '-')}</div>
                            <div class="text-muted small">${escapeHtml(buildFuelApprovalFuelInfo(row))}</div>
                        </td>
                        <td>
                            <div>${escapeHtml(formatCurrency(row.total_amount))}</div>
                            <div class="text-muted small">Qty: ${escapeHtml(formatNumber(row.quantity_litres || row.fuel_purchase_liters))} Ltr</div>
                        </td>
                        <td>
                            <div>${renderFuelApprovalStatus(row.approval_status)}</div>
                            <div class="text-muted small">${escapeHtml(row.approved_by_name || '-')}</div>
                        </td>
                        <td>${buildFuelApprovalActions(row)}</td>
                    </tr>
                `;

                _fuelApprovalLastDate = row.record_date;
                _fuelApprovalLastId = row.id;
            });
        }

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

        const visibleCount = $('#fuelApprovalQueueTable tr').length - ($('#fuelApprovalQueueTable tr td[colspan]').length ? 1 : 0) - ($('#fuelApprovalLoadMoreRow').length ? 1 : 0);
        $('#fuelApprovalVisibleCount').text(visibleCount);

        const hasMore = res.has_more;
        if (hasMore && !$('#fuelApprovalLoadMoreRow').length) {
            $('#fuelApprovalQueueTable').append('<tr id="fuelApprovalLoadMoreRow"><td colspan="9" class="text-center py-2"><button type="button" class="btn btn-sm btn-outline-primary" id="btnFuelApprovalLoadMore">Load more</button></td></tr>');
        } else if (!hasMore) {
            $('#fuelApprovalLoadMoreRow').remove();
        }

        $(document).off('click', '#btnFuelApprovalLoadMore').on('click', '#btnFuelApprovalLoadMore', function () {
            loadFuelApprovalQueue(true);
        });
    }, 'json');
}

function loadFuelApprovalCounts() {
    $.get('api/fuel.php', { action: 'fuel_entry_counts' }, function (res) {
        if (res.status !== 'success' || !res.data) {
            $('#fuelApprovalPendingCount').text('-');
            $('#fuelApprovalApprovedCount').text('-');
            $('#fuelApprovalRejectedCount').text('-');
            return;
        }

        $('#fuelApprovalPendingCount').text(res.data.pending);
        $('#fuelApprovalApprovedCount').text(res.data.approved);
        $('#fuelApprovalRejectedCount').text(res.data.rejected);
    }, 'json');
}

function buildFuelApprovalActions(row) {
    if (!fuelApprovalCanApprove) {
        return '<span class="text-muted small">View only</span>';
    }
    if (String(row.approval_status || '').toLowerCase() === 'approved') {
        return '<span class="text-success small fw-semibold">Already approved</span>';
    }

    return `
        <div class="d-flex flex-wrap gap-2">
            <button type="button" class="btn btn-sm btn-success btn-fuel-queue-approve" data-id="${row.id}">Approve</button>
            <button type="button" class="btn btn-sm btn-outline-danger btn-fuel-queue-reject" data-id="${row.id}">Reject</button>
        </div>
    `;
}

function buildFuelApprovalFuelInfo(row) {
    const parts = [
        row.state_name,
        row.filling_station_name || row.filling_station,
        row.fueling_type
    ].filter(Boolean);
    return parts.join(' | ') || '-';
}

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

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 formatTime(value) {
    if (!value) return '-';
    return String(value).slice(0, 5);
}

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

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

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