$(async function () {
    "use strict";
    // Language
    let base_url = $('#base_url').val() || '';
    let language_name = $('#language_name').val() || 'en';
    let language_path = '/resources/lang/' + language_name + '.json';
    let language_file = base_url + language_path;
    let language_key = {};

    async function loadLanguage() {
        try {
            const res = await fetch(language_file);
            language_key = await res.json();
        } catch (err) {
            console.error('Failed to load language file:', err);
        }
    }
    await loadLanguage();

    let company_data = $('#company_data').val();
    try {
        if (company_data) JSON.parse(company_data);
    } catch (e) {
        console.error('Error parsing company info:', e);
    }

    let outletId = '';
    let date = '';
    let registerId = '';
    let table;

    let registerReportRoute;
    try {
        registerReportRoute = route('report.register-report', {}, false, Ziggy);
    } catch (e) {
        registerReportRoute = '/reports/register-report';
    }

    let currentFilterInfo = {
        outlet: null,
        date: null,
        register: null,
        generated_at: null,
        generated_by: null
    };

    function updateFilteredInformation(filterInfo) {
        if (!filterInfo) {
            $('#filteredInformation').hide();
            return;
        }
        let html = '<p class="pb-0 mb-0"><strong>' + (language_key.RegisterReport || 'Register Report') + '</strong></p>';
        if (filterInfo.outlet) {
            html += '<p class="pb-0 mb-0"><strong>' + (language_key.OutletName || 'Outlet Name') + ': </strong> ' + (filterInfo.outlet.name || '-') + '</p>';
            if (filterInfo.outlet.phone) html += '<p class="pb-0 mb-0"><strong>' + (language_key.OutletPhone || 'Outlet Phone') + ': </strong> ' + filterInfo.outlet.phone + '</p>';
            if (filterInfo.outlet.address) html += '<p class="pb-0 mb-0"><strong>' + (language_key.OutletAddress || 'Outlet Address') + ': </strong> ' + filterInfo.outlet.address + '</p>';
        }
        if (filterInfo.date) {
            html += '<p class="pb-0 mb-0"><strong>' + (language_key.Date || 'Date') + ': </strong> ' + filterInfo.date + '</p>';
        }
        if (filterInfo.register && filterInfo.register.label) {
            html += '<p class="pb-0 mb-0"><strong>' + (language_key.Register || 'Register') + ': </strong> ' + filterInfo.register.label + '</p>';
        }
        if (filterInfo.generated_at) {
            html += '<p class="pb-0 mb-0"><strong>' + (language_key.GeneratedOn || 'Generated on') + ': </strong> ' + filterInfo.generated_at + '</p>';
        }
        if (filterInfo.generated_by && (filterInfo.generated_by.name || filterInfo.generated_by.phone)) {
            let byText = [filterInfo.generated_by.name, filterInfo.generated_by.phone].filter(Boolean).join(', ');
            html += '<p class="pb-0 mb-0"><strong>' + (language_key.GeneratedBy || 'Generated by') + ': </strong> ' + byText + '</p>';
        }
        $('#filterInfoContent').html(html);
        $('#filteredInformation').show();
    }

    function getExportHeader() {
        let header = '<div style="margin-bottom: 20px;">';
        header += '<h3 style="text-align: center; margin-bottom: 15px;">' + (language_key.RegisterReport || 'Register Report') + '</h3>';
        if (currentFilterInfo.outlet) {
            header += '<p style="margin: 5px 0;"><strong>' + (language_key.OutletName || 'Outlet Name') + ': </strong> ' + (currentFilterInfo.outlet.name || '-') + '</p>';
            if (currentFilterInfo.outlet.phone) header += '<p style="margin: 5px 0;"><strong>' + (language_key.OutletPhone || 'Outlet Phone') + ': </strong> ' + currentFilterInfo.outlet.phone + '</p>';
            if (currentFilterInfo.outlet.address) header += '<p style="margin: 5px 0;"><strong>' + (language_key.OutletAddress || 'Outlet Address') + ': </strong> ' + currentFilterInfo.outlet.address + '</p>';
        }
        if (currentFilterInfo.date) header += '<p style="margin: 5px 0;"><strong>' + (language_key.Date || 'Date') + ': </strong> ' + currentFilterInfo.date + '</p>';
        if (currentFilterInfo.register && currentFilterInfo.register.label) header += '<p style="margin: 5px 0;"><strong>' + (language_key.Register || 'Register') + ': </strong> ' + currentFilterInfo.register.label + '</p>';
        if (currentFilterInfo.generated_at) header += '<p style="margin: 5px 0;"><strong>' + (language_key.GeneratedOn || 'Generated on') + ': </strong> ' + currentFilterInfo.generated_at + '</p>';
        if (currentFilterInfo.generated_by && (currentFilterInfo.generated_by.name || currentFilterInfo.generated_by.phone)) {
            let byText = [currentFilterInfo.generated_by.name, currentFilterInfo.generated_by.phone].filter(Boolean).join(', ');
            header += '<p style="margin: 5px 0;"><strong>' + (language_key.GeneratedBy || 'Generated by') + ': </strong> ' + byText + '</p>';
        }
        header += '</div>';
        return header;
    }

    function messageTopForExport() {
        let lines = (language_key.RegisterReport || 'Register Report') + '\n\n';
        if (currentFilterInfo.outlet) {
            lines += (language_key.OutletName || 'Outlet Name') + ': ' + (currentFilterInfo.outlet.name || '-') + '\n';
            if (currentFilterInfo.outlet.phone) lines += (language_key.OutletPhone || 'Outlet Phone') + ': ' + currentFilterInfo.outlet.phone + '\n';
            if (currentFilterInfo.outlet.address) lines += (language_key.OutletAddress || 'Outlet Address') + ': ' + currentFilterInfo.outlet.address + '\n';
        }
        if (currentFilterInfo.date) lines += (language_key.Date || 'Date') + ': ' + currentFilterInfo.date + '\n';
        if (currentFilterInfo.register && currentFilterInfo.register.label) lines += (language_key.Register || 'Register') + ': ' + currentFilterInfo.register.label + '\n';
        if (currentFilterInfo.generated_at) lines += (language_key.GeneratedOn || 'Generated on') + ': ' + currentFilterInfo.generated_at + '\n';
        if (currentFilterInfo.generated_by && (currentFilterInfo.generated_by.name || currentFilterInfo.generated_by.phone)) {
            lines += (language_key.GeneratedBy || 'Generated by') + ': ' + [currentFilterInfo.generated_by.name, currentFilterInfo.generated_by.phone].filter(Boolean).join(', ') + '\n';
        }
        return lines;
    }

    function initTable() {
        if ($.fn.DataTable.isDataTable('#registerReportTable')) {
            $('#registerReportTable').DataTable().destroy();
        }
        table = $('#registerReportTable').DataTable({
            processing: true,
            serverSide: false,
            paging: false,
            searching: true,
            ordering: true,
            info: true,
            autoWidth: false,
            responsive: true,
            data: [],
            columns: [
                { data: 'sn' },
                { data: 'employee' },
                { data: 'opening_date_time' },
                { data: 'opening_balance' },
                { data: 'sale_paid_amount' },
                { data: 'sale_return' },
                { data: 'customer_receive' },
                { data: 'purchase' },
                { data: 'purchase_return' },
                { data: 'supplier_payment' },
                { data: 'expense' },
                { data: 'down_payment' },
                { data: 'installment_collection' },
                { data: 'servicing' },
                { data: 'closing_balance' },
                { data: 'closing_date_time' },
                { data: 'sale_in_payment_method' }
            ],
            order: [[2, 'desc']],
            dom: '<"card-header border-bottom p-3"<"head-label"><"dt-action-buttons text-end"B>>' +
                '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
                '<"row"<"col-sm-12"tr>>' +
                '<"row"<"col-sm-12"i>>',
            buttons: [
                {
                    extend: 'collection',
                    className: 'btn btn-primary dropdown-toggle me-2',
                    text: '<i class="ti tabler-file-export me-sm-1"></i> <span class="d-none d-sm-inline-block">' + (language_key.Export || 'Export') + '</span>',
                    buttons: [
                        {
                            extend: 'print',
                            text: '<i class="ti tabler-printer me-1"></i>' + (language_key.Print || 'Print'),
                            className: 'dropdown-item',
                            title: '',
                            customize: function (win) {
                                $(win.document.body).prepend(getExportHeader());
                            }
                        },
                        {
                            extend: 'excelHtml5',
                            text: '<i class="ti tabler-file-spreadsheet me-1"></i>' + (language_key.Excel || 'Excel'),
                            className: 'dropdown-item',
                            title: '',
                            messageTop: messageTopForExport
                        },
                        {
                            extend: 'pdf',
                            text: '<i class="ti tabler-file-description me-1"></i>' + (language_key.Pdf || 'PDF'),
                            className: 'dropdown-item',
                            title: '',
                            orientation: 'landscape',
                            pageSize: 'A4',
                            messageTop: messageTopForExport
                        }
                    ]
                },
                {
                    text: '<i class="ti tabler-filter me-sm-1"></i> <span class="d-none d-sm-inline-block">' + (language_key.Filter || 'Filter') + '</span>',
                    className: 'btn create-new btn-primary',
                    action: function () {
                        $('#filterSection').slideToggle();
                    }
                }
            ]
        });
    }

    function initSelect2() {
        if ($('#outlet_id').length && !$('#outlet_id').hasClass('select2-hidden-accessible')) {
            $('#outlet_id').select2({
                dropdownParent: $('#filterSection'),
                width: '100%',
                placeholder: language_key.SelectOutlet || 'Select Outlet',
                allowClear: false
            });
        }
        if ($('#register_id').length && !$('#register_id').hasClass('select2-hidden-accessible')) {
            $('#register_id').select2({
                dropdownParent: $('#filterSection'),
                width: '100%',
                placeholder: language_key.AllRegisters || 'All Registers',
                allowClear: true
            });
        }
    }

    function loadRegistersForDate() {
        let out = $('#outlet_id').val();
        let dt = $('#date').val();
        let $reg = $('#register_id');
        $reg.find('option:not(:first)').remove();
        if (!out || !dt) return;
        $.ajax({
            url: base_url + registerReportRoute,
            type: 'GET',
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
            data: { action: 'registers', outlet_id: out, date: dt },
            success: function (res) {
                if (res.success && res.registers && res.registers.length) {
                    res.registers.forEach(function (r) {
                        $reg.append($('<option></option>').attr('value', r.id).text(r.label));
                    });
                }
            }
        });
    }

    function loadReportData() {
        outletId = $('#outlet_id').val();
        date = $('#date').val();
        registerId = $('#register_id').val() || '';
        if (!outletId || !date) {
            Swal.fire({
                icon: 'warning',
                title: language_key.Warning || 'Warning',
                text: language_key.OutletAndDateRequired || 'Outlet and Date are required',
                confirmButtonText: language_key.OK || 'OK'
            });
            return;
        }
        $.ajax({
            url: base_url + registerReportRoute,
            type: 'GET',
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
            data: { outlet_id: outletId, date: date, register_id: registerId },
            success: function (response) {
                if (response.success && response.data && response.data.registers) {
                    if (response.data.filter_info) {
                        currentFilterInfo = response.data.filter_info;
                        updateFilteredInformation(currentFilterInfo);
                    } else {
                        currentFilterInfo = { outlet: null, date: date, register: null, generated_at: null, generated_by: null };
                        updateFilteredInformation(currentFilterInfo);
                    }
                    table.clear();
                    table.rows.add(response.data.registers);
                    table.draw();
                } else {
                    table.clear().draw();
                    $('#filteredInformation').hide();
                }
            },
            error: function (xhr) {
                let msg = (xhr.responseJSON && xhr.responseJSON.message) ? xhr.responseJSON.message : (language_key.ErrorLoadingData || 'Error loading data');
                Swal.fire({ icon: 'error', title: language_key.Error || 'Error', text: msg, confirmButtonText: language_key.OK || 'OK' });
            }
        });
    }

    $(document).on('submit', '#filterForm', function (e) {
        e.preventDefault();
        return false;
    });
    $(document).on('keydown', '#filterForm input, #filterForm select', function (e) {
        if (e.key === 'Enter' || e.keyCode === 13) {
            e.preventDefault();
            $('#applyFilter').click();
            return false;
        }
    });

    $(document).on('change', '#outlet_id, #date', function () {
        loadRegistersForDate();
    });

    $(document).on('click', '#applyFilter', function (e) {
        e.preventDefault();
        loadReportData();
        return false;
    });

    function checkAndShowFilters() {
        let outVal = $('#outlet_id').val();
        let dateVal = $('#date').val();
        if (outVal && dateVal) {
            outletId = outVal;
            date = dateVal;
            registerId = $('#register_id').val() || '';
            $('#filterSection').show();
            initSelect2();
            loadRegistersForDate();
            setTimeout(function () { loadReportData(); }, 300);
        }
    }

    $('#filterSection').on('shown.bs.collapse shown', function () {
        initSelect2();
    });

    initTable();
    initSelect2();
    checkAndShowFilters();
});
