(function ($) {
    "use strict";

    // form serialize to Object
    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    function randomString() {
        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

        for (var i = 0; i < 5; i++)
            text += possible.charAt(Math.floor(Math.random() * possible.length));

        return text;
    }

    /**
     * close swl
     * */
    $('body').on('click', '.close-swl', function (e) {
        e.preventDefault();
        Swal.close();
    });


    $('#summernote').summernote({
        tabsize: 2,
        height: 400,
        placeholder: $('#summernote').attr('placeholder'),
        dialogsInBody: true,
        toolbar: [
            ['style', ['style']],
            ['font', ['bold', 'underline', 'clear']],
            ['fontname', ['fontname']],
            ['color', ['color']],
            ['para', ['paragraph']],
            ['table', ['table']],
            ['insert', ['link', 'picture', 'video']],
            ['view', ['fullscreen', 'codeview']],
        ],
    });


    $('body').on('click', '#saveAndPublish', function (e) {
        e.preventDefault();
        $('#forDraft').val('publish');
        $('#webinarForm').trigger('submit');
    });

    $('body').on('click', '#saveAsDraft', function (e) {
        e.preventDefault();
        $('#forDraft').val(1);
        $('#webinarForm').trigger('submit');
    });

    $('body').on('click', '#saveReject', function (e) {
        e.preventDefault();
        $('#forDraft').val('reject');
        $('#webinarForm').trigger('submit');
    });

    $('#partnerInstructorSwitch').on('change.bootstrapSwitch', function (e) {
        let isChecked = e.target.checked;

        if (isChecked) {
            $('#partnerInstructorInput').removeClass('d-none');
            resetSelect2();
        } else {
            $('#partnerInstructorInput').addClass('d-none');
        }
    });

    $('body').on('change', '#categories', function (e) {
        e.preventDefault();
        let category_id = this.value;
        $.get('/admin/filters/get-by-category-id/' + category_id, function (result) {

            if (result && typeof result.filters !== "undefined" && result.filters.length) {
                let html = '';
                Object.keys(result.filters).forEach(key => {
                    let filter = result.filters[key];
                    let options = [];

                    if (filter.options.length) {
                        options = filter.options;
                    }

                    html += '<div class="col-12 col-md-3">\n' +
                        '<div class="webinar-category-filters">\n' +
                        '<strong class="category-filter-title d-block">' + filter.title + '</strong>\n' +
                        '<div class="py-10"></div>\n' +
                        '\n';

                    if (options.length) {
                        Object.keys(options).forEach(index => {
                            let option = options[index];

                            html += '<div class="form-group mt-20 d-flex align-items-center justify-content-between">\n' +
                                '<label class="" for="filterOption' + option.id + '">' + option.title + '</label>\n' +
                                '<div class="custom-control custom-checkbox">\n' +
                                '<input type="checkbox" name="filters[]" value="' + option.id + '" class="custom-control-input" id="filterOption' + option.id + '">\n' +
                                '<label class="custom-control-label" for="filterOption' + option.id + '"></label>\n' +
                                '</div>\n' +
                                '</div>\n';
                        })
                    }

                    html += '</div></div>';
                });

                $('#categoriesFiltersContainer').removeClass('d-none');
                $('#categoriesFiltersCard').html(html);
            } else {
                $('#categoriesFiltersContainer').addClass('d-none');
                $('#categoriesFiltersCard').html('');
            }
        })
    });

    /**
     * add ticket
     * */
    $('body').on('click', '#webinarAddTicket', function (e) {
        e.preventDefault();
        let add_ticket_modal = '<div id="addTicketModal">';
        add_ticket_modal += $('#webinarTicketModal').html();
        add_ticket_modal += '</div>';

        Swal.fire({
            html: add_ticket_modal,
            showCancelButton: false,
            showConfirmButton: false,
            customClass: {
                content: 'p-0 text-left',
            },
            width: '48rem',
        });

        resetDatePickers();
    });

    $('body').on('click', '#saveTicket', function (e) {
        e.preventDefault();
        const $this = $(this);
        let form = $('#addTicketModal form');
        handleWebinarItemForm(form, $this);
    });

    /**
     * Contents
     * */

    // Select2 renderers for allowed users (ensure Name (email) shows in dropdown and selection)
    // Defined globally so it can be accessed from anywhere
    function select2UserTemplates() {
        return {
            templateResult: function (item) { return item.text; },
            templateSelection: function (item) { return item.text || item.id; }
        };
    }

    $(document).ready(function () {

        const style = getComputedStyle(document.body);
        const primaryColor = style.getPropertyValue('--primary');

        function updateToDatabase(table, idString) {
            $.post('/admin/webinars/order-items', {table: table, items: idString}, function (result) {
                if (result && result.title && result.msg) {
                    $.toast({
                        heading: result.title,
                        text: result.msg,
                        bgColor: primaryColor,
                        textColor: 'white',
                        hideAfter: 10000,
                        position: 'bottom-right',
                        icon: 'success'
                    });
                }
            })
        }

        function setSortable(target) {
            if (target.length) {
                target.sortable({
                    group: 'no-drop',
                    handle: '.move-icon',
                    axis: "y",
                    update: function (e, ui) {
                        var sortData = target.sortable('toArray', {attribute: 'data-id'});
                        var table = e.target.getAttribute('data-order-table');

                        updateToDatabase(table, sortData.join(','))
                    }
                });
            }
        }

        const items = [];

        var draggableContentLists = $('.draggable-content-lists');
        if (draggableContentLists.length) {
            for (let item of draggableContentLists) {
                items.push($(item).attr('data-drag-class'))
            }
        }

        if (items.length) {
            for (let item of items) {
                const tag = $('.' + item);

                if (tag.length) {
                    setSortable(tag);
                }
            }
        }

        const $fileForms = $('.file-form');

        if ($fileForms && $fileForms.length) {
            $fileForms.each(key => {
                if ($fileForms[key]) {
                    const $form = $($fileForms[key]);

                    const source = $form.find('.js-file-storage').val();
                    const fileType = $form.find('.js-ajax-file_type').val();
                    handleShowFileInputsBySource($form, source, fileType);
                }
            });
        }

        if ($('.accordion-content-wrapper .attachments-select2').length) {
            $('.accordion-content-wrapper .attachments-select2').select2({
                multiple: true,
                width: '100%',
            });
        }

        // Initialize Select2 for user selection dropdowns
        if ($('.select2').length) {
            $('.select2').each(function() {
                var $this = $(this);
                // Check if this is a user selection dropdown
                if ($this.attr('name') && $this.attr('name').includes('allowed_users')) {
                    // Check if already initialized and has proper AJAX config
                    if ($this.hasClass('select2-hidden-accessible')) {
                        var select2Data = $this.data('select2');
                        // If it has AJAX config, skip it (it's properly initialized)
                        if (select2Data && select2Data.options && select2Data.options.ajax) {
                            console.log('Select2 already initialized with AJAX for:', $this.attr('name'), '- SKIPPING main init');
                            
                            // But verify it has all selected values displayed
                            setTimeout(function() {
                                var currentVal = $this.val();
                                var select2DataArray = $this.select2('data');
                                
                                if (currentVal && Array.isArray(currentVal) && currentVal.length > 0) {
                                    var expectedCount = currentVal.length;
                                    var actualCount = select2DataArray ? select2DataArray.length : 0;
                                    
                                    if (actualCount !== expectedCount) {
                                        console.warn('Select2 data mismatch detected! Expected', expectedCount, 'but got', actualCount);
                                        console.warn('Current values:', currentVal);
                                        console.warn('Select2 data:', select2DataArray);
                                        console.warn('Forcing update of Select2 display...');
                                        
                                        // Re-fetch and update
                                        $.ajax({
                                            url: '/admin/webinars/get-users-by-ids',
                                            dataType: 'json',
                                            data: { ids: currentVal },
                                            success: function(users) {
                                                console.log('Fetched', users.length, 'users to fix display');
                                                
                                                // Destroy and re-init to ensure clean state
                                                $this.select2('destroy');
                                                
                                                // Update options
                                                $this.empty();
                                                users.forEach(function(user) {
                                                    var option = new Option(user.text, user.id, true, true);
                                                    $this.append(option);
                                                });
                                                
                                                // Re-initialize Select2 with AJAX
                                                var select2Config = {
                                                    multiple: true,
                                                    width: '100%',
                                                    placeholder: 'Type to search users or click to see all...',
                                                    allowClear: true,
                                                    closeOnSelect: false,
                                                    minimumInputLength: 0,
                                                    maximumSelectionLength: null,
                                                    dropdownParent: $this.closest('.swal2-container, .modal, .card-body, body'),
                                                    ajax: {
                                                        url: '/admin/webinars/search-users',
                                                        dataType: 'json',
                                                        delay: 250,
                                                        cache: true,
                                                        data: function (params) {
                                                            return {
                                                                q: params.term || '',
                                                                page: params.page || 1
                                                            };
                                                        },
                                                        processResults: function (data, params) {
                                                            return {
                                                                results: data,
                                                                pagination: { more: false }
                                                            };
                                                        },
                                                        error: function(xhr, status, error){
                                                            if (xhr.status !== 0 && status !== 'abort') {
                                                                console.error('User search error', {
                                                                    status: xhr.status,
                                                                    statusText: xhr.statusText,
                                                                    responseText: xhr.responseText,
                                                                    error: error
                                                                });
                                                            }
                                                            var deferred = $.Deferred();
                                                            deferred.resolve({ results: [] });
                                                            return deferred.promise();
                                                        }
                                                    },
                                                    templateResult: function(user) {
                                                        if (user.loading) {
                                                            return user.text;
                                                        }
                                                        return $('<div>').text(user.text || user.id);
                                                    },
                                                    templateSelection: function(user) {
                                                        return user.text || user.id;
                                                    }
                                                };
                                                
                                                $this.select2(select2Config);
                                                
                                                // Set values after initialization
                                                setTimeout(function() {
                                                    $this.val(currentVal).trigger('change');
                                                    var finalData = $this.select2('data');
                                                    console.log('Select2 display updated - Final count:', finalData ? finalData.length : 0, 'Expected:', expectedCount);
                                                }, 200);
                                            },
                                            error: function(xhr) {
                                                console.error('Error fetching users for display fix:', xhr);
                                            }
                                        });
                                    }
                                }
                            }, 500); // Wait a bit for Select2 to fully initialize
                            
                            return; // Skip this one - it's already properly initialized
                        } else {
                            // It's initialized but without AJAX - we need to re-initialize it
                            console.log('Select2 initialized but missing AJAX config for:', $this.attr('name'), '- Will re-initialize with AJAX');
                            // Get current selected values before destroying
                            var currentValues = $this.val() || [];
                            console.log('Preserving', currentValues.length, 'selected values before re-initialization');
                            $this.select2('destroy');
                            // Continue with initialization below
                        }
                    }
                    
                    console.log('Initializing allowed_users select2:', $this.attr('name'));
                    
                    // Get selected user IDs from existing options
                    var selectedUserIds = [];
                    $this.find('option:selected').each(function() {
                        var userId = $(this).val();
                        var userText = $(this).text();
                        console.log('Found selected option:', userId, userText);
                        if (userId) {
                            selectedUserIds.push(parseInt(userId));
                        }
                    });
                    
                    console.log('Selected user IDs from HTML:', selectedUserIds);
                    
                    var select2Config = {
                        multiple: true,
                        width: '100%',
                        placeholder: 'Type to search users or click to see all...',
                        allowClear: true,
                        closeOnSelect: false, // Keep dropdown open after selection
                        minimumInputLength: 0, // Allow clicking to show all users without typing
                        maximumSelectionLength: null, // No limit on number of selections
                        dropdownParent: $this.closest('.swal2-container, .modal, .card-body, body'),
                        // Add css classes so we can constrain height and enable scrolling
                        selectionCssClass: 'select2-users-selection',
                        dropdownCssClass: 'select2-users-dropdown',
                        language: {
                            inputTooShort: function () { 
                                return 'Type to search or click to see all users...'; 
                            },
                            searching: function() {
                                return 'Searching users...';
                            },
                            noResults: function() {
                                return 'No users found';
                            },
                            maximumSelected: function (e) {
                                return "You can only select " + e.maximum + " item(s)";
                            }
                        },
                        ajax: {
                            url: '/admin/webinars/search-users',
                            dataType: 'json',
                            delay: 250,
                            cache: true, // Cache results for better performance
                            data: function (params) {
                                return {
                                    q: params.term || '', // Allow empty search to get all users
                                    page: params.page || 1
                                };
                            },
                            processResults: function (data, params) {
                                // params.page = params.page || 1;
                                return {
                                    results: data,
                                    pagination: {
                                        more: false // Disable pagination for simplicity
                                    }
                                };
                            },
                            error: function(xhr, status, error){
                                // Only log if it's not an abort (status 0 usually means aborted)
                                if (xhr.status !== 0 && status !== 'abort') {
                                    console.error('User search error', {
                                        status: xhr.status,
                                        statusText: xhr.statusText,
                                        responseText: xhr.responseText,
                                        error: error,
                                        readyState: xhr.readyState,
                                        url: '/admin/webinars/search-users'
                                    });
                                }
                                
                                // Return empty results on error - Select2 expects a deferred/promise
                                var deferred = $.Deferred();
                                deferred.resolve({
                                    results: []
                                });
                                return deferred.promise();
                            }
                        },
                        // Ensure selected items are preserved
                        templateResult: function(user) {
                            if (user.loading) {
                                return user.text;
                            }
                            return $('<div>').text(user.text || user.id);
                        },
                        templateSelection: function(user) {
                            return user.text || user.id;
                        }
                    };
                    
                    // Check if options already have text (from backend rendering)
                    var hasTextOptions = false;
                    var selectedOptionsWithText = [];
                    var allSelectedIds = []; // Collect ALL selected IDs regardless of text
                    
                    console.log('Collecting selected options from:', $this.attr('name'));
                    $this.find('option:selected').each(function() {
                        var text = $(this).text();
                        var val = $(this).val();
                        var userId = parseInt(val);
                        
                        console.log('Found selected option - ID:', userId, 'Text:', text, 'Value:', val);
                        
                        if (userId && !isNaN(userId)) {
                            // Avoid duplicates
                            if (allSelectedIds.indexOf(userId) === -1) {
                                allSelectedIds.push(userId);
                            }
                        }
                        
                        if (text && text.trim() !== '' && text !== val && text !== String(userId)) {
                            hasTextOptions = true;
                            // Avoid duplicates
                            var exists = selectedOptionsWithText.some(function(opt) {
                                return opt.id === userId;
                            });
                            if (!exists) {
                                selectedOptionsWithText.push({
                                    id: userId,
                                    text: text
                                });
                            }
                        }
                    });
                    
                    console.log('Collected allSelectedIds:', allSelectedIds, 'Count:', allSelectedIds.length);
                    
                    // Always preserve selected users from HTML before initializing select2
                    var selectedIdsFromHtml = [];
                    $this.find('option:selected').each(function() {
                        var val = parseInt($(this).val());
                        if (val) {
                            selectedIdsFromHtml.push(val);
                        }
                    });
                    
                    console.log('Selected user IDs from HTML:', selectedIdsFromHtml);
                    console.log('All selected IDs (including those without text):', allSelectedIds);
                    console.log('Selected options with text:', selectedOptionsWithText.length);
                    
                    // If we have some options with text but not all, we need to fetch the missing ones
                    if (hasTextOptions && selectedOptionsWithText.length > 0) {
                        // Check if we have all IDs or if some are missing
                        var idsWithText = selectedOptionsWithText.map(function(opt) { return opt.id; });
                        var missingIds = allSelectedIds.filter(function(id) {
                            return idsWithText.indexOf(id) === -1;
                        });
                        
                        if (missingIds.length > 0) {
                            console.log('Some selected users are missing text, will fetch them:', missingIds);
                            // We'll need to fetch the missing ones, so fall through to the fetch logic
                            hasTextOptions = false; // Force fetch to get all users
                        }
                    }
                    
                    if (hasTextOptions && selectedOptionsWithText.length > 0 && selectedOptionsWithText.length === allSelectedIds.length) {
                        // Options have text from backend AND we have all users, ensure they're properly set
                        console.log('Options have text from backend:', selectedOptionsWithText);
                        
                        // Save the selected options before clearing
                        var selectedOptions = selectedOptionsWithText.map(function(opt) {
                            return { id: opt.id, text: opt.text };
                        });
                        
                        // Clear existing options but remember selected ones
                        $this.empty();
                        
                        // Add selected options back
                        selectedOptions.forEach(function(opt) {
                            var option = new Option(opt.text, opt.id, true, true);
                            $this.append(option);
                        });
                        
                        // Ensure all selected values are in the select
                        var selectedIds = selectedOptionsWithText.map(function(opt) { return opt.id; });
                        console.log('Setting selectedIds BEFORE select2 init:', selectedIds);
                        $this.val(selectedIds);
                        
                        // Verify BEFORE Select2 init
                        console.log('Verify select value BEFORE select2 init:', $this.val());
                        console.log('Verify selected options count BEFORE select2:', $this.find('option:selected').length);
                        
                        // CRITICAL: Pre-populate Select2 data from options with text
                        // This prevents Select2 from only showing the first option
                        var select2DataArray = selectedOptionsWithText.map(function(opt) {
                            return {
                                id: opt.id,
                                text: opt.text
                            };
                        });
                        
                        // Pre-populate the data option in Select2 config
                        // This is the most reliable way to ensure Select2 knows about all users
                        if (select2DataArray.length > 0) {
                            select2Config.data = select2DataArray;
                        }
                        
                        // Initialize with AJAX search but preserve selected values
                        select2Config.templateResult = select2UserTemplates().templateResult;
                        select2Config.templateSelection = select2UserTemplates().templateSelection;
                        $this.select2(select2Config);
                        
                        // Ensure values are set after select2 initialization - use array format
                        setTimeout(function() {
                            // Ensure all selected IDs are in array format
                            var valuesToSet = Array.isArray(selectedIds) ? selectedIds : [selectedIds];
                            console.log('Setting values after Select2 init:', valuesToSet);
                            
                            // Set the values - data is already in Select2 from config
                            $this.val(valuesToSet);
                            
                            // Trigger change to update Select2 display
                            $this.trigger('change.select2');
                            
                            // Verify data is still there
                            var currentData = $this.select2('data');
                            if (!currentData || currentData.length !== valuesToSet.length) {
                                console.warn('Data mismatch after init, re-setting data...');
                                if (select2DataArray.length > 0) {
                                    $this.select2('data', select2DataArray);
                                    $this.val(valuesToSet).trigger('change');
                                }
                            }
                            
                            console.log('Select2 initialized with values:', $this.val());
                            console.log('Number of selected options:', valuesToSet.length);
                            
                            // Get Select2 data to verify - check multiple times to catch timing issues
                            var checkCount = 0;
                            var maxChecks = 5;
                            
                            function checkSelect2Data() {
                                checkCount++;
                                var select2Data = $this.select2('data');
                                var currentVal = $this.val();
                                var actualCount = select2Data ? select2Data.length : 0;
                                var expectedCount = valuesToSet.length;
                                
                                console.log('Check #' + checkCount + ' - Select2 data length:', actualCount, 'Expected:', expectedCount);
                                console.log('Check #' + checkCount + ' - Select value:', currentVal);
                                
                                // If mismatch detected, fix it
                                if (actualCount !== expectedCount && checkCount < maxChecks) {
                                    console.warn('Mismatch detected on check #' + checkCount + '! Expected', expectedCount, 'but got', actualCount);
                                    
                                    // Try to fix by re-setting data and values
                                    if (select2DataArray.length > 0) {
                                        $this.select2('data', select2DataArray);
                                    }
                                    $this.val(valuesToSet).trigger('change');
                                    $this.select2('val', valuesToSet);
                                    
                                    // Set data again after val()
                                    if (select2DataArray.length > 0) {
                                        $this.select2('data', select2DataArray);
                                    }
                                    
                                    // Check again after a delay
                                    setTimeout(checkSelect2Data, 200);
                                } else if (actualCount !== expectedCount && checkCount >= maxChecks) {
                                    // Final attempt - re-fetch and re-initialize
                                    console.error('Mismatch persists after', maxChecks, 'attempts. Re-fetching users...');
                                    
                                    $.ajax({
                                        url: '/admin/webinars/get-users-by-ids',
                                        dataType: 'json',
                                        data: { ids: valuesToSet },
                                        success: function(users) {
                                            console.log('Re-fetching', users.length, 'users to fix display:', users);
                                            
                                            // Destroy Select2
                                            if ($this.hasClass('select2-hidden-accessible')) {
                                                $this.select2('destroy');
                                            }
                                            
                                            // Clear and re-add all options
                                            $this.empty();
                                            users.forEach(function(user) {
                                                var option = new Option(user.text, user.id, true, true);
                                                $this.append(option);
                                                console.log('Added option:', user.id, user.text);
                                            });
                                            
                                            // Set values BEFORE re-initializing
                                            $this.val(valuesToSet);
                                            console.log('Set select value BEFORE Select2 init:', $this.val());
                                            
                                            // Re-init Select2
                                            $this.select2(select2Config);
                                            
                                            // CRITICAL: Add data to Select2's internal cache so it recognizes the options
                                            var select2DataArray = users.map(function(user) {
                                                return {
                                                    id: user.id,
                                                    text: user.text
                                                };
                                            });
                                            
                                            // Set values and data after init
                                            setTimeout(function() {
                                                // Set the data in Select2's cache
                                                $this.select2('data', select2DataArray);
                                                
                                                // Set values
                                                $this.val(valuesToSet).trigger('change');
                                                
                                                // Verify
                                                var finalVal = $this.val();
                                                var finalData = $this.select2('data');
                                                console.log('Final fix - Select value:', finalVal);
                                                console.log('Final fix - Select2 data length:', finalData ? finalData.length : 0);
                                                console.log('Final fix - Select2 data:', finalData);
                                                
                                                if (!finalData || finalData.length !== valuesToSet.length) {
                                                    console.error('Fix still incomplete! Retrying...');
                                                    // One more retry with longer delay
                                                    setTimeout(function() {
                                                        $this.select2('data', select2DataArray);
                                                        $this.val(valuesToSet).trigger('change');
                                                        var retryData = $this.select2('data');
                                                        console.log('Retry - Select2 data length:', retryData ? retryData.length : 0);
                                                    }, 300);
                                                } else {
                                                    console.log('✓ Fix successful! All', valuesToSet.length, 'users are now displayed');
                                                }
                                            }, 200);
                                        },
                                        error: function(xhr) {
                                            console.error('Error re-fetching users:', xhr);
                                        }
                                    });
                                } else if (actualCount === expectedCount) {
                                    console.log('✓ Select2 data matches! All', expectedCount, 'users are displayed correctly');
                                }
                            }
                            
                            // Start checking immediately and then again after delays
                            checkSelect2Data();
                            setTimeout(checkSelect2Data, 200);
                            setTimeout(checkSelect2Data, 500);
                        }, 150);
                        
                        // Handle unselect to prevent clearing all
                        $this.on('select2:unselecting', function(e) {
                            console.log('User unselecting:', e.params.args.data.id);
                            // This is fine - just unselecting one user
                        });
                        
                        // Keep dropdown open after selection to allow multiple selections
                        $this.on('select2:selecting', function(e) {
                            console.log('User selecting, preventing dropdown close');
                            $this.data('selecting-user', true);
                        });
                        
                        $this.on('select2:select', function(e) {
                            console.log('User selected, keeping dropdown open');
                            
                            // CRITICAL: Update Select2 data cache to include the newly selected user
                            var selectedData = e.params.data;
                            if (selectedData && selectedData.id) {
                                // Use a small delay to ensure Select2 has processed the selection
                                setTimeout(function() {
                                    var currentData = $this.select2('data') || [];
                                    var currentVal = $this.val() || [];
                                    
                                    // Check if this user is already in the data cache
                                    var existsInCache = currentData.some(function(item) {
                                        return String(item.id) == String(selectedData.id);
                                    });
                                    
                                    // Check if the value is in the selected values
                                    var valueExists = currentVal.some(function(val) {
                                        return String(val) == String(selectedData.id);
                                    });
                                    
                                    if (!existsInCache && valueExists) {
                                        // Add the new user to the data cache
                                        currentData.push({
                                            id: selectedData.id,
                                            text: selectedData.text || selectedData.id
                                        });
                                        $this.select2('data', currentData);
                                        console.log('Added new user to Select2 data cache:', selectedData.id, selectedData.text);
                                        console.log('Select2 data cache now has', currentData.length, 'users');
                                        
                                        // Verify the update worked
                                        setTimeout(function() {
                                            var verifyData = $this.select2('data');
                                            var verifyVal = $this.val();
                                            console.log('Verification - Select2 data count:', verifyData ? verifyData.length : 0);
                                            console.log('Verification - Select value count:', verifyVal ? (Array.isArray(verifyVal) ? verifyVal.length : 1) : 0);
                                        }, 100);
                                    } else if (existsInCache) {
                                        console.log('User already in Select2 data cache:', selectedData.id);
                                    } else if (!valueExists) {
                                        console.warn('User selected but value not in select:', selectedData.id);
                                    }
                                }, 50);
                            }
                            
                            var $select = $this;
                            setTimeout(function() {
                                if (!$select.select2('isOpen')) {
                                    console.log('Dropdown closed, reopening...');
                                    $select.select2('open');
                                }
                                $select.removeData('selecting-user');
                            }, 100);
                        });
                        
                        $this.one('select2:open', function(){
                            if ($this.data('initial-users-loaded')) return;
                            $.ajax({
                                url: '/admin/webinars/search-users',
                                dataType: 'json',
                                data: { q: '', page: 1 },
                                success: function(list){
                                    (list || []).forEach(function(u){
                                        if ($this.find('option[value="' + u.id + '"]').length === 0) {
                                            var opt = new Option(u.text, u.id, false, false);
                                            $this.append(opt);
                                        }
                                    });
                                    $this.data('initial-users-loaded', true);
                                }
                            });
                        });
                    } else if (selectedUserIds.length > 0 || selectedIdsFromHtml.length > 0 || allSelectedIds.length > 0) {
                        // Selected users without text, fetch their details
                        // Use allSelectedIds if available (most complete), otherwise fall back to others
                        var userIdsToFetch = allSelectedIds.length > 0 ? allSelectedIds : (selectedUserIds.length > 0 ? selectedUserIds : selectedIdsFromHtml);
                        
                        // Remove duplicates and ensure all are numbers
                        userIdsToFetch = userIdsToFetch.filter(function(id, index) {
                            return id && !isNaN(id) && userIdsToFetch.indexOf(id) === index;
                        }).map(function(id) { return parseInt(id); });
                        
                        console.log('Fetching details for selected users:', userIdsToFetch);
                        console.log('Total users to fetch:', userIdsToFetch.length);
                        console.log('Comparison - allSelectedIds:', allSelectedIds.length, 'selectedUserIds:', selectedUserIds.length, 'selectedIdsFromHtml:', selectedIdsFromHtml.length);
                        
                        // Clear select but remember selected IDs
                        $this.empty();
                        
                        $.ajax({
                            url: '/admin/webinars/get-users-by-ids',
                            dataType: 'json',
                            data: { ids: userIdsToFetch },
                            success: function(users) {
                                console.log('Received user details:', users);
                                
                                // Add selected users as options - ensure all are added
                                console.log('Adding', users.length, 'users as options');
                                users.forEach(function(user) {
                                    var option = new Option(user.text, user.id, true, true);
                                    $this.append(option);
                                    console.log('Added option:', user.id, user.text);
                                });
                                
                                // Set the selected values - ensure it's an array
                                var selectedIds = users.map(function(u) { return parseInt(u.id); });
                                console.log('Setting selectedIds as array:', selectedIds);
                                
                                // CRITICAL: Set val() BEFORE initializing Select2
                                $this.val(selectedIds);
                                
                                // Verify the values are set BEFORE Select2 init
                                console.log('Verify select value BEFORE select2 init:', $this.val());
                                console.log('Verify selected options count BEFORE select2:', $this.find('option:selected').length);
                                
                                // Now initialize Select2 with the pre-loaded options
                                select2Config.templateResult = select2UserTemplates().templateResult;
                                select2Config.templateSelection = select2UserTemplates().templateSelection;
                                
                                // Initialize Select2
                                $this.select2(select2Config);
                                
                                // CRITICAL: Set data cache immediately after initialization with ALL users
                                var select2DataArray = users.map(function(user) {
                                    return {
                                        id: user.id,
                                        text: user.text
                                    };
                                });
                                
                                // Set the data in Select2's cache immediately
                                $this.select2('data', select2DataArray);
                                console.log('Select2 initialized with', users.length, 'users');
                                console.log('Fetched user details for initialization:', users);
                                
                                // CRITICAL: After Select2 init, ensure all values are set and trigger change
                                setTimeout(function() {
                                    // Ensure all selected IDs are in array format
                                    var valuesToSet = Array.isArray(selectedIds) ? selectedIds : [selectedIds];
                                    console.log('Setting values after Select2 init:', valuesToSet);
                                    
                                    // Set the data cache again to ensure it's there
                                    $this.select2('data', select2DataArray);
                                    
                                    // Set the values
                                    $this.val(valuesToSet);
                                    
                                    // Trigger change to update Select2 display
                                    $this.trigger('change.select2');
                                    
                                    // Force Select2 to update its display
                                    $this.select2('val', valuesToSet);
                                    
                                    // Set data one more time after setting values
                                    $this.select2('data', select2DataArray);
                                    
                                    console.log('Select2 values after setting:', $this.val());
                                    console.log('Number of selected values:', valuesToSet.length);
                                    console.log('Select2 selected options count:', $this.find('option:selected').length);
                                    
                                    // Get Select2 data to verify
                                    var select2Data = $this.select2('data');
                                    console.log('Select2 data array:', select2Data);
                                    console.log('Select2 data length:', select2Data ? select2Data.length : 0);
                                    
                                    // Verify each option exists
                                    valuesToSet.forEach(function(id) {
                                        var $option = $this.find('option[value="' + id + '"]');
                                        if ($option.length === 0) {
                                            console.warn('Option not found for user ID:', id);
                                        } else {
                                            console.log('Option found for user ID:', id, $option.text(), 'Selected:', $option.is(':selected'));
                                        }
                                    });
                                    
                                    // CRITICAL FIX: If Select2 data doesn't match expected values, force update
                                    if (!select2Data || select2Data.length !== valuesToSet.length) {
                                        console.warn('Select2 data mismatch detected! Expected', valuesToSet.length, 'users but got', select2Data ? select2Data.length : 0);
                                        console.warn('Current values:', valuesToSet);
                                        console.warn('Select2 data:', select2Data);
                                        console.warn('Forcing Select2 to update with all values...');
                                        
                                        // Destroy and re-initialize if needed
                                        setTimeout(function() {
                                            // Re-fetch user details to ensure all options exist
                                            $.ajax({
                                                url: '/admin/webinars/get-users-by-ids',
                                                dataType: 'json',
                                                data: { ids: valuesToSet },
                                        success: function(users) {
                                            console.log('Re-fetching', users.length, 'users to fix display:', users);
                                            
                                            // Destroy Select2 first
                                            if ($this.hasClass('select2-hidden-accessible')) {
                                                $this.select2('destroy');
                                            }
                                            
                                            // Clear and re-add all options
                                            $this.empty();
                                            users.forEach(function(user) {
                                                var option = new Option(user.text, user.id, true, true);
                                                $this.append(option);
                                                console.log('Added option:', user.id, user.text);
                                            });
                                            
                                            // Set values BEFORE re-initializing Select2
                                            $this.val(valuesToSet);
                                            console.log('Set select value to:', $this.val());
                                            
                                            // Re-init Select2 with AJAX config
                                            $this.select2(select2Config);
                                            
                                            // CRITICAL: Add data to Select2's internal cache so it recognizes the options
                                            var select2DataArray = users.map(function(user) {
                                                return {
                                                    id: user.id,
                                                    text: user.text
                                                };
                                            });
                                            
                                            // Set values and data after Select2 init
                                            setTimeout(function() {
                                                // Set the data in Select2's cache FIRST
                                                $this.select2('data', select2DataArray);
                                                
                                                // Then set values
                                                $this.val(valuesToSet).trigger('change');
                                                
                                                // Verify
                                                var finalVal = $this.val();
                                                var finalData = $this.select2('data');
                                                console.log('After fix - Select value:', finalVal);
                                                console.log('After fix - Select2 data length:', finalData ? finalData.length : 0);
                                                console.log('After fix - Select2 data:', finalData);
                                                
                                                if (!finalData || finalData.length !== valuesToSet.length) {
                                                    console.error('Fix failed! Still showing', finalData ? finalData.length : 0, 'instead of', valuesToSet.length);
                                                    // Try one more time with data set again
                                                    setTimeout(function() {
                                                        $this.select2('data', select2DataArray);
                                                        $this.val(valuesToSet).trigger('change');
                                                        var retryData = $this.select2('data');
                                                        console.log('Retry - Select2 data length:', retryData ? retryData.length : 0);
                                                    }, 300);
                                                } else {
                                                    console.log('✓ Fix successful! All', valuesToSet.length, 'users are now displayed');
                                                }
                                            }, 200);
                                        },
                                                error: function(xhr) {
                                                    console.error('Error re-fetching users:', xhr);
                                                }
                                            });
                                        }, 300);
                                    } else {
                                        console.log('Select2 data matches expected values:', valuesToSet.length, 'users');
                                    }
                                }, 150);
                                
                                // Handle unselect to prevent clearing all
                                $this.on('select2:unselecting', function(e) {
                                    console.log('User unselecting:', e.params.args.data.id);
                                    // Store current values before unselect
                                    var currentValues = $this.val() || [];
                                    $this.data('before-unselect', currentValues);
                                });
                                
                                $this.on('select2:unselect', function(e) {
                                    console.log('User unselected:', e.params.data.id);
                                    var currentValues = $this.val() || [];
                                    console.log('Remaining values after unselect:', currentValues);
                                    // Ensure we still have options for remaining values
                                    if (currentValues.length > 0) {
                                        setTimeout(function() {
                                            $this.val(currentValues).trigger('change');
                                        }, 50);
                                    }
                                });
                                
                                // Keep dropdown open after selection to allow multiple selections
                                $this.on('select2:selecting', function(e) {
                                    console.log('User selecting, preventing dropdown close');
                                    $this.data('selecting-user', true);
                                });
                                
                                $this.on('select2:select', function(e) {
                                    console.log('User selected, keeping dropdown open');
                                    
                                    // CRITICAL: Update Select2 data cache to include the newly selected user
                                    var selectedData = e.params.data;
                                    if (selectedData && selectedData.id) {
                                        // Use a small delay to ensure Select2 has processed the selection
                                        setTimeout(function() {
                                            var currentData = $this.select2('data') || [];
                                            var currentVal = $this.val() || [];
                                            
                                            // Check if this user is already in the data cache
                                            var existsInCache = currentData.some(function(item) {
                                                return String(item.id) == String(selectedData.id);
                                            });
                                            
                                            // Check if the value is in the selected values
                                            var valueExists = currentVal.some(function(val) {
                                                return String(val) == String(selectedData.id);
                                            });
                                            
                                            if (!existsInCache && valueExists) {
                                                // Add the new user to the data cache
                                                currentData.push({
                                                    id: selectedData.id,
                                                    text: selectedData.text || selectedData.id
                                                });
                                                $this.select2('data', currentData);
                                                console.log('Added new user to Select2 data cache:', selectedData.id, selectedData.text);
                                                console.log('Select2 data cache now has', currentData.length, 'users');
                                                
                                                // Verify the update worked
                                                setTimeout(function() {
                                                    var verifyData = $this.select2('data');
                                                    var verifyVal = $this.val();
                                                    console.log('Verification - Select2 data count:', verifyData ? verifyData.length : 0);
                                                    console.log('Verification - Select value count:', verifyVal ? (Array.isArray(verifyVal) ? verifyVal.length : 1) : 0);
                                                }, 100);
                                            } else if (existsInCache) {
                                                console.log('User already in Select2 data cache:', selectedData.id);
                                            } else if (!valueExists) {
                                                console.warn('User selected but value not in select:', selectedData.id);
                                            }
                                        }, 50);
                                    }
                                    
                                    var $select = $this;
                                    setTimeout(function() {
                                        if (!$select.select2('isOpen')) {
                                            console.log('Dropdown closed, reopening...');
                                            $select.select2('open');
                                        }
                                        $select.removeData('selecting-user');
                                    }, 100);
                                });
                                
                                $this.one('select2:open', function(){
                                    if ($this.data('initial-users-loaded')) return;
                                    $.ajax({
                                        url: '/admin/webinars/search-users',
                                        dataType: 'json',
                                        data: { q: '', page: 1 },
                                        success: function(list){
                                            (list || []).forEach(function(u){
                                                if ($this.find('option[value="' + u.id + '"]').length === 0) {
                                                    var opt = new Option(u.text, u.id, false, false);
                                                    $this.append(opt);
                                                }
                                            });
                                            $this.data('initial-users-loaded', true);
                                        }
                                    });
                                });
                            },
                            error: function(xhr, status, error) {
                                console.error('Error loading selected users', {
                                    status: xhr.status,
                                    statusText: xhr.statusText,
                                    responseText: xhr.responseText,
                                    error: error
                                });
                                // Initialize anyway with existing selected values
                                $this.val(selectedUserIds);
                                select2Config.templateResult = select2UserTemplates().templateResult;
                                select2Config.templateSelection = select2UserTemplates().templateSelection;
                                $this.select2(select2Config);
                                setTimeout(function() {
                                    $this.val(selectedUserIds).trigger('change');
                                }, 100);
                                $this.one('select2:open', function(){
                                    if ($this.data('initial-users-loaded')) return;
                                    $.ajax({
                                        url: '/admin/webinars/search-users',
                                        dataType: 'json',
                                        data: { q: '', page: 1 },
                                        success: function(list){
                                            (list || []).forEach(function(u){
                                                if ($this.find('option[value="' + u.id + '"]').length === 0) {
                                                    var opt = new Option(u.text, u.id, false, false);
                                                    $this.append(opt);
                                                }
                                            });
                                            $this.data('initial-users-loaded', true);
                                        }
                                    });
                                });
                            }
                        });
                    } else {
                        // No selected users, initialize with AJAX search
                        console.log('No selected users, initializing with AJAX search');
                        select2Config.templateResult = select2UserTemplates().templateResult;
                        select2Config.templateSelection = select2UserTemplates().templateSelection;
                        $this.select2(select2Config);
                        
                        // Keep dropdown open after selection to allow multiple selections
                        $this.on('select2:selecting', function(e) {
                            console.log('User selecting, preventing dropdown close');
                            $this.data('selecting-user', true);
                        });
                        
                        $this.on('select2:select', function(e) {
                            console.log('User selected, keeping dropdown open for multiple selections');
                            
                            // CRITICAL: Update Select2 data cache to include the newly selected user
                            var selectedData = e.params.data;
                            if (selectedData && selectedData.id) {
                                // Use a small delay to ensure Select2 has processed the selection
                                setTimeout(function() {
                                    var currentData = $this.select2('data') || [];
                                    var currentVal = $this.val() || [];
                                    
                                    // Check if this user is already in the data cache
                                    var existsInCache = currentData.some(function(item) {
                                        return String(item.id) == String(selectedData.id);
                                    });
                                    
                                    // Check if the value is in the selected values
                                    var valueExists = currentVal.some(function(val) {
                                        return String(val) == String(selectedData.id);
                                    });
                                    
                                    if (!existsInCache && valueExists) {
                                        // Add the new user to the data cache
                                        currentData.push({
                                            id: selectedData.id,
                                            text: selectedData.text || selectedData.id
                                        });
                                        $this.select2('data', currentData);
                                        console.log('Added new user to Select2 data cache:', selectedData.id, selectedData.text);
                                        console.log('Select2 data cache now has', currentData.length, 'users');
                                        
                                        // Verify the update worked
                                        setTimeout(function() {
                                            var verifyData = $this.select2('data');
                                            var verifyVal = $this.val();
                                            console.log('Verification - Select2 data count:', verifyData ? verifyData.length : 0);
                                            console.log('Verification - Select value count:', verifyVal ? (Array.isArray(verifyVal) ? verifyVal.length : 1) : 0);
                                        }, 100);
                                    } else if (existsInCache) {
                                        console.log('User already in Select2 data cache:', selectedData.id);
                                    } else if (!valueExists) {
                                        console.warn('User selected but value not in select:', selectedData.id);
                                    }
                                }, 50);
                            }
                            
                            var $select = $this;
                            setTimeout(function() {
                                if (!$select.select2('isOpen')) {
                                    console.log('Dropdown closed, reopening...');
                                    $select.select2('open');
                                }
                                $select.removeData('selecting-user');
                            }, 100);
                        });
                        
                        $this.one('select2:open', function(){
                            if ($this.data('initial-users-loaded')) return;
                            $.ajax({
                                url: '/admin/webinars/search-users',
                                dataType: 'json',
                                data: { q: '', page: 1 },
                                success: function(list){
                                    (list || []).forEach(function(u){
                                        if ($this.find('option[value="' + u.id + '"]').length === 0) {
                                            var opt = new Option(u.text, u.id, false, false);
                                            $this.append(opt);
                                        }
                                    });
                                    $this.data('initial-users-loaded', true);
                                }
                            });
                        });
                    }
                } else {
                    // Regular select2 initialization
                    $this.select2({
                        width: '100%',
                        placeholder: function() {
                            return $(this).data('placeholder') || 'Select...';
                        },
                        allowClear: true,
                        closeOnSelect: false
                    });
                }
            });
        }

        var summernoteTarget = $('.accordion-content-wrapper .js-content-summernote');
        if (summernoteTarget.length) {
            summernoteTarget.summernote({
                tabsize: 2,
                height: 400,
                callbacks: {
                    onChange: function (contents, $editable) {
                        $('.js-hidden-content-summernote').val(contents);
                    }
                }
            });
        }
    });

    $('body').on('change', '.js-webinar-content-locale', function (e) {
        e.preventDefault();

        const $this = $(this);
        const $form = $(this).closest('.js-content-form');
        const locale = $this.val();
        const webinarId = $this.attr('data-webinar-id');
        const item_id = $this.attr('data-id');
        const relation = $this.attr('data-relation');
        let fields = $this.attr('data-fields');
        fields = fields.split(',');


        $this.addClass('loadingbar gray');

        const path = '/admin/webinars/' + webinarId + '/getContentItemByLocale';
        const data = {
            item_id,
            locale,
            relation
        };

        $.post(path, data, function (result) {
            if (result && result.item) {
                const item = result.item;

                Object.keys(item).forEach(function (key) {
                    const value = item[key];

                    if ($.inArray(key, fields) !== -1) {
                        let element = $form.find('.js-ajax-' + key);
                        element.val(value);
                    }

                    if (relation === 'textLessons' && key === 'content') {
                        var summernoteTarget = $form.find('.js-content-' + item_id);

                        if (summernoteTarget.length) {
                            summernoteTarget.summernote('destroy');


                            summernoteTarget.val(value);
                            $('.js-hidden-content-' + item_id).val(value);

                            summernoteTarget.summernote({
                                tabsize: 2,
                                height: 400,
                                callbacks: {
                                    onChange: function (contents, $editable) {
                                        $('.js-hidden-content-' + item_id).val(contents);
                                    }
                                }
                            });
                        }
                    }
                });

                $this.removeClass('loadingbar gray');
            }
        }).fail(err => {
            $this.removeClass('loadingbar gray');
        });
    });

    function handleFileFormSubmit(form, $this) {
        console.log('=== HANDLE FILE FORM SUBMIT START ===');
        console.log('Form element:', form);
        console.log('Form action:', form.attr('action'));
        console.log('Form data-action:', form.attr('data-action'));
        
        // Ensure select2 values are properly included in form serialization
        form.find('select.select2, select[name*="allowed_users"]').each(function() {
            var $select = $(this);
            console.log('File form - Found select element:', $select.attr('name'), 'Select2 initialized:', $select.hasClass('select2-hidden-accessible'));
            
            if ($select.hasClass('select2-hidden-accessible')) {
                // Get selected values from select2
                var selectedValues = $select.select2('val');
                console.log('File form - Select2 selected values:', selectedValues);
                console.log('File form - Select element current value:', $select.val());
                
                if (selectedValues && selectedValues.length > 0) {
                    // Ensure the underlying select element has the correct values
                    $select.val(selectedValues);
                    console.log('File form - Set select value to:', $select.val());
                } else {
                    // Clear the select if no values are selected
                    $select.val(null);
                    console.log('File form - Cleared select value');
                }
                // Trigger change to ensure select2 syncs values to the original select
                $select.trigger('change');
                console.log('File form - After trigger change, select value:', $select.val());
            }
        });
        
        let data = serializeObjectByTag(form);
        console.log('File form - Raw serialized data:', data);
        console.log('File form - Raw data keys:', Object.keys(data));
        
        let action = form.attr('data-action');

        $this.addClass('loadingbar primary').prop('disabled', true);
        form.find('input').removeClass('is-invalid');
        form.find('textarea').removeClass('is-invalid');

        var formData = new FormData();

        const s3Input = form.find('.js-s3-file-input');

        if (s3Input && s3Input.prop('files') && s3Input.prop('files')[0]) {
            formData.append('s3_file', s3Input.prop('files')[0]);
        }

        const items = form.find('input, textarea, select').serializeArray();
        console.log('File form - Serialized array items:', items);
        console.log('File form - Items with allowed_users:', items.filter(function(item) { return item.name.includes('allowed_users'); }));

        $.each(items, function () {
            formData.append(this.name, this.value);
            if (this.name.includes('allowed_users')) {
                console.log('File form - Appending to FormData:', this.name, '=', this.value);
            }
        });
        
        console.log('File form - FormData entries for allowed_users:');
        for (var pair of formData.entries()) {
            if (pair[0].includes('allowed_users')) {
                console.log('  ', pair[0], ':', pair[1]);
            }
        }

        $.ajax({
            url: action,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            cache: false,
            success: function (result) {
                if (result && result.code === 200) {
                    //window.location.reload();
                    Swal.fire({
                        icon: 'success',
                        html: '<h3 class="font-20 text-center text-dark-blue py-25">' + saveSuccessLang + '</h3>',
                        showConfirmButton: false,
                        width: '25rem',
                    });

                    setTimeout(() => {
                        window.location.reload();
                    }, 500);
                }
            },
            error: function (err) {
                $this.removeClass('loadingbar primary').prop('disabled', false);
                var errors = err.responseJSON;
                
                console.error('File form submission error:', err);
                console.error('Error response:', errors);

                var errorMessage = 'An error occurred while saving the file.';
                var errorDetails = [];
                
                if (errors) {
                    if (errors.message) {
                        errorMessage = errors.message;
                    }
                    
                    if (errors.errors) {
                        Object.keys(errors.errors).forEach((key) => {
                            const error = errors.errors[key];
                            var errorText = Array.isArray(error) ? error[0] : error;
                            errorDetails.push(key + ': ' + errorText);
                            
                            let element = form.find('.js-ajax-' + key);
                            
                            if (!element.length) {
                                // Try without js-ajax prefix
                                element = form.find('[name="' + key + '"]');
                            }
                            
                            // Also try to find by name containing the key
                            if (!element.length) {
                                element = form.find('[name*="' + key + '"]');
                            }

                            if (element.length) {
                                element.addClass('is-invalid');
                                const feedbackElement = element.parent().find('.invalid-feedback');
                                if (feedbackElement.length) {
                                    feedbackElement.text(errorText);
                                } else {
                                    // Create feedback element if it doesn't exist
                                    element.after('<div class="invalid-feedback">' + errorText + '</div>');
                                }
                            }
                        });
                    }
                }
                
                if (errorDetails.length > 0) {
                    errorMessage += '\n\nValidation Errors:\n' + errorDetails.join('\n');
                }

                Swal.fire({
                    icon: 'error',
                    title: 'Error Saving File',
                    text: errorMessage,
                    width: '40rem',
                });
            }
        });
    }

    window.handleWebinarItemForm = function (form, $this) {
        console.log('=== HANDLE WEBINAR ITEM FORM START ===');
        console.log('Form element:', form);
        console.log('Form action:', form.attr('action'));
        console.log('Form data-action:', form.attr('data-action'));
        
        // Ensure select2 values are properly included in form serialization
        form.find('select.select2, select[name*="allowed_users"]').each(function() {
            var $select = $(this);
            console.log('Found select element:', $select.attr('name'), 'Select2 initialized:', $select.hasClass('select2-hidden-accessible'));
            
            if ($select.hasClass('select2-hidden-accessible')) {
                // Get selected values from select2
                var selectedValues = $select.select2('val');
                console.log('Select2 selected values:', selectedValues);
                console.log('Select element current value:', $select.val());
                console.log('Select element options:', $select.find('option').length);
                
                if (selectedValues && selectedValues.length > 0) {
                    // Ensure the underlying select element has the correct values
                    $select.val(selectedValues);
                    console.log('Set select value to:', $select.val());
                } else {
                    // Clear the select if no values are selected
                    $select.val(null);
                    console.log('Cleared select value');
                }
                // Trigger change to ensure select2 syncs values to the original select
                $select.trigger('change');
                console.log('After trigger change, select value:', $select.val());
            }
        });
        
        let data = serializeObjectByTag(form);
        console.log('Raw serialized data:', data);
        console.log('Raw data keys:', Object.keys(data));
        
        let action = form.attr('data-action') || form.attr('action');
        console.log('Action URL:', action);
        
        // Handle allowed_users[] field - ensure it's always an array
        // The field name is allowed_users[] so serializeObjectByTag creates allowed_users[] key
        var allowedUsersKey = 'allowed_users[]';
        console.log('Checking for allowed_users key:', allowedUsersKey, 'Exists:', data.hasOwnProperty(allowedUsersKey));
        
        if (data.hasOwnProperty(allowedUsersKey)) {
            console.log('Found allowed_users[] key, value:', data[allowedUsersKey], 'Type:', typeof data[allowedUsersKey], 'IsArray:', Array.isArray(data[allowedUsersKey]));
            // Ensure it's an array
            if (!Array.isArray(data[allowedUsersKey])) {
                data[allowedUsersKey] = data[allowedUsersKey] ? [data[allowedUsersKey]] : [];
                console.log('Converted to array:', data[allowedUsersKey]);
            }
            // Remove empty strings from array
            var originalLength = data[allowedUsersKey].length;
            data[allowedUsersKey] = data[allowedUsersKey].filter(function(val) {
                return val !== '' && val !== null && val !== undefined;
            });
            console.log('After filtering empty values:', data[allowedUsersKey], 'Original length:', originalLength, 'New length:', data[allowedUsersKey].length);
            // Rename to allowed_users (without brackets) for controller
            data['allowed_users'] = data[allowedUsersKey];
            delete data[allowedUsersKey];
            console.log('Renamed to allowed_users:', data['allowed_users']);
        } else {
            // If field doesn't exist in form data (all users removed), add it as empty array
            console.log('allowed_users[] not found in form data, adding as empty array');
            data['allowed_users'] = [];
        }
        
        console.log('Data before wrapping:', data);
        console.log('allowed_users in data:', data['allowed_users']);

        // Check if this is an update action (contains /update)
        if (action && action.includes('/update')) {
            // Extract session ID from the action URL
            const sessionIdMatch = action.match(/\/sessions\/(\d+)\/update/);
            console.log('Update action detected, sessionIdMatch:', sessionIdMatch);
            if (sessionIdMatch && sessionIdMatch[1]) {
                const sessionId = sessionIdMatch[1];
                console.log('Session ID extracted:', sessionId);
                // Wrap data in ajax[session_id] format as expected by the controller
                const wrappedData = {
                    ajax: {}
                };
                wrappedData.ajax[sessionId] = data;
                data = wrappedData;
                // Debug: Log the wrapped data
                console.log('Form data after wrapping:', data);
                console.log('Wrapped allowed_users:', data.ajax[sessionId]['allowed_users']);
            }
        }
        
        console.log('=== FINAL DATA BEING SENT ===');
        console.log(JSON.stringify(data, null, 2));

        $this.addClass('loadingbar primary').prop('disabled', true);
        form.find('input').removeClass('is-invalid');
        form.find('textarea').removeClass('is-invalid');

        $.post(action, data, function (result) {
            if (result && result.code === 200) {
                //window.location.reload();
                Swal.fire({
                    icon: 'success',
                    html: '<h3 class="font-20 text-center text-dark-blue py-25">' + saveSuccessLang + '</h3>',
                    showConfirmButton: false,
                    width: '25rem',
                });

                setTimeout(() => {
                    window.location.reload();
                }, 500)
            }
        }).fail(err => {
            $this.removeClass('loadingbar primary').prop('disabled', false);
            var errors = err.responseJSON;

            if (errors && errors.status === 'zoom_jwt_token_invalid') {
                Swal.fire({
                    icon: 'error',
                    html: '<h3 class="font-20 text-center text-dark-blue py-25">' + zoomJwtTokenInvalid + '</h3>',
                    showConfirmButton: false,
                    width: '25rem',
                });
            }

            if (errors && errors.errors) {
                Object.keys(errors.errors).forEach((key) => {
                    const error = errors.errors[key];
                    let element = form.find('.js-ajax-' + key);

                    if (key === 'zoom-not-complete-alert') {
                        form.find('.js-zoom-not-complete-alert').removeClass('d-none');
                    } else {
                        element.addClass('is-invalid');
                        element.parent().find('.invalid-feedback').text(error[0]);
                    }
                });
            }
        })
    }

    $('body').on('click', '.save-chapter', function (e) {
        e.preventDefault();
        const $this = $(this);
        let form = $this.closest('.chapter-form');

        handleWebinarItemForm(form, $this);
    });


    $('body').on('click', '.js-add-chapter', function (e) {
        const $this = $(this);

        const webinarId = $this.attr('data-webinar-id');
        const type = $this.attr('data-type');
        const itemId = $this.attr('data-chapter');
        const locale = $this.attr('data-locale');

        const random = itemId ? itemId : randomString();

        var clone = $('#chapterModalHtml').clone();
        clone.removeClass('d-none');
        var cloneHtml = clone.prop('innerHTML');
        cloneHtml = cloneHtml.replaceAll('record', random);

        clone.html('<div id="chapterModal' + random + '">' + cloneHtml + '</div>');

        Swal.fire({
            html: clone,
            showCancelButton: false,
            showConfirmButton: false,
            customClass: {
                content: 'p-0 text-left',
            },
            width: '36rem',
            onOpen: function () {

                const modal = $('#chapterModal' + random);

                modal.find('input.js-chapter-webinar-id').val(webinarId);
                modal.find('input.js-chapter-type').val(type);

                if (itemId) {
                    modal.find('.section-title').text(editChapterLang);

                    const path = '/admin/chapters/' + itemId + '/update';
                    modal.find('.chapter-form').attr('data-action', path);

                    $.get('/admin/chapters/' + itemId + '?locale=' + locale, function (result) {
                        if (result && result.chapter) {
                            modal.find('.js-ajax-title').val(result.chapter.title);

                            const status = modal.find('.js-chapter-status-switch');
                            if (result.chapter.status === 'active') {
                                status.prop('checked', true);
                            } else {
                                status.prop('checked', false);
                            }

                            const checkedAllContents = (result.chapter.check_all_contents_pass && result.chapter.check_all_contents_pass !== "0");
                            modal.find('.js-chapter-check-all-contents-pass').prop('checked', checkedAllContents);

                            var localeSelect = modal.find('.js-chapter-locale');
                            localeSelect.val(locale);
                            localeSelect.addClass('js-webinar-content-locale');
                            localeSelect.attr('data-id', itemId);
                        }
                    })
                }
            }
        });
    });

    $('body').on('click', '.js-add-course-content-btn, .add-new-interactive-file-btn', function (e) {
        e.preventDefault();
        const $this = $(this);
        const type = $this.attr('data-type');
        const chapterId = $this.attr('data-chapter');

        const contentTagId = '#chapterContentAccordion' + chapterId;
        const key = randomString();
        var html = '';

        switch (type) {
            case 'file':
                const newFileForm = $('#newFileForm');
                newFileForm.find('.chapter-input').val(chapterId);
                html = newFileForm.html();

                html = html.replace(/record/g, key);

                $(contentTagId).prepend(html);

                // Initialize Select2 for new file form
                $(contentTagId).find('.select2').each(function() {
                    var $this = $(this);
                    if ($this.attr('name') && $this.attr('name').includes('allowed_users')) {
                        // Get selected user IDs from existing options
                        var selectedUserIds = [];
                        $this.find('option:selected').each(function() {
                            var userId = $(this).val();
                            if (userId) {
                                selectedUserIds.push(userId);
                            }
                        });
                        
                        // Initialize with AJAX search for user selection
                        var select2Config = {
                            multiple: true,
                            width: '100%',
                            placeholder: 'Type to search users...',
                            allowClear: true,
                            closeOnSelect: false,
                            minimumInputLength: 0,
                            // Fix dropdown visibility when inside overlays/collapses
                            dropdownParent: $this.closest('.swal2-container, .modal, .card-body, body'),
                            language: {
                                inputTooShort: function () { return ''; }
                            },
                            ajax: {
                                url: '/admin/webinars/search-users',
                                dataType: 'json',
                                delay: 250,
                                cache: false,
                                data: function (params) {
                                    return {
                                        q: params.term,
                                        page: params.page || 1
                                    };
                                },
                                processResults: function (data, params) {
                                    return {
                                        results: data
                                    };
                                },
                                error: function(xhr){
                                    console.error('User search error', xhr.status, xhr.responseText);
                                },
                                cache: true
                            },
                            templateResult: select2UserTemplates().templateResult,
                            templateSelection: select2UserTemplates().templateSelection
                        };
                        
                        // If there are selected users, fetch their details and pre-load them
                        if (selectedUserIds.length > 0) {
                            $.ajax({
                                url: '/admin/webinars/get-users-by-ids',
                                dataType: 'json',
                                data: { ids: selectedUserIds },
                                success: function(users) {
                                    // Add users as options
                                    users.forEach(function(user) {
                                        var option = new Option(user.text, user.id, true, true);
                                        $this.append(option);
                                    });
                                    
                                // Now initialize Select2 with the pre-loaded options
                                $this.select2(select2Config);
                                $this.trigger('change');
                                $this.one('select2:open', function(){
                                    if ($this.data('initial-users-loaded')) return;
                                    $.ajax({
                                        url: '/admin/webinars/search-users',
                                        dataType: 'json',
                                        data: { q: '', page: 1 },
                                        success: function(list){
                                            (list || []).forEach(function(u){
                                                if ($this.find('option[value="' + u.id + '"]').length === 0) {
                                                    var opt = new Option(u.text, u.id, false, false);
                                                    $this.append(opt);
                                                }
                                            });
                                            $this.data('initial-users-loaded', true);
                                        }
                                    });
                                });
                                },
                                error: function(xhr) {
                                    console.error('Error loading selected users', xhr);
                                    // Initialize anyway without pre-loaded users
                                $this.select2(select2Config);
                                $this.one('select2:open', function(){
                                    if ($this.data('initial-users-loaded')) return;
                                    $.ajax({
                                        url: '/admin/webinars/search-users',
                                        dataType: 'json',
                                        data: { q: '', page: 1 },
                                        success: function(list){
                                            (list || []).forEach(function(u){
                                                if ($this.find('option[value="' + u.id + '"]').length === 0) {
                                                    var opt = new Option(u.text, u.id, false, false);
                                                    $this.append(opt);
                                                }
                                            });
                                            $this.data('initial-users-loaded', true);
                                        }
                                    });
                                });
                                }
                            });
                        } else {
                            // No selected users, initialize normally
                        $this.select2(select2Config);
                        $this.one('select2:open', function(){
                            if ($this.data('initial-users-loaded')) return;
                            $.ajax({
                                url: '/admin/webinars/search-users',
                                dataType: 'json',
                                data: { q: '', page: 1 },
                                success: function(list){
                                    (list || []).forEach(function(u){
                                        if ($this.find('option[value="' + u.id + '"]').length === 0) {
                                            var opt = new Option(u.text, u.id, false, false);
                                            $this.append(opt);
                                        }
                                    });
                                    $this.data('initial-users-loaded', true);
                                }
                            });
                        });
                        }
                    } else {
                        $this.select2({
                            width: '100%',
                            placeholder: function() {
                                return $(this).data('placeholder') || 'Select...';
                            },
                            allowClear: true,
                            closeOnSelect: false
                        });
                    }
                });

                break;
            case 'new_interactive_file':
                const newInteractiveFileForm = $('#newInteractiveFileForm');
                newInteractiveFileForm.find('.chapter-input').val(chapterId);
                html = newInteractiveFileForm.html();

                html = html.replace(/record/g, key);

                $(contentTagId).prepend(html);

                break;
            case 'session':
                const newSessionForm = $('#newSessionForm');
                newSessionForm.find('.chapter-input').val(chapterId);
                html = newSessionForm.html();

                html = html.replace(/record/g, key);

                $(contentTagId).prepend(html);

                // Initialize Select2 for new session form
                $(contentTagId).find('.select2').each(function() {
                    var $this = $(this);
                    if ($this.attr('name') && $this.attr('name').includes('allowed_users')) {
                        $this.select2({
                            multiple: true,
                            width: '100%',
                            placeholder: function() {
                                return $(this).data('placeholder') || 'Select users...';
                            },
                            allowClear: true,
                            closeOnSelect: false
                        });
                    } else {
                        $this.select2({
                            width: '100%',
                            placeholder: function() {
                                return $(this).data('placeholder') || 'Select...';
                            },
                            allowClear: true,
                            closeOnSelect: false
                        });
                    }
                });

                break;
            case 'text_lesson':
                const newTextLessonForm = $('#newTextLessonForm');
                newTextLessonForm.find('.chapter-input').val(chapterId);
                html = newTextLessonForm.html();

                html = html.replace(/record/g, key);

                html = html.replaceAll('attachments-select2', 'attachments-select2-' + key);
                html = html.replaceAll('js-content-summernote', 'js-content-summernote-' + key);
                html = html.replaceAll('js-hidden-content-summernote', 'js-hidden-content-summernote-' + key);

                $(contentTagId).prepend(html);

                $('.attachments-select2-' + key).select2({
                    multiple: true,
                    width: '100%',
                });

                $('.js-content-summernote-' + key).summernote({
                    tabsize: 2,
                    height: 400,
                    callbacks: {
                        onChange: function (contents, $editable) {
                            $('.js-hidden-content-summernote-' + key).val(contents);
                        }
                    }
                });

                // Initialize Select2 for new text lesson form
                $(contentTagId).find('.select2').each(function() {
                    var $this = $(this);
                    if ($this.attr('name') && $this.attr('name').includes('allowed_users')) {
                        $this.select2({
                            multiple: true,
                            width: '100%',
                            placeholder: function() {
                                return $(this).data('placeholder') || 'Select users...';
                            },
                            allowClear: true,
                            closeOnSelect: false
                        });
                    } else {
                        $this.select2({
                            width: '100%',
                            placeholder: function() {
                                return $(this).data('placeholder') || 'Select...';
                            },
                            allowClear: true,
                            closeOnSelect: false
                        });
                    }
                });

                break;

            case 'assignment':
                const newAssignmentForm = $('#newAssignmentForm');
                newAssignmentForm.find('.chapter-input').val(chapterId);
                html = newAssignmentForm.html();

                html = html.replace(/record/g, key);

                $(contentTagId).prepend(html);
                break;

            case 'quiz':
                const newQuizForm = $('#newQuizForm');
                newQuizForm.find('.chapter-input').val(chapterId);
                html = newQuizForm.html();

                html = html.replace(/record/g, key);

                $(contentTagId).prepend(html);
                break;
        }

        resetDatePickers();
        feather.replace();
    });

    $('body').on('click', '.js-change-content-chapter', function (e) {
        e.preventDefault();
        const $this = $(this);
        const itemId = $this.attr('data-item-id');
        const itemType = $this.attr('data-item-type');
        const chapterId = $this.attr('data-chapter-id');

        const random = randomString();

        var clone = $('#changeChapterModalHtml').clone();
        clone.removeClass('d-none');
        var cloneHtml = clone.prop('innerHTML');

        clone.html('<div id="changeChapterModalHtml' + random + '">' + cloneHtml + '</div>');

        Swal.fire({
            html: clone,
            showCancelButton: false,
            showConfirmButton: false,
            customClass: {
                content: 'p-0 text-left',
            },
            width: '36rem',
            onOpen: function () {

                const modal = $('#changeChapterModalHtml' + random);

                modal.find('input.js-item-id').val(itemId);
                modal.find('input.js-item-type').val(itemType);
                modal.find('.js-ajax-chapter_id').val(chapterId).change();
            }
        });
    });

    $('body').on('click', '.save-change-chapter', function (e) {
        e.preventDefault();
        const $this = $(this);
        let form = $this.closest('.change-chapter-form');

        handleWebinarItemForm(form, $this);
    });

    // ======
    // contents files
    function handleShowFileInputsBySource($form, source, fileType) {
        const featherIconsConf = {width: 20, height: 20};
        let icon = feather.icons['upload'].toSvg(featherIconsConf);

        const $fileTypeVolumeInputs = $form.find('.js-file-type-volume');
        const $downloadableInput = $form.find('.js-downloadable-input');
        const $onlineViewerInput = $form.find('.js-online_viewer-input');

        const $filePathInputGroup = $form.find('.js-file-path-input');
        const $s3FilePathInputGroup = $form.find('.js-s3-file-path-input');
        const $filePathButton = $form.find('.js-file-path-input button');
        const $filePathInput = $form.find('.js-file-path-input input');

        $filePathButton.addClass('panel-file-manager');
        $filePathInputGroup.removeClass('d-none');
        $s3FilePathInputGroup.addClass('d-none');

        switch (source) {
            case 'youtube':
            case 'vimeo':
            case 'iframe':
                $fileTypeVolumeInputs.addClass('d-none');
                $downloadableInput.find('input').prop('checked', false);
                $downloadableInput.addClass('d-none');

                $onlineViewerInput.find('input').prop('checked', false);
                $onlineViewerInput.addClass('d-none');

                icon = feather.icons['link'].toSvg(featherIconsConf);
                $filePathButton.removeClass('panel-file-manager');

                break;

            case 'external_link':
            case 's3':
                $fileTypeVolumeInputs.removeClass('d-none');

                if (fileType && fileType === 'video') {
                    $downloadableInput.removeClass('d-none');
                } else {
                    $downloadableInput.find('input').prop('checked', false);
                    $downloadableInput.addClass('d-none');
                }

                if (source === 'external_link') {
                    icon = feather.icons['external-link'].toSvg(featherIconsConf);
                    $filePathButton.removeClass('panel-file-manager');
                } else if (source === 's3') {
                    $filePathInputGroup.addClass('d-none');
                    $s3FilePathInputGroup.removeClass('d-none');
                }

                if (fileType && (fileType === 'pdf')) {
                    $onlineViewerInput.removeClass('d-none');
                } else {
                    $onlineViewerInput.find('input').prop('checked', false);
                    $onlineViewerInput.addClass('d-none');
                }

                break;

            case 'google_drive':
                $fileTypeVolumeInputs.removeClass('d-none');
                $downloadableInput.find('input').prop('checked', false);
                $downloadableInput.addClass('d-none');

                if (fileType && (fileType === 'pdf')) {
                    $onlineViewerInput.removeClass('d-none');
                } else {
                    $onlineViewerInput.find('input').prop('checked', false);
                    $onlineViewerInput.addClass('d-none');
                }

                icon = feather.icons['box'].toSvg(featherIconsConf);
                $filePathButton.removeClass('panel-file-manager');

                break;

            case 'upload':
                $fileTypeVolumeInputs.removeClass('d-none');
                $downloadableInput.removeClass('d-none');

                if (fileType && (fileType === 'pdf')) {
                    $onlineViewerInput.removeClass('d-none');
                } else {
                    $onlineViewerInput.find('input').prop('checked', false);
                    $onlineViewerInput.addClass('d-none');
                }
        }

        if (icon) {
            $filePathButton.html(icon);
        }

        if (filePathPlaceHolderBySource) {
            $filePathInput.attr('placeholder', filePathPlaceHolderBySource[source]);
        }

    }

    $('body').on('click', '.js-save-file', function (e) {
        e.preventDefault();
        const $this = $(this);
        let form = $this.closest('.file-form');

        handleFileFormSubmit(form, $this);
    });

    $('body').on('change', '.js-file-storage', function (e) {
        e.preventDefault();

        const value = this.value;
        const formGroup = $(this).closest('form');
        const fileType = formGroup.find('.js-ajax-file_type').val();

        handleShowFileInputsBySource(formGroup, value, fileType);
    });

    $('body').on('change', '.js-ajax-file_type', function (e) {
        e.preventDefault();

        const value = $(this).val();
        const formGroup = $(this).closest('form');
        const source = formGroup.find('.js-file-storage').val();

        handleShowFileInputsBySource(formGroup, source, value);
    });

    // Sessions
    $('body').on('change', '.js-api-input', function (e) {
        e.preventDefault();

        const sessionForm = $(this).closest('.session-form');
        const value = this.value;

        sessionForm.find('.js-zoom-not-complete-alert').addClass('d-none');
        sessionForm.find('.js-agora-chat-and-rec').addClass('d-none');

        if (value === 'big_blue_button') {
            sessionForm.find('.js-local-link').addClass('d-none');
            sessionForm.find('.js-api-secret').removeClass('d-none');
            sessionForm.find('.js-moderator-secret').removeClass('d-none');
        } else if (value === 'zoom') {
            sessionForm.find('.js-local-link').addClass('d-none');
            sessionForm.find('.js-api-secret').addClass('d-none');
            sessionForm.find('.js-moderator-secret').addClass('d-none');

            if (hasZoomApiToken && hasZoomApiToken !== 'true') {
                sessionForm.find('.js-zoom-not-complete-alert').removeClass('d-none');
            }
        } else if (value === 'agora') {
            sessionForm.find('.js-agora-chat-and-rec').removeClass('d-none');
            sessionForm.find('.js-api-secret').addClass('d-none');
            sessionForm.find('.js-local-link').addClass('d-none');
            sessionForm.find('.js-moderator-secret').addClass('d-none');
        } else {
            sessionForm.find('.js-local-link').removeClass('d-none');
            sessionForm.find('.js-api-secret').removeClass('d-none');
            sessionForm.find('.js-moderator-secret').addClass('d-none');
        }
    });

    $('body').on('click', '.js-save-session', function (e) {
        e.preventDefault();
        const $this = $(this);
        let form = $this.closest('.session-form');

        handleWebinarItemForm(form, $this);
    });

    $('body').on('click', '.js-session-has-ended', function () {

        $.toast({
            heading: requestFailedLang,
            text: thisLiveHasEndedLang,
            bgColor: '#f63c3c',
            textColor: 'white',
            hideAfter: 10000,
            position: 'bottom-right',
            icon: 'error'
        });
    });

    // Text lession
    $('body').on('click', '.js-save-text_lesson', function (e) {
        e.preventDefault();
        const $this = $(this);
        let form = $this.closest('.text_lesson-form');

        handleWebinarItemForm(form, $this);
    });

    // assignments

    $('body').on('click', '.js-save-assignment', function (e) {
        e.preventDefault();
        const $this = $(this);
        let form = $this.closest('.assignment-form');

        handleWebinarItemForm(form, $this);
    });

    $('body').on('click', '.assignment-attachments-add-btn', function (e) {
        var $container = $(this).closest('.js-assignment-attachments-items');
        var mainRow = $container.find('.assignment-attachments-main-row');

        var copy = mainRow.clone();
        copy.removeClass('assignment-attachments-main-row');
        copy.removeClass('d-none');

        const removeBtn = copy.find('.assignment-attachments-remove-btn');

        if (removeBtn) {
            removeBtn.removeClass('d-none');
        }

        var copyHtml = copy.prop('innerHTML');
        copyHtml = copyHtml.replaceAll('assignmentTemp', randomString());
        copyHtml = copyHtml.replaceAll('btn-primary', 'btn-danger');
        copyHtml = copyHtml.replaceAll('assignment-attachments-add-btn', 'assignment-attachments-remove-btn');

        copy.html(copyHtml);
        $container.append(copy);
    });

    $('body').on('click', '.assignment-attachments-remove-btn', function (e) {
        e.preventDefault();
        $(this).closest('.js-ajax-attachments').remove();
    });

    /*
    * ./ Contents
    * */

    $('body').on('click', '.cancel-accordion', function (e) {
        e.preventDefault();

        $(this).closest('.accordion-row').remove();
    });



    /**
     * add webinar prerequisites
     * */
    $('body').on('click', '#webinarAddPrerequisites', function (e) {
        e.preventDefault();
        let add_prerequisites_modal = '<div id="addPrerequisitesModal">';
        add_prerequisites_modal += $('#webinarPrerequisitesModal').html();
        add_prerequisites_modal += '</div>';
        add_prerequisites_modal = add_prerequisites_modal.replaceAll('prerequisites-select', 'prerequisites-select2');
        add_prerequisites_modal = add_prerequisites_modal.replaceAll('str_', '');

        Swal.fire({
            html: add_prerequisites_modal,
            showCancelButton: false,
            showConfirmButton: false,
            customClass: {
                content: 'p-0 text-left',
            },
            width: '48rem',
            onOpen: () => {
                $('.prerequisites-select2').select2({
                    placeholder: $(this).data('placeholder'),
                    minimumInputLength: 3,
                    allowClear: true,
                    ajax: {
                        url: '/admin/webinars/search',
                        dataType: 'json',
                        type: "POST",
                        quietMillis: 50,
                        data: function (params) {
                            var queryParameters = {
                                term: params.term,
                                webinar_id: $(this).data('webinar-id')
                            }
                            return queryParameters;
                        },
                        processResults: function (data) {
                            return {
                                results: $.map(data, function (item) {
                                    return {
                                        text: item.title,
                                        id: item.id
                                    }
                                })
                            };
                        }
                    }
                });
            },
        });
    });

    $('body').on('click', '#savePrerequisites', function (e) {
        e.preventDefault();
        const $this = $(this);
        let form = $('#addPrerequisitesModal form');
        handleWebinarItemForm(form, $this);
    });

    /**
     * add webinar FAQ
     * */
    $('body').on('click', '#webinarAddFAQ', function (e) {
        e.preventDefault();
        let add_faq_modal = '<div id="addFAQsModal">';
        add_faq_modal += $('#webinarFaqModal').html();
        add_faq_modal += '</div>';

        Swal.fire({
            html: add_faq_modal,
            showCancelButton: false,
            showConfirmButton: false,
            customClass: {
                content: 'p-0 text-left',
            },
            width: '48rem',
        });
    });

    $('body').on('click', '#saveFAQ', function (e) {
        e.preventDefault();
        const $this = $(this);
        let form = $('#addFAQsModal form');
        handleWebinarItemForm(form, $this);
    });

    /*
    * add extra description
    * */
    $('body').on('click', '#add_new_learning_materials', function (e) {
        e.preventDefault();
        const key = randomString();

        let html = '<div id="extraDescriptionModal">';
        html += $('#extraDescriptionForm').html();
        html += '</div>';

        Swal.fire({
            html: html,
            showCancelButton: false,
            showConfirmButton: false,
            customClass: {
                content: 'p-0 text-left',
            },
            width: '48rem',
            onOpen: function () {
                $('#extraDescriptionModal input[name="type"]').val('learning_materials')
            }
        });
    });

    function handleCompanyLogosInputHtml(key) {
        let html = '<div id="extraDescriptionModal">';
        html += $('#extraDescriptionForm').html();
        html += '</div>';

        var modalHtml = $(html);
        modalHtml.find('.js-form-groups').children().remove();
        modalHtml.find('.js-form-groups').append('<div class="form-group">\n' +
            '            <label class="input-label">image</label>\n' +
            '            <div class="input-group">\n' +
            '                <div class="input-group-prepend">\n' +
            '                    <button type="button" class="input-group-text admin-file-manager" data-input="image_' + key + '" data-preview="holder">\n' +
            '                        <i class="fa fa-upload"></i>\n' +
            '                    </button>\n' +
            '                </div>\n' +
            '                <input type="text" name="value" id="image_' + key + '" class="form-control"/>\n' +
            '            </div>\n' +
            '        </div>');

        var mainHtml = '<div id="extraDescriptionModal">';
        mainHtml += modalHtml.html();
        mainHtml += '</div>';

        return mainHtml;
    }

    $('body').on('click', '#add_new_company_logos', function (e) {
        e.preventDefault();
        const key = randomString();
        var html = handleCompanyLogosInputHtml(key)

        Swal.fire({
            html: html,
            showCancelButton: false,
            showConfirmButton: false,
            customClass: {
                content: 'p-0 text-left',
            },
            width: '48rem',
            onOpen: function () {
                $('#extraDescriptionModal input[name="type"]').val('company_logos')
            }
        });
    });

    $('body').on('click', '#add_new_requirements', function (e) {
        e.preventDefault();
        const key = randomString();

        let html = '<div id="extraDescriptionModal">';
        html += $('#extraDescriptionForm').html();
        html += '</div>';

        Swal.fire({
            html: html,
            showCancelButton: false,
            showConfirmButton: false,
            customClass: {
                content: 'p-0 text-left',
            },
            width: '48rem',
            onOpen: function () {
                $('#extraDescriptionModal input[name="type"]').val('requirements')
            }
        });
    });

    $('body').on('click', '#saveExtraDescription', function (e) {
        e.preventDefault();
        const $this = $(this);
        let form = $('#extraDescriptionModal form');
        handleWebinarItemForm(form, $this);
    });

    $('body').on('click', '.edit-extraDescription', function (e) {
        e.preventDefault();
        const $this = $(this);

        editExtraDescription($this);
    });

    $('body').on('change', '.js-edit-extraDescription-locale-ajax', function (e) {
        e.preventDefault();
        const $this = $(this);
        const locale = $this.val();

        editExtraDescription($this, locale);
    });

    function editExtraDescription($this, locale) {
        const item_id = $this.attr('data-item-id');
        const webinar_id = $this.attr('data-webinar-id');

        const rendomKey = randomString();

        const edit_data = {
            item_id: webinar_id,
            locale: locale
        };

        $.post('/admin/webinar-extra-description/' + item_id + '/edit', edit_data, function (result) {
            if (result && result.webinarExtraDescription) {
                const webinarExtraDescription = result.webinarExtraDescription;

                let html = '<div id="extraDescriptionModal">';
                html += $('#extraDescriptionForm').html();
                html += '</div>';

                if (webinarExtraDescription.type === 'company_logos') {
                    html = handleCompanyLogosInputHtml(rendomKey);
                }

                html = html.replaceAll('/admin/webinar-extra-description/store', '/admin/webinar-extra-description/' + item_id + '/update');

                Swal.fire({
                    html: html,
                    showCancelButton: false,
                    showConfirmButton: false,
                    customClass: {
                        content: 'p-0 text-left',
                    },
                    width: '48rem',
                    onOpen: () => {
                        var $modal = $('#extraDescriptionModal');

                        Object.keys(webinarExtraDescription).forEach(key => {
                            $modal.find('[name="' + key + '"]').val(webinarExtraDescription[key]);
                        });

                        var localeSelect = $modal.find('select[name="locale"]');

                        if (localeSelect) {
                            localeSelect.addClass('js-edit-extraDescription-locale-ajax');
                            localeSelect.attr('data-item-id', item_id);
                            localeSelect.attr('data-webinar-id', webinar_id);
                        }
                    }
                });
            }
        });
    }

    /**
     * add webinar Quiz
     * */
    $('body').on('click', '#webinarAddQuiz', function (e) {
        e.preventDefault();
        let add_quiz_modal = '<div id="addQuizModal">';
        add_quiz_modal += $('#quizzesModal').html();
        add_quiz_modal += '</div>';
        add_quiz_modal = add_quiz_modal.replaceAll('quiz-select2', 'quiz-select22');

        Swal.fire({
            html: add_quiz_modal,
            showCancelButton: false,
            showConfirmButton: false,
            customClass: {
                content: 'p-0 text-left',
            },
            width: '30rem',
            onOpen: () => {
                $(".quiz-select22").select2({
                    placeholder: $(this).data('placeholder'),
                    allowClear: true,
                    width: '100%',
                });
            }
        });
    });

    $('body').on('click', '#saveQuiz', function (e) {
        e.preventDefault();
        const $this = $(this);
        let form = $('#addQuizModal form');
        handleWebinarItemForm(form, $this);
    });

    /*
    * edit ticket
    * */

    function editTicket($this, locale = null) {
        const ticket_id = $this.attr('data-ticket-id');
        const webinar_id = $this.attr('data-webinar-id');

        const edit_data = {
            item_id: webinar_id,
            locale: locale,
        };

        $.post('/admin/tickets/' + ticket_id + '/edit', edit_data, function (result) {
            if (result && result.ticket) {
                const ticket = result.ticket;

                let edit_ticket_modal = '<div id="addTicketModal">';
                edit_ticket_modal += $('#webinarTicketModal').html();
                edit_ticket_modal += '</div>';
                edit_ticket_modal = edit_ticket_modal.replaceAll('/admin/tickets/store', '/admin/tickets/' + ticket_id + '/update');

                Swal.fire({
                    html: edit_ticket_modal,
                    showCancelButton: false,
                    showConfirmButton: false,
                    customClass: {
                        content: 'p-0 text-left',
                    },
                    width: '48rem',
                    onOpen: () => {
                        if (jQuery().daterangepicker) {
                            $('.date-range-picker').daterangepicker({
                                locale: {format: 'YYYY-MM-DD'},
                                drops: 'down',
                                opens: 'right',
                                startDate: moment(ticket.start_date * 1000).toDate(),
                                endDate: moment(ticket.end_date * 1000).toDate(),
                            });
                        }
                        delete ticket.start_date;
                        delete ticket.end_date;

                        Object.keys(ticket).forEach(key => {
                            $('#addTicketModal').find('[name="' + key + '"]').val(ticket[key]);
                        });

                        var localeSelect = $('#addTicketModal').find('select[name="locale"]');

                        if (localeSelect) {
                            localeSelect.addClass('js-edit-ticket-locale-ajax');
                            localeSelect.attr('data-ticket-id', ticket_id);
                            localeSelect.attr('data-webinar-id', webinar_id);
                        }
                    }
                });
            }
        });
    }

    $('body').on('click', '.edit-ticket', function (e) {
        e.preventDefault();
        const $this = $(this);

        loadingSwl();

        editTicket($this);
    });

    $('body').on('change', '.js-edit-ticket-locale-ajax', function (e) {
        e.preventDefault();
        const $this = $(this);

        const locale = $this.val();

        editTicket($this, locale);
    });

    /*
    * edit session
    * */

    function editChapter($this, locale = null) {
        const chapter_id = $this.attr('data-chapter-id');
        const webinar_id = $this.attr('data-webinar-id');

        const edit_data = {
            item_id: webinar_id,
            locale: locale,
        };

        $.post('/admin/chapters/' + chapter_id + '/edit', edit_data, function (result) {
            if (result && result.chapter) {
                const chapter = result.chapter;

                let html = '<div id="editChapterModal">';
                html += $('#webinarChapterModal').html();
                html += '</div>';

                html = html.replaceAll('/admin/chapters/store', '/admin/chapters/' + chapter_id + '/update');
                const nameId = randomString();
                html = html.replaceAll('record', nameId);

                Swal.fire({
                    html: html,
                    showCancelButton: false,
                    showConfirmButton: false,
                    customClass: {
                        content: 'p-0 text-left',
                    },
                    width: '48rem',
                    onOpen: () => {
                        var $modal = $('#editChapterModal');

                        Object.keys(chapter).forEach(key => {
                            if (key === 'status') {
                                const checked = (chapter.status === 'active');

                                $modal.find('[name="' + key + '"]').prop('checked', checked)
                            } else if (key === 'check_all_contents_pass') {
                                const checkedAllContents = (chapter.check_all_contents_pass && chapter.check_all_contents_pass !== "0");
                                $modal.find('[name="' + key + '"]').prop('checked', checkedAllContents)
                            } else {
                                $modal.find('[name="' + key + '"]').val(chapter[key]);
                            }
                        });

                        var localeSelect = $modal.find('select[name="locale"]');

                        if (localeSelect) {
                            localeSelect.addClass('js-edit-chapter-locale-ajax');
                            localeSelect.attr('data-chapter-id', chapter_id);
                            localeSelect.attr('data-webinar-id', webinar_id);
                        }
                    }
                });
            }
        });
    }

    $('body').on('click', '.edit-chapter', function (e) {
        e.preventDefault();
        const $this = $(this);

        loadingSwl();

        editChapter($this);
    });

    $('body').on('change', '.js-edit-chapter-locale-ajax', function (e) {
        e.preventDefault();
        const $this = $(this);
        const locale = $this.val();

        editChapter($this, locale);
    });

    /*
    * edit session
    * */

    function editSession($this, locale = null) {
        const session_id = $this.attr('data-session-id');
        const webinar_id = $this.attr('data-webinar-id');

        const edit_data = {
            item_id: webinar_id,
            locale: locale
        };

        $.post('/admin/sessions/' + session_id + '/edit', edit_data, function (result) {
            if (result && result.session) {
                const session = result.session;

                let edit_session_modal = '<div id="addSessionModal">';
                edit_session_modal += $('#webinarSessionModal').html();
                edit_session_modal += '</div>';
                edit_session_modal = edit_session_modal.replaceAll('/admin/sessions/store', '/admin/sessions/' + session_id + '/update');
                const nameId = randomString();
                edit_session_modal = edit_session_modal.replaceAll('record', nameId);
                // Set form action and data-action attribute
                edit_session_modal = edit_session_modal.replace(/action="[^"]*"/, 'action="/admin/sessions/' + session_id + '/update"');
                // Add data-action attribute if it doesn't exist
                if (!edit_session_modal.includes('data-action')) {
                    edit_session_modal = edit_session_modal.replace(/<form[^>]*>/, '<form action="/admin/sessions/' + session_id + '/update" method="post" class="session-form" data-action="/admin/sessions/' + session_id + '/update">');
                } else {
                    edit_session_modal = edit_session_modal.replace(/data-action="[^"]*"/, 'data-action="/admin/sessions/' + session_id + '/update"');
                }

                Swal.fire({
                    html: edit_session_modal,
                    showCancelButton: false,
                    showConfirmButton: false,
                    customClass: {
                        content: 'p-0 text-left',
                    },
                    width: '48rem',
                    onOpen: () => {
                        var $modal = $('#addSessionModal');

                        var datetimepicker = $('.datetimepicker');
                        datetimepicker.val(session.date);
                        if (jQuery().daterangepicker) {
                            datetimepicker.daterangepicker({
                                locale: {format: 'YYYY-MM-DD HH:mm'},
                                singleDatePicker: true,
                                timePicker: true,
                                timePicker24Hour: true,
                            });
                        }
                        delete session.date;

                        Object.keys(session).forEach(key => {
                            if (key === 'session_api') {
                                var apiInput = $modal.find('.js-api-input[value="' + session[key] + '"]');
                                apiInput.prop('checked', true);

                                $modal.find('.js-api-input').prop('disabled', true);

                                if (session[key] !== 'local') {
                                    $modal.find('.js-ajax-api_secret').prop('disabled', true);
                                    $modal.find('.js-ajax-date').prop('disabled', true);
                                    $modal.find('.js-ajax-duration').prop('disabled', true);
                                    $modal.find('.js-ajax-link').prop('disabled', true);
                                }

                                if (session[key] === 'big_blue_button') {
                                    $modal.find('.js-moderator-secret').removeClass('d-none');
                                    $modal.find('.js-ajax-moderator_secret').prop('disabled', true);
                                } else if (session[key] === 'zoom') {
                                    $modal.find('.js-local-link').addClass('d-none');
                                    $modal.find('.js-api-secret').addClass('d-none');
                                    $modal.find('.js-moderator-secret').addClass('d-none');
                                } else if (session[key] === 'agora') {
                                    $modal.find('.js-agora-chat-and-rec').removeClass('d-none');
                                    $modal.find('.js-api-secret').addClass('d-none');
                                    $modal.find('.js-local-link').addClass('d-none');
                                    $modal.find('.js-moderator-secret').addClass('d-none');
                                }

                            } else if (key === 'status') {
                                const checked = (session.status === 'active');

                                $modal.find('[name="' + key + '"]').prop('checked', checked);
                            } else if (key === 'check_previous_parts' || key === 'access_after_day') {
                                const sequenceContentSwitchChecked = (session.check_previous_parts || session.access_after_day !== null);

                                if (sequenceContentSwitchChecked) {
                                    $modal.find('.js-sequence-content-switch').prop('checked', true);
                                    $modal.find('[name="check_previous_parts"]').prop('checked', session.check_previous_parts);
                                    $modal.find('[name="access_after_day"]').val(session.access_after_day);
                                    $modal.find('.js-sequence-content-inputs').removeClass('d-none')
                                }
                            } else if (key === 'agora_settings') {
                                const agora_settings = JSON.parse(session.agora_settings);

                                if (agora_settings && agora_settings['chat'] && (agora_settings['chat'] === true || agora_settings['chat'] === 'true')) {
                                    $modal.find('[name="agora_chat"]').prop('checked', true)
                                }

                                if (agora_settings && agora_settings['record'] && (agora_settings['record'] === true || agora_settings['record'] === 'true')) {
                                    $modal.find('[name="agora_record"]').prop('checked', true)
                                }
                            } else if (key === 'allowed_users') {
                                // Handle allowed users - populate select2 with selected users
                                var $allowedUsersSelect = $modal.find('select[name="allowed_users[]"]');
                                if ($allowedUsersSelect.length && session.allowed_users && Array.isArray(session.allowed_users) && session.allowed_users.length > 0) {
                                    // Fetch user details and populate select2
                                    $.ajax({
                                        url: '/admin/webinars/get-users-by-ids',
                                        dataType: 'json',
                                        data: { ids: session.allowed_users },
                                        success: function(users) {
                                            // Clear existing selections
                                            $allowedUsersSelect.empty();
                                            
                                            // Add selected users as options
                                            users.forEach(function(user) {
                                                var option = new Option(user.text, user.id, true, true);
                                                $allowedUsersSelect.append(option);
                                            });
                                            
                                            // Initialize or update Select2
                                            if ($allowedUsersSelect.hasClass('select2-hidden-accessible')) {
                                                $allowedUsersSelect.select2('destroy');
                                            }
                                            
                                            $allowedUsersSelect.select2({
                                                multiple: true,
                                                width: '100%',
                                                placeholder: 'Type to search users...',
                                                allowClear: true,
                                                closeOnSelect: false,
                                                minimumInputLength: 0,
                                                dropdownParent: $allowedUsersSelect.closest('.swal2-container, .modal, body'),
                                                ajax: {
                                                    url: '/admin/webinars/search-users',
                                                    dataType: 'json',
                                                    delay: 250,
                                                    cache: false,
                                                    data: function (params) {
                                                        return {
                                                            q: params.term,
                                                            page: params.page || 1
                                                        };
                                                    },
                                                    processResults: function (data, params) {
                                                        return {
                                                            results: data
                                                        };
                                                    },
                                                    cache: true
                                                },
                                                templateResult: function(user) {
                                                    if (user.loading) {
                                                        return user.text;
                                                    }
                                                    return $('<div>').text(user.text);
                                                },
                                                templateSelection: function(user) {
                                                    return user.text;
                                                }
                                            });
                                            
                                            // Trigger change to ensure select2 recognizes the values
                                            $allowedUsersSelect.trigger('change');
                                            
                                            // Ensure values are properly set in the select element
                                            setTimeout(function() {
                                                var selectedValues = $allowedUsersSelect.val();
                                                if (selectedValues && selectedValues.length > 0) {
                                                    $allowedUsersSelect.val(selectedValues).trigger('change');
                                                }
                                            }, 100);
                                        },
                                        error: function(xhr) {
                                            console.error('Error loading allowed users:', xhr);
                                            // Initialize select2 anyway
                                            if (!$allowedUsersSelect.hasClass('select2-hidden-accessible')) {
                                                $allowedUsersSelect.select2({
                                                    multiple: true,
                                                    width: '100%',
                                                    placeholder: 'Type to search users...',
                                                    allowClear: true,
                                                    closeOnSelect: false,
                                                    minimumInputLength: 0,
                                                    dropdownParent: $allowedUsersSelect.closest('.swal2-container, .modal, body'),
                                                    ajax: {
                                                        url: '/admin/webinars/search-users',
                                                        dataType: 'json',
                                                        delay: 250,
                                                        cache: false,
                                                        data: function (params) {
                                                            return {
                                                                q: params.term,
                                                                page: params.page || 1
                                                            };
                                                        },
                                                        processResults: function (data, params) {
                                                            return {
                                                                results: data
                                                            };
                                                        },
                                                        cache: true
                                                    }
                                                });
                                            }
                                        }
                                    });
                                } else {
                                    // Initialize select2 even if no users are selected
                                    var $allowedUsersSelect = $modal.find('select[name="allowed_users[]"]');
                                    if (!$allowedUsersSelect.hasClass('select2-hidden-accessible')) {
                                        $allowedUsersSelect.select2({
                                            multiple: true,
                                            width: '100%',
                                            placeholder: 'Type to search users...',
                                            allowClear: true,
                                            closeOnSelect: false,
                                            minimumInputLength: 0,
                                            dropdownParent: $allowedUsersSelect.closest('.swal2-container, .modal, body'),
                                            ajax: {
                                                url: '/admin/webinars/search-users',
                                                dataType: 'json',
                                                delay: 250,
                                                cache: false,
                                                data: function (params) {
                                                    return {
                                                        q: params.term,
                                                        page: params.page || 1
                                                    };
                                                },
                                                processResults: function (data, params) {
                                                    return {
                                                        results: data
                                                    };
                                                },
                                                cache: true
                                            }
                                        });
                                    }
                                }
                            } else {
                                $modal.find('[name="' + key + '"]').val(session[key]);
                            }
                        });

                        var localeSelect = $modal.find('select[name="locale"]');

                        if (localeSelect) {
                            localeSelect.addClass('js-edit-session-locale-ajax');
                            localeSelect.attr('data-session-id', session_id);
                            localeSelect.attr('data-webinar-id', webinar_id);
                        }
                    }
                });
            }
        });
    }

    $('body').on('click', '.edit-session', function (e) {
        e.preventDefault();
        const $this = $(this);

        loadingSwl();

        editSession($this);
    });

    $('body').on('change', '.js-edit-session-locale-ajax', function (e) {
        e.preventDefault();
        const $this = $(this);
        const locale = $this.val();

        editSession($this, locale);
    });


    $('body').on('change', '.js-video-demo-source', function (e) {
        e.preventDefault();

        const value = $(this).val();

        const $filePathUploadButton = $('.js-video-demo-path-input .js-video-demo-path-upload');
        const $filePathLinkButton = $('.js-video-demo-path-input .js-video-demo-path-links');
        const $filePathInput = $('.js-video-demo-path-input input');

        $filePathUploadButton.addClass('d-none');
        $filePathLinkButton.addClass('d-none');

        if (value === 'upload') {
            $filePathUploadButton.removeClass('d-none');
        } else {
            $filePathLinkButton.removeClass('d-none');
        }

        if (videoDemoPathPlaceHolderBySource) {
            $filePathInput.attr('placeholder', videoDemoPathPlaceHolderBySource[value]);
        }
    });

    /*
    * edit prerequisites
    * */
    $('body').on('click', '.edit-prerequisite', function (e) {
        e.preventDefault();
        const $this = $(this);
        const prerequisite_id = $this.attr('data-prerequisite-id');
        const webinar_id = $this.attr('data-webinar-id');

        loadingSwl();

        const edit_data = {
            item_id: webinar_id
        };

        $.post('/admin/prerequisites/' + prerequisite_id + '/edit', edit_data, function (result) {
            if (result && result.prerequisite) {
                const prerequisite = result.prerequisite;

                let edit_prerequisite_modal = '<div id="addPrerequisitesModal">';
                edit_prerequisite_modal += $('#webinarPrerequisitesModal').html();
                edit_prerequisite_modal += '</div>';
                edit_prerequisite_modal = edit_prerequisite_modal.replaceAll('prerequisites-select', 'prerequisites-select2');
                edit_prerequisite_modal = edit_prerequisite_modal.replaceAll('/admin/prerequisites/store', '/admin/prerequisites/' + prerequisite_id + '/update');
                edit_prerequisite_modal = edit_prerequisite_modal.replaceAll('str_', '');

                Swal.fire({
                    html: edit_prerequisite_modal,
                    showCancelButton: false,
                    showConfirmButton: false,
                    customClass: {
                        content: 'p-0 text-left',
                    },
                    width: '48rem',
                    onOpen: () => {
                        $('.prerequisites-select2').append('<option selected="selected" value="' + prerequisite.webinar_id + '">' + prerequisite.webinar_title + '</option>');

                        if (prerequisite.required === 1) {
                            $('#addPrerequisitesModal').find('[name="required"]').prop('checked', true);
                        }

                        $('.prerequisites-select2').select2({
                            placeholder: $(this).data('placeholder'),
                            minimumInputLength: 3,
                            allowClear: true,
                            ajax: {
                                url: '/admin/webinars/search',
                                dataType: 'json',
                                type: "POST",
                                quietMillis: 50,
                                data: function (params) {
                                    var queryParameters = {
                                        term: params.term,
                                        webinar_id: $(this).data('webinar-id')
                                    }
                                    return queryParameters;
                                },
                                processResults: function (data) {
                                    return {
                                        results: $.map(data, function (item) {
                                            return {
                                                text: item.title,
                                                id: item.id
                                            }
                                        })
                                    };
                                }
                            }
                        });
                    }
                });
            }
        });
    });

    /*
   * edit FAQ
   * */
    function editFaq($this, locale = null) {
        const faq_id = $this.attr('data-faq-id');
        const webinar_id = $this.attr('data-webinar-id');

        const edit_data = {
            item_id: webinar_id,
            locale: locale
        };

        $.post('/admin/faqs/' + faq_id + '/edit', edit_data, function (result) {
            if (result && result.faq) {
                const faq = result.faq;

                let edit_faq_modal = '<div id="addFAQsModal">';
                edit_faq_modal += $('#webinarFaqModal').html();
                edit_faq_modal += '</div>';
                edit_faq_modal = edit_faq_modal.replaceAll('/admin/faqs/store', '/admin/faqs/' + faq_id + '/update');

                Swal.fire({
                    html: edit_faq_modal,
                    showCancelButton: false,
                    showConfirmButton: false,
                    customClass: {
                        content: 'p-0 text-left',
                    },
                    width: '48rem',
                    onOpen: () => {
                        var $modal = $('#addFAQsModal');

                        Object.keys(faq).forEach(key => {
                            $modal.find('[name="' + key + '"]').val(faq[key]);
                        });

                        var localeSelect = $modal.find('select[name="locale"]');

                        if (localeSelect) {
                            localeSelect.addClass('js-edit-faq-locale-ajax');
                            localeSelect.attr('data-faq-id', faq_id);
                            localeSelect.attr('data-webinar-id', webinar_id);
                        }
                    }
                });
            }
        });
    }

    $('body').on('click', '.edit-faq', function (e) {
        e.preventDefault();
        const $this = $(this);

        loadingSwl();

        editFaq($this);
    });

    $('body').on('change', '.js-edit-faq-locale-ajax', function (e) {
        e.preventDefault();
        const $this = $(this);
        const locale = $this.val();

        editFaq($this, locale);
    });

    $('body').on('click', '.js-get-faq-description', function (e) {
        e.preventDefault();
        const $this = $(this);
        const answer = $this.parent().find('input').val();

        var html = '<div class="my-2">' + answer + '</div>';

        Swal.fire({
            html: html,
            showCancelButton: false,
            showConfirmButton: false,
            customClass: {
                content: 'p-0 text-left',
            },
            width: '30rem',
        });
    });

    /*
   * edit FAQ
   * */
    $('body').on('click', '.edit-webinar-quiz', function (e) {
        e.preventDefault();
        const $this = $(this);
        const webinar_quiz_id = $this.attr('data-webinar-quiz-id');
        const webinar_id = $this.attr('data-webinar-id');

        loadingSwl();

        const edit_data = {
            item_id: webinar_id
        };

        $.post('/admin/webinar-quiz/' + webinar_quiz_id + '/edit', edit_data, function (result) {
            if (result && result.webinarQuiz) {
                const webinar_quiz = result.webinarQuiz;

                let edit_webinar_quiz_modal = '<div id="addQuizModal">';
                edit_webinar_quiz_modal += $('#quizzesModal').html();
                edit_webinar_quiz_modal += '</div>';
                edit_webinar_quiz_modal = edit_webinar_quiz_modal.replaceAll('/admin/webinar-quiz/store', '/admin/webinar-quiz/' + webinar_quiz_id + '/update');
                edit_webinar_quiz_modal = edit_webinar_quiz_modal.replaceAll('quiz-select2', 'quiz-select22');

                Swal.fire({
                    html: edit_webinar_quiz_modal,
                    showCancelButton: false,
                    showConfirmButton: false,
                    customClass: {
                        content: 'p-0 text-left',
                    },
                    width: '30rem',
                    onOpen: () => {

                        $('.quiz-select22').append('<option selected="selected" value="' + webinar_quiz.id + '">' + webinar_quiz.title + '</option>');
                        $(".quiz-select22").select2({
                            placeholder: $(this).data('placeholder'),
                            allowClear: true,
                            width: '100%',
                        });

                        $('#addQuizModal').find('[name="chapter_id"]').val(webinar_quiz.chapter_id);
                    }
                });
            }
        });
    });

    /*
    * ./
    * */

    $('body').on('change', 'select[name="type"]', function () {
        const value = this.value;
        const webinarItem = ['capacity', 'start_date'];

        let show = true;

        if (value !== 'webinar') {
            show = false;
        }

        for (let item of webinarItem) {
            if (show) {
                $('.js-' + item).removeClass('d-none');
            } else {
                $('.js-' + item).addClass('d-none');
            }
        }
    });

    $('body').on('change', '.js-sequence-content-switch', function () {
        const parent = $(this).closest('form');

        const sequenceContentInputs = parent.find('.js-sequence-content-inputs');
        sequenceContentInputs.addClass('d-none');

        if (this.checked) {
            sequenceContentInputs.removeClass('d-none');
        }
    });


    $('body').on('click', '#bundleAddNewCourses', function (e) {
        e.preventDefault();
        let html = '<div id="addBundleWebinarModal">';
        html += $('#bundleWebinarsModal').html();
        html += '</div>';
        html = html.replaceAll('bundleWebinars-select', 'bundleWebinars-select2');
        html = html.replaceAll('str_', '');

        Swal.fire({
            html: html,
            showCancelButton: false,
            showConfirmButton: false,
            customClass: {
                content: 'p-0 text-left',
            },
            width: '48rem',
            onOpen: () => {
                $('.bundleWebinars-select2').select2({
                    allowClear: false,
                });
            },
        });
    });

    $('body').on('click', '#saveBundleWebinar', function (e) {
        e.preventDefault();
        const $this = $(this);
        let form = $('#addBundleWebinarModal form');
        handleWebinarItemForm(form, $this);
    });

    $('body').on('click', '.edit-bundle-webinar', function (e) {
        e.preventDefault();
        const $this = $(this);
        const item_id = $this.attr('data-item-id');
        const bundle_id = $this.attr('data-bundle-id');

        loadingSwl();

        const edit_data = {
            item_id: bundle_id
        };

        $.post('/admin/bundle-webinars/' + item_id + '/edit', edit_data, function (result) {
            if (result && result.bundleWebinar) {
                const bundleWebinar = result.bundleWebinar;

                let html = '<div id="addBundleWebinarModal">';
                html += $('#bundleWebinarsModal').html();
                html += '</div>';
                html = html.replaceAll('bundleWebinars-select', 'bundleWebinars-select2');
                html = html.replaceAll('/admin/bundle-webinars/store', '/admin/bundle-webinars/' + item_id + '/update');
                html = html.replaceAll('str_', '');

                Swal.fire({
                    html: html,
                    showCancelButton: false,
                    showConfirmButton: false,
                    customClass: {
                        content: 'p-0 text-left',
                    },
                    width: '48rem',
                    onOpen: () => {
                        var select = $('.bundleWebinars-select2');

                        select.val(bundleWebinar.webinar_id);
                        select.select2({
                            allowClear: false,
                        });
                    }
                });
            }
        });
    });


    /* feather icons */
    // **
    // **
    feather.replace();

    // Function to initialize user selection dropdowns (only for NEW dropdowns, not already initialized ones)
    window.initializeUserSelect2 = function() {
        console.log('Checking for uninitialized user selection dropdowns...');
        
        $('select[name*="allowed_users"]').each(function() {
            var $this = $(this);
            
            // Check if already initialized and has proper AJAX config
            if ($this.hasClass('select2-hidden-accessible')) {
                var select2Data = $this.data('select2');
                // If it has AJAX config, skip it (it's properly initialized)
                if (select2Data && select2Data.options && select2Data.options.ajax) {
                    console.log('Select2 already initialized with AJAX for:', $this.attr('name'), '- SKIPPING (will not destroy)');
                    return; // Skip this one - it's already properly initialized
                } else {
                    // It's initialized but without AJAX - re-initialize it now
                    console.log('Select2 initialized but missing AJAX config for:', $this.attr('name'), '- Re-initializing with AJAX');
                    
                    // Get current selected values before destroying
                    var currentValues = $this.val() || [];
                    var currentOptions = [];
                    $this.find('option:selected').each(function() {
                        var val = $(this).val();
                        var text = $(this).text();
                        if (val && text && text.trim() !== '') {
                            currentOptions.push({ id: val, text: text });
                        }
                    });
                    
                    // Destroy and re-initialize
                    try {
                        var select2Data = $this.data('select2');
                        if (select2Data) {
                            $this.select2('destroy');
                        }
                    } catch(e) {
                        console.log('Error destroying Select2:', e);
                    }
                    
                    // Clear and re-add options
                    $this.empty();
                    if (currentOptions.length > 0) {
                        currentOptions.forEach(function(opt) {
                            var option = new Option(opt.text, opt.id, true, true);
                            $this.append(option);
                        });
                        $this.val(currentValues);
                    }
                    
                    // Now initialize with AJAX - this will be handled by the main init logic below
                    // We'll let it fall through to the initialization code
                }
            }
            
            // Only initialize if not already initialized or if it's a basic initialization that needs upgrade
            if (!$this.hasClass('select2-hidden-accessible')) {
                console.log('Found uninitialized user selection dropdown:', $this.attr('name'));
                
                // Get selected values BEFORE any initialization
                var selectedValues = [];
                $this.find('option:selected').each(function() {
                    var val = parseInt($(this).val());
                    if (val) {
                        selectedValues.push(val);
                    }
                });
                
                console.log('Preserving selected values:', selectedValues);
                
                // If there are selected values, fetch user details first
                if (selectedValues.length > 0) {
                    $.ajax({
                        url: '/admin/webinars/get-users-by-ids',
                        dataType: 'json',
                        data: { ids: selectedValues },
                        success: function(users) {
                            console.log('Fetched user details for initialization:', users);
                            
                            // Clear and add selected users as options
                            $this.empty();
                            users.forEach(function(user) {
                                var option = new Option(user.text, user.id, true, true);
                                $this.append(option);
                            });
                            
                            // Initialize Select2 with AJAX config (same as main initialization)
                            var select2Config = {
                                multiple: true,
                                width: '100%',
                                placeholder: 'Type to search users or click to see all...',
                                allowClear: true,
                                closeOnSelect: false,
                                minimumInputLength: 0,
                                maximumSelectionLength: null,
                                dropdownParent: $this.closest('.swal2-container, .modal, .card-body, body'),
                                ajax: {
                                    url: '/admin/webinars/search-users',
                                    dataType: 'json',
                                    delay: 250,
                                    cache: true,
                                    data: function (params) {
                                        return {
                                            q: params.term || '',
                                            page: params.page || 1
                                        };
                                    },
                                    processResults: function (data, params) {
                                        return {
                                            results: data,
                                            pagination: { more: false }
                                        };
                                    }
                                },
                                templateResult: function(user) {
                                    if (user.loading) {
                                        return user.text;
                                    }
                                    return $('<div>').text(user.text || user.id);
                                },
                                templateSelection: function(user) {
                                    return user.text || user.id;
                                }
                            };
                            
                            $this.select2(select2Config);
                            
                            // Set values after initialization
                            setTimeout(function() {
                                var ids = users.map(function(u) { return parseInt(u.id); });
                                $this.val(ids).trigger('change');
                                console.log('Select2 initialized with', ids.length, 'users');
                            }, 100);
                        },
                        error: function(xhr) {
                            console.error('Error fetching users, initializing without selected values');
                            // Initialize anyway
                            $this.select2({
                                multiple: true,
                                width: '100%',
                                placeholder: 'Type to search users...',
                                allowClear: true,
                                closeOnSelect: false,
                                minimumInputLength: 0
                            });
                        }
                    });
                } else {
                    // No selected values, just initialize with AJAX
                    $this.select2({
                        multiple: true,
                        width: '100%',
                        placeholder: 'Type to search users...',
                        allowClear: true,
                        closeOnSelect: false,
                        minimumInputLength: 0,
                        ajax: {
                            url: '/admin/webinars/search-users',
                            dataType: 'json',
                            delay: 250,
                            cache: true,
                            data: function (params) {
                                return {
                                    q: params.term || '',
                                    page: params.page || 1
                                };
                            },
                            processResults: function (data, params) {
                                return {
                                    results: data,
                                    pagination: { more: false }
                                };
                            }
                        }
                    });
                }
            }
        });
        
        console.log('User selection dropdown check complete.');
    };

    // REMOVED: Don't auto-initialize on page load - let the main $(document).ready() handle it
    // The main initialization at line 167-685 already handles this properly
    
    // Add a flag to track if main initialization has completed
    window.userSelect2MainInitialized = false;
    
    // Mark as initialized after main $(document).ready() completes
    $(document).ready(function() {
    // Inject minimal CSS to enable scrolling in Select2 selection and dropdown
    if (!document.getElementById('select2-users-scroll-style')) {
        var styleTag = document.createElement('style');
        styleTag.id = 'select2-users-scroll-style';
        styleTag.type = 'text/css';
        styleTag.innerHTML = "\n"
            + ".select2-users-selection .select2-selection__rendered{max-height:140px;overflow-y:auto;}\n"
            + ".select2-users-dropdown .select2-results__options{max-height:320px;overflow-y:auto;}\n";
        document.head.appendChild(styleTag);
    }
        setTimeout(function() {
            window.userSelect2MainInitialized = true;
            console.log('Main Select2 initialization completed');
        }, 2000); // Give main initialization time to complete
    });

    // Re-initialize when new content is added (only for truly new dropdowns)
    $(document).on('DOMNodeInserted', function(e) {
        var $newSelects = $(e.target).find('select[name*="allowed_users"]');
        if ($newSelects.length > 0) {
            // Only initialize if they're not already initialized
            $newSelects.each(function() {
                var $this = $(this);
                if (!$this.hasClass('select2-hidden-accessible')) {
                    setTimeout(function() {
                        window.initializeUserSelect2();
                    }, 100);
                }
            });
        }
    });

    // Simple fallback function for manual testing
    window.fixUserDropdowns = function() {
        console.log('Manual fix triggered...');
        $('select[name*="allowed_users"]').each(function() {
            var $this = $(this);
            $this.select2('destroy');
            $this.select2({
                multiple: true,
                width: '100%',
                placeholder: 'Type to search users...',
                allowClear: true,
                closeOnSelect: false
            });
        });
        console.log('Manual fix complete!');
    };

    // Show All Users Button Handler - Opens in new tab
    $(document).on('click', '.js-show-all-users', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        console.log('Show all users button clicked!');
        
        const $button = $(this);
        const selectName = $button.data('select-name');
        
        if (!selectName) {
            console.error('Select name not found in button data');
            alert('Error: Select name not found. Please refresh the page.');
            return;
        }
        
        console.log('Select name:', selectName);
        
        const $select = $button.closest('.form-group').find('select[name="' + selectName + '"]');
        
        if ($select.length === 0) {
            console.error('Select element not found for name:', selectName);
            alert('Error: Select element not found. Please refresh the page.');
            return;
        }
        
        console.log('Select element found:', $select.length);
        
        // Get currently selected users
        const currentSelected = $select.val() || [];
        const selectedIdsParam = currentSelected.length > 0 ? currentSelected.join(',') : '';
        
        console.log('Currently selected users:', currentSelected);
        
        // Store reference to the select element for later use
        const selectIdentifier = 'select_' + selectName.replace(/[\[\]]/g, '_') + '_' + Date.now();
        sessionStorage.setItem(selectIdentifier, JSON.stringify({
            selectName: selectName,
            currentSelected: currentSelected
        }));
        sessionStorage.setItem('lastSelectIdentifier', selectIdentifier);
        
        // Open new tab with only saved users for this lecture
        const url = '/admin/webinars/show-all-users?only_selected=1&selected_ids=' + encodeURIComponent(selectedIdsParam) + '&select_identifier=' + encodeURIComponent(selectIdentifier);
        console.log('Opening URL:', url);
        
        const newWindow = window.open(url, '_blank', 'width=900,height=700,scrollbars=yes');
        
        if (!newWindow) {
            alert('Please allow popups for this site to open the users list.');
        } else {
            console.log('New window opened successfully');
        }
    });

    // Listen for messages from the new window
    window.addEventListener('message', function(event) {
        if (event.data && event.data.type === 'users_selected') {
            console.log('Received users selection from new window:', event.data);
            
            const selectedIds = event.data.selectedIds || [];
            const storageKey = event.data.storageKey;
            const selectIdentifier = event.data.selectIdentifier || sessionStorage.getItem('lastSelectIdentifier');
            
            if (selectIdentifier) {
                // Get select data from sessionStorage
                const selectDataStr = sessionStorage.getItem(selectIdentifier);
                if (selectDataStr) {
                    try {
                        const selectData = JSON.parse(selectDataStr);
                        const selectName = selectData.selectName;
                        const $select = $('select[name="' + selectName + '"]');
                        
                        if ($select.length > 0) {
                            console.log('Updating select:', selectName, 'with', selectedIds.length, 'users');
                            
                            // Get user details for selected users
                            if (selectedIds.length > 0) {
                                $.ajax({
                                    url: '/admin/webinars/get-users-by-ids',
                                    dataType: 'json',
                                    data: { ids: selectedIds },
                                    success: function(selectedUsers) {
                                        console.log('Received selected user details:', selectedUsers);
                                        
                                        // Destroy Select2 if it exists and is initialized
                                        if ($select.hasClass('select2-hidden-accessible')) {
                                            try {
                                                $select.select2('destroy');
                                            } catch(e) {
                                                console.log('Select2 not initialized or already destroyed');
                                            }
                                        }
                                        
                                        // Clear existing options
                                        $select.empty();
                                        
                                        // Add selected users as options
                                        selectedUsers.forEach(function(user) {
                                            var option = new Option(user.text, user.id, true, true);
                                            $select.append(option);
                                        });
                                        
                                        // Set values
                                        const ids = selectedUsers.map(function(u) { return parseInt(u.id); });
                                        $select.val(ids);
                                        
                                        // Re-initialize Select2 if it was initialized before
                                        if ($select.hasClass('js-allowed-users-select') || $select.hasClass('select2-hidden-accessible')) {
                                            // Re-initialize Select2 with AJAX config
                                            setTimeout(function() {
                                                // Make sure Select2 is destroyed first - check if it's actually initialized
                                                if ($select.hasClass('select2-hidden-accessible')) {
                                                    try {
                                                        // Check if Select2 data exists before destroying
                                                        var select2Data = $select.data('select2');
                                                        if (select2Data) {
                                                            $select.select2('destroy');
                                                        }
                                                    } catch(e) {
                                                        console.log('Select2 already destroyed or not initialized');
                                                    }
                                                }
                                                
                                                $select.select2({
                                                    multiple: true,
                                                    width: '100%',
                                                    placeholder: 'Type to search users or click to see all...',
                                                    allowClear: true,
                                                    closeOnSelect: false,
                                                    minimumInputLength: 0,
                                                    maximumSelectionLength: null,
                                                    dropdownParent: $select.closest('.swal2-container, .modal, .card-body, body'),
                                                    language: {
                                                        inputTooShort: function () { 
                                                            return 'Type to search or click to see all users...'; 
                                                        },
                                                        searching: function() {
                                                            return 'Searching users...';
                                                        },
                                                        noResults: function() {
                                                            return 'No users found';
                                                        }
                                                    },
                                                    ajax: {
                                                        url: '/admin/webinars/search-users',
                                                        dataType: 'json',
                                                        delay: 250,
                                                        data: function (params) {
                                                            return {
                                                                q: params.term,
                                                                page: params.page || 1
                                                            };
                                                        },
                                                        processResults: function (data) {
                                                            return {
                                                                results: data
                                                            };
                                                        },
                                                        cache: true
                                                    },
                                                    templateResult: function(user) {
                                                        if (user.loading) {
                                                            return 'Searching...';
                                                        }
                                                        return user.text;
                                                    },
                                                    templateSelection: function(user) {
                                                        return user.text;
                                                    }
                                                });
                                                
                                                // Set the values again after Select2 is initialized
                                                setTimeout(function() {
                                                    $select.val(ids).trigger('change');
                                                    console.log('Select2 values set:', ids);
                                                    
                                                    // Force update Select2 display
                                                    $select.trigger('select2:select');
                                                    
                                                    // Verify the values are set
                                                    const currentVal = $select.val();
                                                    // Normalize both arrays to numbers for comparison
                                                    const normalizedCurrent = Array.isArray(currentVal) ? currentVal.map(function(v) { return parseInt(v); }).sort() : [parseInt(currentVal)];
                                                    const normalizedIds = ids.map(function(v) { return parseInt(v); }).sort();
                                                    console.log('Select2 current value after setting:', currentVal);
                                                    console.log('Expected values:', ids);
                                                    console.log('Match:', JSON.stringify(normalizedCurrent) === JSON.stringify(normalizedIds));
                                                }, 200);
                                                
                                                console.log('Select2 re-initialized with', ids.length, 'users');
                                            }, 100);
                                        } else {
                                            // Just trigger change if Select2 is not used
                                            $select.trigger('change');
                                        }
                                        
                                        console.log('Updated select with', ids.length, 'users:', ids);
                                    },
                                    error: function(xhr) {
                                        console.error('Error fetching user details:', xhr);
                                    }
                                });
                            } else {
                                // Clear all selections
                                $select.empty();
                                $select.val(null);
                                if ($select.hasClass('select2-hidden-accessible')) {
                                    $select.trigger('change.select2');
                                }
                            }
                        }
                    } catch (e) {
                        console.error('Error parsing select data:', e);
                    }
                }
            }
            
            // Clean up
            if (storageKey) {
                localStorage.removeItem(storageKey);
            }
        }
    });

    // Also listen for storage events (for same-origin communication)
    window.addEventListener('storage', function(event) {
        if (event.key && event.key.startsWith('webinar_selected_users_')) {
            try {
                if (!event.newValue) {
                    return; // No data to parse
                }
                
                const data = JSON.parse(event.newValue);
                const selectedIds = data.selectedIds || [];
                
                // Find the select element from sessionStorage
                const selectIdentifier = sessionStorage.getItem('lastSelectIdentifier');
                if (selectIdentifier) {
                    let selectData;
                    try {
                        // Try to parse as JSON first (it might be stored as JSON)
                        selectData = JSON.parse(selectIdentifier);
                    } catch(e) {
                        // If it's not JSON, it might be stored as a plain string identifier
                        // Try to get the actual data from sessionStorage using the identifier
                        const storedData = sessionStorage.getItem(selectIdentifier);
                        if (storedData) {
                            try {
                                selectData = JSON.parse(storedData);
                            } catch(e2) {
                                console.error('Could not parse select data from storage:', e2);
                                return;
                            }
                        } else {
                            console.error('Select identifier not found in sessionStorage');
                            return;
                        }
                    }
                    
                    const selectName = selectData.selectName;
                    const $select = $('select[name="' + selectName + '"]');
                    
                    if ($select.length > 0 && selectedIds.length > 0) {
                        console.log('Updating select from storage:', selectName, 'with', selectedIds.length, 'users');
                        
                        // Get user details and update select
                        $.ajax({
                            url: '/admin/webinars/get-users-by-ids',
                            dataType: 'json',
                            data: { ids: selectedIds },
                            success: function(selectedUsers) {
                                // Clear existing options
                                $select.empty();
                                
                                // Add selected users as options
                                selectedUsers.forEach(function(user) {
                                    var option = new Option(user.text, user.id, true, true);
                                    $select.append(option);
                                });
                                
                                // Set values
                                const ids = selectedUsers.map(function(u) { return parseInt(u.id); });
                                $select.val(ids);
                                
                                // Update Select2 if it's initialized
                                if ($select.hasClass('select2-hidden-accessible')) {
                                    try {
                                        $select.trigger('change.select2');
                                        $select.select2('val', ids);
                                    } catch(e) {
                                        console.log('Error updating Select2:', e);
                                    }
                                }
                            }
                        });
                    }
                }
            } catch (e) {
                console.error('Error handling storage event:', e);
            }
        }
    });
})(jQuery);
