jQuery(function ($){
    var OmniCommon = {
        init: function (){
            OmniCommon.HandleTestChannel();
            OmniCommon.handleTwitterDebug();
            OmniCommon.handleSMSDebug();
            OmniCommon.handleFaceBookDebug();
            OmniCommon.handleWhatsAppDebug();
            jQuery("body").on('click','.add_channel',this.HandleAddConfig);
            jQuery("body").on('click','.smtp_submit_config',this.HandleSubmit);
            jQuery("body").on('click','.test_channel',this.handleTestSubmit);
            jQuery("body").on('click','.delete_channel',this.HandleDelete);
            jQuery("body").on('click','.Cancel',this.HandleCancel);
            jQuery("body").on('click','.attctment_check',this.HandleAttchement);
            jQuery("body").on('change','.channel_name',this.HandleChannelForm);
            jQuery("body").on('change','.type_auth',this.HandleImapType); 
            jQuery("body").on('click','.Imapsubmit_config',this.HandleImapSubmit);
            jQuery("body").on('click','.submit_twitter_config',this.HandleTwitterSubmit);

            jQuery("body").on('click','.submit_sms_config',this.HandleSmsSubmit);
            jQuery("body").on('click','.submit_whatsapp_config',this.HandleWhatsappSubmit);
            jQuery("body").on('click','.submit_messenger_config',this.HandleMessengerSubmit);
            jQuery("body").on('click','.submit_instagram_config',this.HandleInstagramSubmit);
            jQuery("body").on('click','.submit_facebook_config',this.HandleFacebookSubmit);
            jQuery("body").on('click','.Refresh',this.HandleRefresh);

            jQuery("body").on('click','.twitter_debug_channel',this.handleTwitterSubmit);
            jQuery("body").on('click','.sms_debug_channel',this.handleSMSSubmit);
            jQuery("body").on('click','.facebook_debug_channel',this.handleFaceBookSubmit);
            jQuery("body").on('click','.whatsapp_debug_channel',this.handleWhatsAppSubmit);
            jQuery("body").on('click','.messenger_debug_channel',this.handleMessengerSubmit);
            // jQuery("body").on('click','.instagram_debug_channel',this.handleInstagramSubmit);
            jQuery("body").on('change','.method_type',this.handleMethod); 
            jQuery("body").on('change','.sms_type',this.handleSmsType);
            jQuery("body").on('change','.oauth_type_twitter',this.HandleTwitterChangeAuth);
            jQuery("body").on('click','.dynamic_submit_config',this.HandleDynamicSubmit);

        },
        HandleAddConfig:function(){
        	$('#myModal').modal('show');
        },
        HandleSubmit:function(){
            var formData = new FormData($('#addconfig')[0]);
            formData.append("channel_name",$('.channel_name').val());
             $.ajax({
                method: 'POST',
                url: 'omnichannel_config/config_function.php',
                cache: false,
                processData: false,
                contentType: false,
                data: formData,
                success: function (response) {
                    $('#success').html('<div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>Extension Insert Successfuly</div>');
                    setTimeout(function(){ 
                        var encodedToken = btoa('configuration');
                        window.location = 'omni_channel.php?token='+ encodeURIComponent(encodedToken); 
                    },2000); //reload a page after 5 seconds
                }
            });
        }, HandleDynamicSubmit: function (e) {
            e.preventDefault(); // 🚫 prevent default form submit
       
            var formData = new FormData($('#dyconfig')[0]);
           
            $.ajax({
                method: 'POST',
                url: 'omnichannel_config/config_function.php',
                cache: false,
                processData: false,
                contentType: false,
                data: formData,
                success: function (response) {
        
                    $('#success').html('<div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>' + response + '</div>');
        
                    setTimeout(function () {
                        var encodedToken = btoa('configuration');
                        window.location = 'omni_channel.php?token=' + encodeURIComponent(encodedToken);
                    }, 2000);
                }
            });
        },
        
        HandleImapSubmit:function(){
            var formData = new FormData($('#imapconfig')[0]);
            formData.append("channel_name",$('.channel_name').val());
             $.ajax({
                method: 'POST',
                url: 'omnichannel_config/config_function.php',
                cache: false,
                processData: false,
                contentType: false,
                data: formData,
                success: function (response) {
                    $('#success').html('<div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>Extension Insert Successfuly</div>');
                    setTimeout(function(){ 
                        var encodedToken = btoa('configuration');
                        window.location = 'omni_channel.php?token='+ encodeURIComponent(encodedToken); 
                    },2000); //reload a page after 5 seconds
                }
            }); 
         },
        HandleTwitterSubmit:function(){
            var formData = new FormData($('#twitterconfig')[0]);
            formData.append("channel_name",$('.channel_name').val());
             $.ajax({
                method: 'POST',
                url: 'omnichannel_config/config_function.php',
                cache: false,
                processData: false,
                contentType: false,
                data: formData,
                success: function (response) {
                    $('#success').html('<div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>Extension Insert Successfuly</div>');
                    setTimeout(function(){ 
                        var encodedToken = btoa('configuration');
                        window.location = 'omni_channel.php?token='+ encodeURIComponent(encodedToken); 
                    },2000); //reload a page after 5 seconds
                }
            });
        },
        HandleTwitterChangeAuth(){
            if($(this).val() == '0'){
                $('.bearer_token').show();
            }else{
                $('.bearer_token').hide();
            }
        },
        HandleSmsSubmit:function(){
            var formData = new FormData($('#smsconfig')[0]);
            formData.append("channel_name",$('.channel_name').val());
             $.ajax({
                method: 'POST',
                url: 'omnichannel_config/config_function.php',
                cache: false,
                processData: false,
                contentType: false,
                data: formData,
                success: function (response) {
                    $('#success').html('<div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>Extension Insert Successfuly</div>');
                    setTimeout(function(){ 
                        var encodedToken = btoa('configuration');
                        window.location = 'omni_channel.php?token='+ encodeURIComponent(encodedToken); 
                    },2000); //reload a page after 5 seconds
                }
            });
        },
HandleWhatsappSubmit: function() {
    var formData = new FormData($('#whatsappconfig')[0]);
    formData.append("channel_name", $('.channel_name').val());

    $.ajax({
        method: 'POST',
        url: 'omnichannel_config/config_function.php',
        cache: false,
        processData: false,
        contentType: false,
        data: formData,
        success: function(response) {
            $('#success').html('<div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>Extension Insert Successfully</div>');
            setTimeout(function() {
                window.location.reload();
            }, 2000);
        },
        error: function(xhr, status, error) {
            console.log('Form submission failed. Status:', status);
            console.log('Error:', error);
            console.log('Response:', xhr.responseText);
        }
    });
},
        HandleMessengerSubmit:function(){
            var formData = new FormData($('#messengerconfig')[0]);
            formData.append("channel_name",$('.channel_name').val());
             $.ajax({
                method: 'POST',
                url: 'omnichannel_config/config_function.php',
                cache: false,
                processData: false,
                contentType: false,
                data: formData,
                success: function (response) {
                    $('#success').html('<div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>Extension Insert Successfuly</div>');
                    setTimeout(function(){ 
                        var encodedToken = btoa('configuration');
                        window.location = 'omni_channel.php?token='+ encodeURIComponent(encodedToken); 
                    },2000); //reload a page after 5 seconds
                }
            });
        },
        HandleInstagramSubmit:function(){
            var formData = new FormData($('#instagramconfig')[0]);
            formData.append("channel_name",$('.channel_name').val());
             $.ajax({
                method: 'POST',
                url: 'omnichannel_config/config_function.php',
                cache: false,
                processData: false,
                contentType: false,
                data: formData,
                success: function (response) {
                    $('#success').html('<div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>Extension Insert Successfuly</div>');
                    setTimeout(function(){ 
                        var encodedToken = btoa('configuration');
                        window.location = 'omni_channel.php?token='+ encodeURIComponent(encodedToken); 
                    },2000); //reload a page after 5 seconds
                }
            });
        },

        HandleFacebookSubmit:function(){
            var formData = new FormData($('#facebookconfig')[0]);
            formData.append("channel_name",$('.channel_name').val());
             $.ajax({
                method: 'POST',
                url: 'omnichannel_config/config_function.php',
                cache: false,
                processData: false,
                contentType: false,
                data: formData,
                success: function (response) {
                    $('#success').html('<div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>Extension Insert Successfuly</div>');
                    setTimeout(function(){ 
                        var encodedToken = btoa('configuration');
                        window.location = 'omni_channel.php?token='+ encodeURIComponent(encodedToken); 
                    },2000); //reload a page after 5 seconds
                }
            });
        },
        handleTestSubmit:function(){
            $("#testconfig").submit();
        },
        HandleTestChannel:function(){
             $("#testconfig").validate({
                ignore: [],
                rules: {
                    email_to: {
                        required:true,
                    },
                    subject: {
                        required:true,
                    },
                    body:{
                        required:true,
                    }                    
                },              
                submitHandler: function(form) {
                    var formData = new FormData($('#testconfig')[0]);
                    $.ajax({
                        method: 'POST',
                       url: 'omnichannel_config/config_function.php',
                        cache: false,
                        processData: false,
                        contentType: false,
                        data: formData,
                        success: function (response) {
                            //this will display your success message
                            // $('#table_display').hide();
                            $('.output_display').show();
                            $('.output_display').text(response);
                            // setTimeout(function(){ 
                            // window.location.reload(); 
                            // },8000); //reload a page after 5 seconds
                        }
                    });
                }
            });
        },
        HandleDelete: function () {
            var result = confirm("Are you sure to delete ?");
            if (result) {
                var id = $(this).data('id');
                var channel = $(this).data('channel');
                if (id) {
                    $.ajax({
                        method: 'POST',
                        url: 'omnichannel_config/config_function.php',
                        data: { 'action': 'ChannelDelete', 'id': id, 'channel': channel },
                        success: function (response) {
                            $('#success').html('<div class="alert alert-success alert-dismissible" role="alert"> Deletion Successful</div>');
                            setTimeout(function () {
                                $('#success').html('');
                                location.reload();
                            }, 3000);
                        }
                    });
                }
            }
        },
        HandleCancel:function(){
            var encodedToken = btoa('configuration');
            window.location = 'omni_channel.php?token='+encodeURIComponent(encodedToken); 
        },
        HandleAttchement:function(){
            if ($(this).prop('checked')==true){ 
                $('.file').show();
            }else{
                $('.file').hide();
            }
        },
        HandleChannelForm:function(){
            var select = $(this).val();
            if(select == 'Smtp'){
                $('.Smtp_form').show();
                $('.Imap_form').hide();
                $('.twitter_form').hide();
                $('.sms_form').hide();  
                $('.whatsapp_form').hide(); 
                $('.messenger_form').hide();
                $('.instagram_form').hide();  
                $('.facebook_form').hide();
                $('.dynamic_form').hide();  
            }else if(select == 'Imap'){
                $('.Imap_form').show();
                $('.Smtp_form').hide();
                $('.twitter_form').hide();
                $('.sms_form').hide();  
                $('.whatsapp_form').hide(); 
                $('.messenger_form').hide(); 
                $('.instagram_form').hide(); 
                $('.facebook_form').hide();
                $('.dynamic_form').hide();  
            }else if(select == 'Twitter'){
                $('.twitter_form').show();
                $('.Imap_form').hide();
                $('.Smtp_form').hide(); 
                $('.sms_form').hide();  
                $('.whatsapp_form').hide();  
                $('.messenger_form').hide(); 
                $('.instagram_form').hide(); 
                $('.facebook_form').hide();  
                $('.dynamic_form').hide();           
            }else if(select == 'SMS'){
                $('.sms_form').show();
                $('.twitter_form').hide();
                $('.Imap_form').hide();
                $('.Smtp_form').hide(); 
                $('.whatsapp_form').hide(); 
                $('.messenger_form').hide();
                $('.instagram_form').hide();  
                $('.facebook_form').hide();
                $('.dynamic_form').hide();  
            }else if(select == 'Whatsapp'){
                $('.whatsapp_form').show();
                $('.sms_form').hide();
                $('.twitter_form').hide();
                $('.messenger_form').hide(); 
                $('.instagram_form').hide(); 
                $('.Imap_form').hide();
                $('.Smtp_form').hide(); 
                $('.facebook_form').hide();
                $('.dynamic_form').hide();  
            }else if(select == 'Facebook'){
                $('.facebook_form').show();
                $('.whatsapp_form').hide();
                $('.sms_form').hide();
                $('.twitter_form').hide();
                $('.messenger_form').hide();
                $('.instagram_form').hide();  
                $('.Imap_form').hide();
                $('.Smtp_form').hide(); 
                $('.dynamic_form').hide();  
            }else if(select == 'Messenger'){
                $('.facebook_form').hide();
                $('.whatsapp_form').hide();
                $('.sms_form').hide();
                $('.twitter_form').hide();
                $('.messenger_form').show();
                $('.instagram_form').hide();  
                $('.Imap_form').hide();
                $('.Smtp_form').hide(); 
                $('.dynamic_form').hide();  
            }else if(select == 'Instagram'){
                $('.facebook_form').hide();
                $('.whatsapp_form').hide();
                $('.sms_form').hide();
                $('.twitter_form').hide();
                $('.messenger_form').hide();
                $('.instagram_form').show();  
                $('.Imap_form').hide();
                $('.Smtp_form').hide(); 
                $('.dynamic_form').hide();  
            }else if(select == 'Dynamic'){
                $('.facebook_form').hide();
                $('.whatsapp_form').hide();
                $('.sms_form').hide();
                $('.twitter_form').hide();
                $('.messenger_form').hide();
                $('.instagram_form').hide();  
                $('.Imap_form').hide();
                $('.Smtp_form').hide(); 
                $('.dynamic_form').show();  
            }
        },
        HandleImapType:function(){
            var select = $(this).val();
            if(select == 'OAuth'){
                $('.auth2').hide();
            }else if(select == 'OAuth2'){
                $('.auth2').show();
            }
        },
        HandleRefresh:function(){
            window.location.reload();
        },
        handleTwitterSubmit:function(){
            $("#twitterconfig").submit();
        },
        handleTwitterDebug:function(){
            $("#twitterconfig").validate({
                ignore: [],             
                submitHandler: function(form) {
                    var formData = new FormData($('#twitterconfig')[0]);
                    $.ajax({
                        method: 'POST',
                       url: 'omnichannel_config/config_function.php',
                        cache: false,
                        processData: false,
                        contentType: false,
                        data: formData,
                        success: function (response) {
                            $('.output_display_twitter').show();
                            $('.output_display_twitter').html(response);
                        }
                    });
                }
            });
        },
        handleSMSDebug:function(){
            $("#smsconfig").validate({
                ignore: [],
                rules: {
                    number: {
                        required:true,
                    },
                    sms_message:{
                        required:true,
                    }                    
                },              
                submitHandler: function(form) {
                    var formData = new FormData($('#smsconfig')[0]);
                    $.ajax({
                        method: 'POST',
                       url: 'omnichannel_config/config_function.php',
                        cache: false,
                        processData: false,
                        contentType: false,
                        data: formData,
                        success: function (response) {
                            $('.output_display_sms').show();
                            $('.output_display_sms').html(response);
                        }
                    });
                }
            });
        },
        handleSMSSubmit:function(){
            $("#smsconfig").submit();
        },
        handleWhatsAppSubmit:function(){
            $("#whatsappconfig").submit();
        },
        handleMessengerSubmit:function(){
            $("#messengerconfig").submit();
        },
        handleWhatsAppDebug:function(){
            $("#whatsappconfig").validate({
                ignore: [],
                rules: {
                    number: {
                        required:true,
                    },
                    sms_message:{
                        required:true,
                    }                    
                },              
                submitHandler: function(form) {
                    var formData = new FormData($('#whatsappconfig')[0]);
                    $.ajax({
                        method: 'POST',
                       url: 'omnichannel_config/config_function.php',
                        cache: false,
                        processData: false,
                        contentType: false,
                        data: formData,
                        success: function (response) {
                            $('.output_display_whatsapp').show();
                            $('.output_display_whatsapp').html(response);
                        }
                    });
                }
            });
        },
        handleFaceBookSubmit:function(){
            $("#facebookconfig").submit();
        },
        handleFaceBookDebug:function(){
            $("#facebookconfig").validate({
                ignore: [],
                rules: {
                    number: {
                        required:true,
                    },
                    sms_message:{
                        required:true,
                    }                    
                },              
                submitHandler: function(form) {
                    var formData = new FormData($('#facebookconfig')[0]);
                    $.ajax({
                        method: 'POST',
                       url: 'omnichannel_config/config_function.php',
                        cache: false,
                        processData: false,
                        contentType: false,
                        data: formData,
                        success: function (response) {
                            $('.output_display_facebook').show();
                            $('.output_display_facebook').html(response);
                        }
                    });
                }
            });
        },
        handleMethod:function(){
            var select = $(this).val();
            if(select == 'POST'){
                $('.show_post').show();
            }else{
                $('.show_post').hide();
            }
        },
        handleSmsType:function(){
            var select = $(this).val();
            if(select == 'url_based'){
                $('.sms_zambia').show();
                $('.sms_onfonmedia').hide();
                $('.exotel').hide();
                $('.sms_common').show();
                $('.SMPP').hide();
            }else if(select == 'onfonmedia'){
                $('.sms_onfonmedia').show();
                $('.sms_zambia').hide();
                $('.exotel').hide();
                $('.sms_common').show();
                $('.SMPP').hide();
            }else if(select == 'exotel'){
                $('.sms_onfonmedia').hide();
                $('.sms_zambia').hide();
                $('.exotel').show();
                $('.sms_common').hide();
                $('.SMPP').hide();
            }else if(select == 'SMPP'){
                $('.sms_onfonmedia').hide();
                $('.sms_zambia').hide();
                $('.exotel').hide();
                $('.sms_common').hide();
                $('.SMPP').show();
            }
        }
    }
    OmniCommon.init();
});
// ############################### WebChat code here ####################################
function initialize_datatables_web_chat(startdatetime = '', enddatetime = '', phone = '', id = '', chat_type, caseid = '',send_name ='',iallstatus ='' ) {
    var startdatetime = $('#startdatetime').val();
        var enddatetime = $('#enddatetime').val();
        
    var dataTable = $('#chat_table').DataTable({
        "processing": true,
        "serverSide": true,
        "order": [],
        "pageLength": 25, // Set default number of records per page to 30
        "lengthMenu": [ [10, 25, 50, 100,  -1], [10, 25, 50,100, "All"] ],
        "searching": false,
        "ajax": {
            url: "omnichannel_config/fetchData.php",
            type: "POST",
            data: function(d) {
                d.startdatetime = startdatetime;
                d.enddatetime = enddatetime;
                d.phone = phone;
                d.id =  id;
                d.chat_type = chat_type;
                d.caseid = caseid;
                d.send_name =  send_name;
                d.iallstatus = iallstatus;
                d.action = 'web_chat';
            }
        },
        "createdRow": function( row, data, dataIndex) {
        var clr = data[8]; // Assuming clr value 
        if (clr == 'yellow') {
            // $(row).addClass('flag-yellow');
        } else if (clr == 'red') {
            $(row).addClass('mail-row');
        } else if (clr == 'green') {
            // $(row).addClass('flag-green');
        }
        },
        "drawCallback": function( settings ) {
            // Reinitialize Colorbox for new elements
            $(".ico-interaction2").colorbox({
                iframe: true,
                innerWidth: 1000,
                innerHeight: 450
            });
            // Reinitialize Colorbox for new elements
            // $(".openPopup").colorbox({iframe:true, width:"80%", height:"80%"});
        }

    });
    return dataTable;
}   
$(document).ready(function() {
     // Set an interval to refresh data every 2 seconds
     initialize_datatables_web_chat();
     // Set an interval to refresh data every 9 seconds
     setInterval(function() {
        // Check if table exists before using DataTable
        if ($.fn.DataTable.isDataTable('#chat_table')) {
             // Get the current page info before reloading
             var dataTable = $('#chat_table').DataTable();
             var pageInfo = dataTable.page.info();

             // Reload the data without resetting the paging
             dataTable.ajax.reload(null, false);

             // After the reload, set the page back to the original page
             dataTable.page(pageInfo.page).draw(false);
         }
     }, 20000); // 9000 milliseconds = 9 seconds
     $('#post_web_chat').submit(function(e) {
        e.preventDefault();
        var startdatetime = $('#startdatetime').val();
        var enddatetime = $('#enddatetime').val();
        var phone = $('#phone').val();
        var id = $('#id').val();
        var chat_type = $('#chat_type').val();
        var caseid = $('#caseid').val();
        var send_name = $('#send_name').val();
        var iallstatus = $('#iallstatus').val();
        // Destroy DataTable instance to reinitialize with new data
        $('#chat_table').DataTable().destroy();
    
        // Call initialize_datatables function with appropriate filter parameters
        initialize_datatables_web_chat(startdatetime, enddatetime, phone, id, chat_type, caseid,send_name,iallstatus);
});
$('#reset_button_chat').click(function () {
    $('#chat_table').DataTable().destroy();
    $('#startdatetime,#enddatetime,#phone,#id,#chat_type, #caseid','#send_name','#iallstatus').val('');
    initialize_datatables_web_chat();
});
// ############################### END WebChat code here ####################################

// ############################### START Facebook code here ####################################
fill_datatables_facebook();
function fill_datatables_facebook(startdatetime = '', enddatetime = '', iallstatus = '') {
    var id = $('#inte_id').val();
    var dataTable = $('#facebook_table').DataTable({
        "processing": true,
        "serverSide": true,
        "order": [],
        "pageLength": 25, // Set default number of records per page to 30
        "lengthMenu": [ [10, 25, 50, 100,  -1], [10, 25, 50,100, "All"] ],
        "searching": false,
        "ajax": {
            url: "omnichannel_config/fetchData.php",
            type: "POST",
            data:{
                startdatetime: startdatetime,
                enddatetime: enddatetime,
                iallstatus: iallstatus,
                id:id,
                action:'facebook'
            }
        },
            "createdRow": function( row, data, dataIndex) {
            var clr = data[7]; // Assuming clr value 
           
            if (clr == 'yellow') {
                // $(row).addClass('flag-yellow');
            } else if (clr == 'red') {
                $(row).addClass('mail-row');
            } else if (clr == 'green') {
                // $(row).addClass('flag-green');
            }
        }

    });
}  
$('#post_facebook').submit(function(e) {
    e.preventDefault();
    var startdatetime = $('#startdatetime').val();
    var enddatetime = $('#enddatetime').val();
    var iallstatus = $('#iallstatus').val();

    // Destroy DataTable instance to reinitialize with new data
    $('#facebook_table').DataTable().destroy();

    // Call fill_datatables function with appropriate filter parameters
    fill_datatables_facebook(startdatetime, enddatetime,  iallstatus );
});

// ############################### END Facebook code here ####################################

// ############################### START SMS code here ####################################
function fill_datatables_sms() {

    // Always destroy old instance if it exists
    if ($.fn.DataTable.isDataTable('#sms_table')) {
        $('#sms_table').DataTable().destroy();
    }

    var dataTable = $('#sms_table').DataTable({
        processing: true,
        serverSide: true,
        order: [],
        pageLength: 25,
        lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        searching: false,

        ajax: {
            url: "omnichannel_config/fetchData.php",
            type: "POST",
            data: function(d) {
                // Always take current values dynamically
                d.startdatetime = $('#startdatetime').val();
                d.enddatetime   = $('#enddatetime').val();
                d.phone         = $('#phone').val();
                d.id            = $('#inte_id').val();
                d.ICASEID       = $('#ICASEID').val();
                d.iallstatus    = $('#iallstatus').val();
                d.searchfield   = $('#searchfield').val();
                d.action        = 'sms';
            },
            error: function(xhr) {
                console.error("AJAX Error:", xhr.responseText);
            }
        },

        createdRow: function(row, data) {
            var clr = data[7]; // Adjust index if color column changes
            if (clr === 'red') {
                $(row).addClass('mail-row');
            }
        },

        drawCallback: function() {
            // Reinitialize colorbox after redraw
            $(".ico-interaction2").colorbox({
                iframe: true,
                innerWidth: 750,
                innerHeight: 560
            });

            // Highlight matching term in column index 2 (adjust as needed)
            var searchTerm = $('#searchfield').val();
            $('#sms_table tbody tr').each(function() {
                applyHighlight($(this).find('td').eq(2), searchTerm);
            });
        }
    });

    // Live search trigger (re-attached only once)
    $('#searchfield').off('input.smsSearch').on('input.smsSearch', function() {
        if (dataTable) {
            dataTable.ajax.reload(null, false);
        }
    });
}


// reload timer 10 sec [vastvikta][24-06-2025]
$(document).ready(function () {
    // Call on page load
    fill_datatables_sms();

    // Call every 10 seconds
    setInterval(function () {
        fill_datatables_sms();
    }, 10000); // 10 seconds
});
$('#post_sms').submit(function(e) {
    e.preventDefault();
    var startdatetime = $('#startdatetime').val();
    var enddatetime = $('#enddatetime').val();
    var phone = $('#phone').val();
    var ICASEID = $('#ICASEID').val();
    var iallstatus = $('#iallstatus').val();
    // Destroy DataTable instance to reinitialize with new data
    $('#sms_table').DataTable().destroy();

    // Call fill_datatables function with appropriate filter parameters
    fill_datatables_sms(startdatetime, enddatetime, phone, ICASEID, iallstatus);
  
});
    
$('#reset_button_sms').click(function () {
    $('#sms_table').DataTable().destroy();
    $('#startdatetime').val();
    $('#enddatetime').val();
    $('#phone').val('');
    $('#ICASEID').val();
    fill_datatables_sms();
});

function applyHighlight($cells, searchTerm) {
    searchTerm = searchTerm.trim();
    if (searchTerm === '') {
        $cells.each(function () {
            $(this).html($(this).text());
        });
        return;
    }
    let terms = searchTerm.split(/\s+/).filter(t => t.length > 0);
    let safeTerms = terms.map(t => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
    let regex = new RegExp('(' + safeTerms.join('|') + ')', 'gi');

    $cells.each(function () {
        let text = $(this).text();
        if (text) {
            $(this).html(text.replace(regex, '<span class="highlight">$1</span>'));
        }
    });
}

$(document).ready(function() {
    var TwitterdataTable;
    var twitterReport;

    // Function to initialize Twitter DataTable
    function fill_datatables_twitter(startdatetime = '', enddatetime = '', searchfield = '') {
        if (!$.fn.DataTable.isDataTable('#twitter_table')) {
            TwitterdataTable = $('#twitter_table').DataTable({
                "processing": true,
                "serverSide": true,
                "order": [],
                "pageLength": 25,
                "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                "searching": false,
                "ajax": {
                    url: "omnichannel_config/fetchData.php",
                    type: "POST",
                    data: function (d) {
                        d.startdatetime = $('#startdatetime').val();
                        d.enddatetime = $('#enddatetime').val();
                        d.searchfield = $('#searchfield').val();
                        d.agent_search = $('#agent_search').val();
                        d.v_Screenname = $('#v_Screenname').val();
                        d.v_name = $('#v_name').val();
                        d.ICASEID = $('#ICASEID').val();
                        d.id = $('#inte_id').val();
                        d.action = 'twitter';
                    }
                },
                "createdRow": function (row, data, dataIndex) {
                    // updated js  for color [vastvikta][31-10-202]
                    var clr = data[8]; // Assuming clr value is in the ninth column
                    if (clr == 'yellow') {
                    $(row).addClass('flag-yellow');
                    } else if (clr == 'red') {
                        $(row).addClass('mail-row');
                    } else if (clr == 'green') {
                        // $(row).addClass('flag-green');
                    }
                },
                "drawCallback": function (settings) {
                    // Reinitialize Colorbox
                    $(".ico-interaction2").colorbox({
                        iframe: true,
                        innerWidth: 1000,
                        innerHeight: 550
                    });

                    // Highlight search term in the relevant column (e.g., column index 4)
                    let searchTerm = $('#searchfield').val();
                    $('#twitter_table tbody tr').each(function () {
                        applyHighlight($(this).find('td').eq(2), searchTerm);  // Change index if needed
                    });
                }
            });
        } else {
            TwitterdataTable.ajax.reload(null, false);
        }
    }

    // Function to initialize Twitter Report DataTable
    function fill_datatables_twitter_report(startdatetime = '', enddatetime = '', status = '', recipient_id = '', searchfield = '') {
        if (!$.fn.DataTable.isDataTable('#twitter_report')) {
            twitterReport = $('#twitter_report').DataTable({
                "processing": true,
                "serverSide": true,
                "order": [],
                "pageLength": 25,
                "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                "searching": false,
                "paging": true,
                "dom": "lBfrtip",
                "buttons": [
                    // Define your export or custom buttons here
                ],
                "ajax": {
                    url: "omnichannel_config/fetchData.php",
                    type: "POST",
                    data: function (d) {
                        d.startdatetime = startdatetime || $('#startdatetime').val();
                        d.enddatetime = enddatetime || $('#enddatetime').val();
                        d.searchfield = searchfield || $('#searchfield').val();
                        d.status = status || $('#status').val();
                        d.recipient_id = recipient_id || $('#recipient_id').val();
                        d.action = 'twitter_report';
                    },
                    error: function (xhr, error, thrown) {
                        console.error('DataTables error:', error);
                    }
                }
            });
        } else {
            twitterReport.ajax.reload(null, false);
        }
    }

    // Initialize tables
    fill_datatables_twitter();
    fill_datatables_twitter_report();

    // Refresh Twitter data table every 60 seconds
    setInterval(function () {
        if (TwitterdataTable) TwitterdataTable.ajax.reload(null, false);
    }, 60000);

    // Refresh Twitter report every 10 seconds
    setInterval(function () {
        if (twitterReport) twitterReport.ajax.reload(null, false);
    }, 10000);

    // Form submission for Twitter search
    $('#post_twitter').submit(function (e) {
        e.preventDefault();
        if (TwitterdataTable) TwitterdataTable.destroy();
        fill_datatables_twitter();
    });

    // Reset form and reload Twitter table
    $('#reset_twitter').click(function () {
        if (TwitterdataTable) TwitterdataTable.destroy();
        $('#startdatetime, #enddatetime, #searchfield, #v_Screenname, #v_name, #ICASEID').val('');
        fill_datatables_twitter();
    });

    // Form submission for Twitter report
    $('#twitter_report_form').submit(function (e) {
        e.preventDefault();
        if (twitterReport) twitterReport.destroy();
        fill_datatables_twitter_report();
    });

    // Live search input triggers DataTable reload (and highlight on draw)
    $('#searchfield').on('input', function () {
        if (TwitterdataTable) {
            TwitterdataTable.ajax.reload(null, false);
        }
    });

});



// ############################### END Twittwr code here ####################################

// ############################### START Whatsapp code here ####################################
$(document).ready(function() {

    var WhatsadatappReport;

// Function to initialize and fill the WhatsApp data table
function fill_datatables_whatsapp_report(startdatetime ='',enddatetime ='',status ='',send_to ='') {
        
    WhatsadatappReport = $('#whatsapp_report').DataTable({
        "processing": true,
        "serverSide": true,
        "order": [],
        "pageLength": 25, // Default records per page
        "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        "searching": false,
        "paging": true, // Ensure paging is enabled
        "dom": "lBfrtip", // "p" ensures pagination is included in the layout
             "buttons": [
                {
                    extend: 'csvHtml5',
                    text: '<i class="fa fa-file-excel-o"></i>',
                    titleAttr: 'CSV',
                    filename: 'csv',
                    title: $('.download_label').html(),
                    exportOptions: {
                        columns: ':visible'
                    }
                },{
                    extend: 'excelHtml5',
                    text: '<i class="fa fa-file-excel-o"></i>',
                    titleAttr: 'Excel',
                    filename: 'Excel',
                    title: $('.download_label').html(),
                    exportOptions: {
                        columns: ':visible'
                    }
                },{
                        extend: 'pdfHtml5',
                        filename : $('.report_name').text(),
                        messageTop : $('.download_label').html(),
                        orientation: 'landscape',
                        pageSize: 'A3',
                        text: '<i class="fa fa-file-pdf-o"></i>',
                        titleAttr: 'PDF',
                        // changed logo code [vastvikta][05-05-2025]
                        customize: function ( doc ) {
                            
                            var logoBase64 = document.getElementById('pdf-logo-base64').innerText;
                            doc.images = doc.images || {};
                            doc.images.logo = logoBase64;
                        
                        doc.content.splice( 1, 0, {
                            margin: [ 0, 0, 0, 5 ],
                                alignment: 'left',
                                image: 'logo', 
                                 width: 250
                            } );
                        },
                        title: '.',
                        exportOptions: {
                            columns: ':visible'
                            
                        }
                    },{
                    extend: 'colvis',
                    text: '<i class="fa fa-columns"></i>',
                    titleAttr: 'Columns',
                    title: $('.download_label').html(),
                    postfixButtons: ['colvisRestore']
                },
            ],
        "ajax": {
            url: "omnichannel_config/fetchData.php",
            type: "POST",
            data: function(d) {
                d.startdatetime = $('#startdatetime').val();
                d.enddatetime = $('#enddatetime').val();
                d.searchfield = $('#searchfield').val();
                d.send_to = $('#send_to').val();
                d.status = $('#status').val();
                d.group_by = $('input[name="group_by"]:checked').val(); // Capture selected radio button value
   
                d.action = 'Whatsapp_report';
            }
        }
    });
}

// Initialize WhatsApp report table
fill_datatables_whatsapp_report();

// Set an interval to refresh the table every 10 seconds
setInterval(function() {
    WhatsadatappReport.ajax.reload(null, false); // Reload data without resetting pagination
}, 10000);

// Submit form and reload data based on new filters
$('#whatsapp_report_form').submit(function(e) {
    e.preventDefault();
    
    $('#whatsapp_report').DataTable().destroy();
    var startdatetime = $('#startdatetime').val();
    var enddatetime = $('#enddatetime').val();
    var status = $('#status').val();
    var send_to = $('#send_to').val();
    fill_datatables_whatsapp_report(startdatetime,enddatetime,status,send_to);// Refresh the table with the new filter parameters
});

// Reset button functionality
$('.reset_whatsapp_report').click(function () {

    // Destroy the existing DataTable
    WhatsadatappReport.destroy();

    // Get the current date and time
    var currentDate = new Date();
    
    // Format the first day of the current month as '01-mm-yyyy 00:00:00'
    var startOfMonth = '01-' + ('0' + (currentDate.getMonth() + 1)).slice(-2) + '-' + currentDate.getFullYear() + ' 00:00:00';

    // Format the current date as 'dd-mm-yyyy 23:59:59'
    var formattedEndDate = ('0' + currentDate.getDate()).slice(-2) + '-' +
                           ('0' + (currentDate.getMonth() + 1)).slice(-2) + '-' +
                           currentDate.getFullYear() + ' 23:59:59';

    // Reset the form fields
    $('#startdatetime').val(startOfMonth);
    $('#enddatetime').val(formattedEndDate);
    $('#status').val('');
    $('#send_to').val('0'); // Reset to the default "Select" option
    $('#searchBox').val(''); // Clear the search input field

    // Optionally, clear any previous dropdown visibility or messages
    $('#dropdownContainer').hide(); // Hide the dropdown if it is visible
    $('#noPhoneNumber').hide(); // Hide the "No records found" message if visible
    $('#searchSenderBox').val('');
    $('#searchBox').val('');
    
    // Reinitialize the table with default filters
    fill_datatables_whatsapp_report(); // Ensure this function initializes the table correctly
});


var messengerReport;

// Function to initialize and fill the messeneger report data table
function fill_datatables_messenger_report(startdatetime ='',enddatetime ='',status ='',send_to = '') {
   
    messengerReport = $('#messenger_report').DataTable({
        "processing": true,
        "serverSide": true,
        "order": [],
        "pageLength": 25, // Default records per page
        "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        "searching": false,
        "paging": true, // Ensure paging is enabled
        "dom": "lBfrtip", // "p" ensures pagination is included in the layout
             "buttons": [
                {
                    extend: 'csvHtml5',
                    text: '<i class="fa fa-file-excel-o"></i>',
                    titleAttr: 'CSV',
                    filename: 'csv',
                    title: $('.download_label').html(),
                    exportOptions: {
                        columns: ':visible'
                    }
                },{
                    extend: 'excelHtml5',
                    text: '<i class="fa fa-file-excel-o"></i>',
                    titleAttr: 'Excel',
                    filename: 'Excel',
                    title: $('.download_label').html(),
                    exportOptions: {
                        columns: ':visible'
                    }
                },{
                        extend: 'pdfHtml5',
                        filename : $('.report_name').text(),
                        messageTop : $('.download_label').html(),
                        orientation: 'landscape',
                        pageSize: 'A3',
                        text: '<i class="fa fa-file-pdf-o"></i>',
                        titleAttr: 'PDF',
                        // changed logo code [vastvikta][05-05-2025]
                        customize: function ( doc ) {
                            
                            var logoBase64 = document.getElementById('pdf-logo-base64').innerText;
                            doc.images = doc.images || {};
                            doc.images.logo = logoBase64;
                        
                        doc.content.splice( 1, 0, {
                            margin: [ 0, 0, 0, 5 ],
                                alignment: 'left',
                                image: 'logo', 
                                 width: 250
                            } );
                        },
                        title: '.',
                        exportOptions: {
                            columns: ':visible'
                            
                        }
                    },{
                    extend: 'colvis',
                    text: '<i class="fa fa-columns"></i>',
                    titleAttr: 'Columns',
                    title: $('.download_label').html(),
                    postfixButtons: ['colvisRestore']
                },
            ],
        "ajax": {
            url: "omnichannel_config/fetchData.php",
            type: "POST",
            data: function(d) {
                d.startdatetime = $('#startdatetime').val();
                d.enddatetime = $('#enddatetime').val();
                d.status = $('#status').val();
                d.send_to = $('#send_to').val();
                d.action = 'messenger_report';
            }
        }
    });
}

// Initialize messenger report table
fill_datatables_messenger_report();

// Set an interval to refresh the table every 10 seconds
setInterval(function() {
    messengerReport.ajax.reload(null, false); // Reload data without resetting pagination
}, 10000);

// Submit form and reload data based on new filters
$('#messenger_report_form').submit(function(e) {
    e.preventDefault();
    
    $('#messenger_report').DataTable().destroy();
    var startdatetime = $('#startdatetime').val();
    var enddatetime = $('#enddatetime').val();
    var status = $('#status').val();
    var send_to = $('#send_to').val();
   
    fill_datatables_messenger_report(startdatetime,enddatetime,status,send_to);// Refresh the table with the new filter parameters
});
fill_datatables_facebook_report();

// Function to initialize and fill the messeneger report data table
function fill_datatables_facebook_report(startdatetime ='',enddatetime ='',status ='',name = '') {
   
    facebookReport = $('#facebook_report').DataTable({
        "processing": true,
        "serverSide": true,
        "order": [],
        "pageLength": 25, // Default records per page
        "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        "searching": false,
        "paging": true, // Ensure paging is enabled
        "dom": "lBfrtip", // "p" ensures pagination is included in the layout
             "buttons": [
                {
                    extend: 'csvHtml5',
                    text: '<i class="fa fa-file-excel-o"></i>',
                    titleAttr: 'CSV',
                    filename: 'csv',
                    title: $('.download_label').html(),
                    exportOptions: {
                        columns: ':visible'
                    }
                },{
                    extend: 'excelHtml5',
                    text: '<i class="fa fa-file-excel-o"></i>',
                    titleAttr: 'Excel',
                    filename: 'Excel',
                    title: $('.download_label').html(),
                    exportOptions: {
                        columns: ':visible'
                    }
                },{
                        extend: 'pdfHtml5',
                        filename : $('.report_name').text(),
                        messageTop : $('.download_label').html(),
                        orientation: 'landscape',
                        pageSize: 'A3',
                        text: '<i class="fa fa-file-pdf-o"></i>',
                        titleAttr: 'PDF',
                        // changed logo code [vastvikta][05-05-2025]
                        customize: function ( doc ) {
                            
                            var logoBase64 = document.getElementById('pdf-logo-base64').innerText;
                            doc.images = doc.images || {};
                            doc.images.logo = logoBase64;
                        
                        doc.content.splice( 1, 0, {
                            margin: [ 0, 0, 0, 5 ],
                                alignment: 'left',
                                image: 'logo', 
                                 width: 250
                            } );
                        },
                        title: '.',
                        exportOptions: {
                            columns: ':visible'
                            
                        }
                    },{
                    extend: 'colvis',
                    text: '<i class="fa fa-columns"></i>',
                    titleAttr: 'Columns',
                    title: $('.download_label').html(),
                    postfixButtons: ['colvisRestore']
                },
            ],
        "ajax": {
            url: "omnichannel_config/fetchData.php",
            type: "POST",
            data: function(d) {
                d.startdatetime = $('#startdatetime').val();
                d.enddatetime = $('#enddatetime').val();
                d.status = $('#status').val();
                d.name = $('#name').val();
                d.action = 'facebook_report';
            }
        }
    });
}
// Set an interval to refresh the table every 10 seconds
setInterval(function() {
    facebookReport.ajax.reload(null, false); // Reload data without resetting pagination
}, 10000);
// Submit form and reload data based on new filters
$('#facebook_report_form').submit(function(e) {
    e.preventDefault();

    $('#facebook_report').DataTable().destroy();
    var startdatetime = $('#startdatetime').val();
    var enddatetime = $('#enddatetime').val();
    var status = $('#status').val();
    var name = $('#name').val();

    fill_datatables_facebook_report(startdatetime, enddatetime, status, name); // ✅ FIXED
});
// for  Twitter Queue Report [vastvikta][16-06-2025]
fill_datatables_twitter_queue_report();

function applyHighlight($cells, searchTerm) {
        searchTerm = searchTerm.trim();
        if (searchTerm === '') {
            $cells.each(function () {
                $(this).html($(this).text());
            });
            return;
        }
        let terms = searchTerm.split(/\s+/).filter(t => t.length > 0);
        let safeTerms = terms.map(t => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
        let regex = new RegExp('(' + safeTerms.join('|') + ')', 'gi');

        $cells.each(function () {
            let text = $(this).text();
            if (text) {
                $(this).html(text.replace(regex, '<span class="highlight">$1</span>'));
            }
        });
}
// Function to initialize and fill the messeneger report data table
function fill_datatables_twitter_queue_report(startdatetime ='',enddatetime ='',status ='',name = '') {
   
    twitter_queueReport = $('#twitter_queue_report').DataTable({
        "processing": true,
        "serverSide": true,
        "order": [],
        "pageLength": 25, // Default records per page
        "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        "searching": false,
        "paging": true, // Ensure paging is enabled
        "dom": "lBfrtip", // "p" ensures pagination is included in the layout
             "buttons": [
                {
                    extend: 'csvHtml5',
                    text: '<i class="fa fa-file-excel-o"></i>',
                    titleAttr: 'CSV',
                    filename: 'csv',
                    title: $('.download_label').html(),
                    exportOptions: {
                        columns: ':visible'
                    }
                },{
                    extend: 'excelHtml5',
                    text: '<i class="fa fa-file-excel-o"></i>',
                    titleAttr: 'Excel',
                    filename: 'Excel',
                    title: $('.download_label').html(),
                    exportOptions: {
                        columns: ':visible'
                    }
                },{
                        extend: 'pdfHtml5',
                        filename : $('.report_name').text(),
                        messageTop : $('.download_label').html(),
                        orientation: 'landscape',
                        pageSize: 'A3',
                        text: '<i class="fa fa-file-pdf-o"></i>',
                        titleAttr: 'PDF',
                        // changed logo code [vastvikta][05-05-2025]
                        customize: function ( doc ) {
                            
                            var logoBase64 = document.getElementById('pdf-logo-base64').innerText;
                            doc.images = doc.images || {};
                            doc.images.logo = logoBase64;
                        
                        doc.content.splice( 1, 0, {
                            margin: [ 0, 0, 0, 5 ],
                                alignment: 'left',
                                image: 'logo', 
                                 width: 250
                            } );
                        },
                        title: '.',
                        exportOptions: {
                            columns: ':visible'
                            
                        }
                    },{
                    extend: 'colvis',
                    text: '<i class="fa fa-columns"></i>',
                    titleAttr: 'Columns',
                    title: $('.download_label').html(),
                    postfixButtons: ['colvisRestore']
                },
            ],
        "ajax": {
            url: "omnichannel_config/fetchData.php",
            type: "POST",
            data: function(d) {
                d.startdatetime = $('#startdatetime').val();
                d.enddatetime = $('#enddatetime').val();
                d.status = $('#status').val();
                d.name = $('#name').val();
                d.action = 'twitter_queue_report';
            }
        }
    });
}
// Set an interval to refresh the table every 10 seconds
setInterval(function() {
    facebookReport.ajax.reload(null, false); // Reload data without resetting pagination
}, 10000);
// Submit form and reload data based on new filters
$('#twitter_queue_report_form').submit(function(e) {
    e.preventDefault();

    $('#twitter_queue_report').DataTable().destroy();
    var startdatetime = $('#startdatetime').val();
    var enddatetime = $('#enddatetime').val();
    var status = $('#status').val();
    var name = $('#name').val();

    fill_datatables_twitter_queue_report(startdatetime, enddatetime, status, name); // ✅ FIXED
});

// for  Twitter Queue Report [vastvikta][16-06-2025]
fill_datatables_twitter_dm();

// Function to initialize and fill the messeneger report data table
//  updated -- Roshni Gupta


var twitter_dm; // Keep the instance globally

let selectedtweet = new Set();
let isUserSelecting = false;

// Initialize DataTable
function fill_datatables_twitter_dm(startdatetime ='', enddatetime ='', searchfield = '',assigned_only = '',agent_search = '') {
    // Only initialize if not already done
    startdatetime = $('#startdatetime').val();
    enddatetime = $('#enddatetime').val();
    searchfield = $('#searchfield').val();
    assigned_only = $('#assigned_message').is(':checked') ? 1 : 0;
    agent_search = $('#agent_search').val();

    if (!$.fn.DataTable.isDataTable('#twitter_dm')) {
        twitter_dm = $('#twitter_dm').DataTable({
            "processing": true,
            "serverSide": true,
            "order": [],
            "pageLength": 25,
            "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
            "searching": false,
            "paging": true,
            "ajax": {
                url: "omnichannel_config/fetchData.php",
                type: "POST",
                data: function(d) {
                    d.startdatetime =     startdatetime;
                    d.enddatetime = enddatetime;
                    d.searchfield = searchfield;
                    d.assigned_only = assigned_only;
                    d.agent_search  =agent_search;
                    d.action = 'twitter_dm';
                }
            },
                "createdRow": function (row, data, dataIndex) {
                   var clr = data[8]; // Assuming clr value is in the ninth column
                if (clr == 'yellow') {
                    // $(row).addClass('flag-yellow');
                } else if (clr == 'red') {
                    $(row).addClass('mail-row');
                } else if (clr == 'green') {
                    // $(row).addClass('flag-green');
                }
            },
            "drawCallback": function(settings) {
                // Reinitialize Colorbox
                
                $(".ico-interaction2").colorbox({
                    iframe: true,
                    innerWidth: 800,
                    innerHeight: 550
                });

                // Highlight search terms
                
                var searchTerm = $('#searchfield').val();
                $('#twitter_dm tbody tr').each(function () {
                    applyHighlight($(this).find('td').eq(4), searchTerm);  // change .eq(4) if needed
                });
                $('.tweet-checkbox').each(function () {
                    if (selectedtweet.has(this.value)) {
                        this.checked = true;
                    }
                });
                updateSelectionUI();

            }
        });
    } else {
        // If already initialized, just reload data
        twitter_dm.ajax.reload(null, false);
    }
}

setInterval(function () {

    if (isUserSelecting) return;

    if (twitter_dm) {
        twitter_dm.ajax.reload(null, false);
    }

}, 10000);



function updateSelectionUI() {
    const count = selectedtweet.size;
    const total = $('.tweet-checkbox').length;

    if (count > 0) {
        $('#selected_countX').text(count + ' selected').show();
    } else {
        $('#selected_countX').hide();
        isUserSelecting = false; // resume auto refresh
    }

    $('#select-all-tweet').prop(
        'checked',
        total > 0 && count === total
    );
}
$('#select-all-tweet').on('change', function () {

    isUserSelecting = true;
    const checked = this.checked;

    $('.tweet-checkbox').each(function () {
        this.checked = checked;

        if (checked) {
            selectedtweet.add(this.value);
        } else {
            selectedtweet.delete(this.value);
        }
    });

    updateSelectionUI();
});
$(document).on('change', '.tweet-checkbox', function () {

    isUserSelecting = true;

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

    if (this.checked) {
        selectedtweet.add(id);
    } else {
        selectedtweet.delete(id);
    }

    updateSelectionUI();
});
$('#openAgentAssignX').on('click', function () {

    let selectedtweet = $('.tweet-checkbox:checked')
        .map(function () {
            return $(this).val();
        })
        .get();

    if (selectedtweet.length === 0) {
        alert('Please select at least one messages.');
        return;
    }

    // 🔥 self assign directly
    if (USER_GROUP === '070000') {
        assignTWEET(LOGGED_IN_USER_ID, selectedtweet);
        return;
    }

    $('#agentAssignX').stop(true, true).slideToggle();
});
$(document).on('click', '#assignNowBtnX', function () {

    let agentId;

    if (USER_GROUP === '070000') {
        agentId = LOGGED_IN_USER_ID;
    } else {
        agentId = $('#agentSelect').val();
    }

    let selectedtweet = $('.tweet-checkbox:checked')
        .map(function () {
            return $(this).val();
        })
        .get();

    if (USER_GROUP !== '070000' && !agentId) {
        alert('Please select an agent.');
        return;
    }

    if (selectedtweet.length === 0) {
        alert('Please select at least one tweet.');
        return;
    }

    assignTWEET(agentId, selectedtweet);
});
$('#unassignNowBtnX').on('click', function () {
    const selectedtweet = $('.tweet-checkbox:checked').map(function () {
        return $(this).val();
    }).get();

    if (selectedtweet.length === 0) {
        alert('Please select at least one messages.');
        return;
    }

    if (!confirm(`Are you sure you want to unassign ${selectedtweet.length} messages?`)) return;

    // Lock UI
    $('#unassignNowBtnX').prop('disabled', true).text('Unassigning...');
    $('.tweet-checkbox').prop('disabled', true);

    $.ajax({
        url: 'omnichannel_config/fetchData.php',
        method: 'POST',
        data: {
            action: 'unassign_agent_tweet',
            tweet_ids: selectedtweet
        },
        dataType: 'json',
        success: function (response) {
            alert(response.message || 'Unassignment completed.');
            setTimeout(function () {
                window.location.href = window.location.href;
            }, 100); // ✅ full page reload
        },
        error: function (xhr, status, error) {
            alert('Error occurred: ' + error);
        },
        complete: function () {
            $('#unassignNowBtnX').prop('disabled', false).text('Unassign');
            $('.tweet-checkbox').prop('disabled', false).prop('checked', false);
            $('#agentDropdownContainerX').slideUp();
        }
    });
});
/* ==============================
    RESET UI
=============================== */
function resetAssignUI() {
    $('#assignNowBtnX')
        .prop('disabled', false)
        .text('Assign');

    $('.tweet-checkbox')
        .prop('disabled', false)
        .prop('checked', false);

    $('#select-all-tweet').prop('checked', false);
    $('#selected_countX').hide().text('');
    $('#agentDropdownContainerX').slideUp();
}
// Initialize table on page load
$('#twitter_dm_form').submit(function(e) {
    e.preventDefault();

    $('#twitter_dm').DataTable().destroy();
    var startdatetime = $('#startdatetime').val();
    var enddatetime = $('#enddatetime').val();
    var searchfield = $('#searchfield').val();
    var assigned_only = $('#assigned_message').is(':checked') ? 1 : 0;
    var agent_search = $('#agent_search').val();

    fill_datatables_twitter_dm(startdatetime, enddatetime, searchfield,assigned_only,agent_search); // ✅ FIXED
});
// 🔹 Live search as user types

$('#searchfield').on('input', function () {
    if (twitter_dm) {
        twitter_dm.ajax.reload(null, false); // refresh table, keep pagination
    }
});
function assignTWEET(agentId, selectedtweet) {

    $('#assignNowBtnX')
        .prop('disabled', true)
        .text('Checking...');

    $('.tweet-checkbox').prop('disabled', true);

    $.ajax({
        url: 'omnichannel_config/fetchData.php',
        type: 'POST',
        dataType: 'json',
        data: {
            action: 'check_existing_assignment_tweet',
            tweet_ids: selectedtweet
        },

        success: function (checkResponse) {

            if (checkResponse.alreadyAssigned?.length > 0) {

                let confirmReassign = confirm(
                    'Some selected messages are already assigned.\nDo you want to unassign and reassign?'
                );

                if (!confirmReassign) {
                    resetAssignUI();
                    return;
                }

                // 🔥 Step 1: unassign
                unassignTWEET(selectedtweet, function () {

                    // 🔥 Step 2: assign
                    assignNowTWEET(agentId, selectedtweet);

                });

                return;
            }

            // direct assign if no conflict
            assignNowTWEET(agentId, selectedtweet);
        },

        error: function () {
            alert('Assignment check failed.');
            resetAssignUI();
        }
    });
} 
function assignNowTWEET(agentId, selectedtweet) {

    $('#assignNowBtnX').text('Assigning...');

    $.ajax({
        url: 'omnichannel_config/fetchData.php',
        type: 'POST',
        dataType: 'json',
        data: {
            action: 'assign_agent_tweet',
            agent_id: agentId,
            tweet_ids: selectedtweet,
            force_reassign: true
        },

        success: function (response) {
            alert(response.message || 'Assignment complete.');
            location.reload();
        },

        error: function () {
            alert('Assignment failed.');
        },

        complete: function () {
            resetAssignUI();
        }
    });
}function unassignTWEET(selectedtweet, callback) {

    $.ajax({
        url: 'omnichannel_config/fetchData.php',
        method: 'POST',
        data: {
            action: 'unassign_agent_tweet',
            tweet_ids: selectedtweet
        },
        dataType: 'json',

        success: function (response) {
            console.log('Unassigned:', response);

            if (callback) callback(); // 🔥 continue flow
        },

        error: function (xhr, status, error) {
            alert('Error during unassign: ' + error);
        }
    });
}


    var WhatsadataTable;

    function fill_datatables_whatsapp() {   
        if ($.fn.DataTable.isDataTable('#whatsapp_table')) {
            $('#whatsapp_table').DataTable().destroy();
        }

        WhatsadataTable = $('#whatsapp_table').DataTable({
            processing: false,
            serverSide: true,
            order: [],
            pageLength: 25,
            lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
            searching: false,
            ajax: {
                url: "omnichannel_config/fetchData.php",
                type: "POST",
                data: function(d) {  
                    d.startdatetime = $('#startdatetime').val();
                    d.enddatetime   = $('#enddatetime').val();
                    d.searchfield   = $('#searchfield').val();
                    d.phone         = $('#phone').val();
                    d.ICASEID       = $('#ICASEID').val();
                    d.send_from     = $('#send_from').val();
                    d.send_name     = $('#send_name').val();
                    d.id            = $('#inte_id').val();
                    d.action        = 'whatsapp';
                },
                error: function(xhr) {  
                    console.log("AJAX Error: ", xhr.responseText);
                }
            },
            createdRow: function(row, data) {
                var clr = data[9];
                if (clr == 'red') $(row).addClass('mail-row');
            },
            drawCallback: function() {
                $(".ico-interaction2").colorbox({
                    iframe: true,
                    innerWidth: 1000,
                    innerHeight: 550
                });

                var searchTerm = $('#searchfield').val();
                $('#whatsapp_table tbody tr').each(function() {
                    applyHighlight($(this).find('td').eq(4), searchTerm);
                });
            }
        });
    }

    // Initialize DataTable on load
    fill_datatables_whatsapp();

    // Reload table every 10 seconds
    setInterval(function() {
        if ($.fn.DataTable.isDataTable('#whatsapp_table')) {
            WhatsadataTable.ajax.reload(null, false);
        }
    }, 10000);

    // Dynamic filter (search field)
    $('#searchfield').on('input', function() {
        if (WhatsadataTable) {
            WhatsadataTable.ajax.reload(null, false);
        }
    });

    // Form submit event
    $('#post_whatsapp').submit(function(e) {
        e.preventDefault();
        fill_datatables_whatsapp();
    });

});

// Whatsapp code end
    $('#btn_delete').click(function() {
        if (confirm("Are you sure you want to delete this Email id?")) {
            var id = [];
            $(':checkbox:checked').each(function(i) {
                id[i] = $(this).val();
            });
            if (id.length === 0) //tell you if the array is empty
            {
                alert("Please Select atleast one checkbox");
            } else {
                $.ajax({
                    url: 'delete_emailqueue.php',
                    method: 'POST',
                    data: {
                        id: id
                    },
                    success: function(data) {
                        alert("Delete sucessfully!!!");
                        location.reload();
                    }
                });
            }
        } else {
            return false;
        }
    });
    
   //javascript functions  for web_email_complaint 
    //    $('.example').DataTable({
    //     "aaSorting": [],
    //     "ordering": false,
    //     "pageLength": 30,
    //     "dom": 'rtip'
    // });




    // Check or Uncheck All checkboxes
    $("#checkall").change(function() {
        var checked = $(this).is(':checked');
        if (checked) {
            $(".checkbox").each(function() {
                $(this).prop("checked", true);
            });
        } else {
            $(".checkbox").each(function() {
                $(this).prop("checked", false);
            });
        }
    });

    // Changing state of CheckAll checkbox 
    $(".checkbox").click(function() {

        if ($(".checkbox").length == $(".checkbox:checked").length) {
            $("#checkall").prop("checked", true);
        } else {
            $("#checkall").removeAttr("checked");
        }

    });


   // $('.date_class').datetimepicker();

});
//shifted from web_email_complaint.php
function clearText(field) {
    if (field.defaultValue == field.value) field.value = '';
    else if (field.value == '') field.value = field.defaultValue;
}
function CenterWindow(windowWidth, windowHeight, windowOuterHeight, url, wname, features) {
    var centerLeft = parseInt((window.screen.availWidth - windowWidth) / 2);
    var centerTop = parseInt(((window.screen.availHeight - windowHeight) / 2) - windowOuterHeight);

    var misc_features;
    if (features) {
        misc_features = ', ' + features;
    } else {
        misc_features = ', status=no, location=no, scrollbars=yes, resizable=yes';
    }
    var windowFeatures = 'width=' + 500 + ',height=' + 140 + ',left=' + centerLeft + ',top=' + centerTop +
    misc_features;
    var win = window.open(url, wname, windowFeatures);
    win.focus();
    return win;
}
function Centerss(windowWidth, windowHeight, windowOuterHeight, url, wname, features) {
    var centerLeft = parseInt((window.screen.availWidth - windowWidth) / 2);
    var centerTop = parseInt(((window.screen.availHeight - windowHeight) / 2) - windowOuterHeight);

    var misc_features;
    if (features) {
        misc_features = ', ' + features;
    } else {
        misc_features = ', status=no, location=no, scrollbars=yes, resizable=yes';
    }
    var windowFeatures = 'width=' + 600 + ',height=' + 500 + ',left=' + centerLeft + ',top=' + centerTop +
    misc_features;
    var win = window.open(url, wname, windowFeatures);
    win.focus();
    return win;
}
    
function delUser(id) {
    // alert(id);
    if (confirm("Are you sure to delete?")) {
        location.href = "web_email_complaint.php?act=del&id=" + id;
    }
}
function editcase(url) {
    window.open(url, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=100,left=200,width=500,height=300");
}

$('.set_button').click(function() {
  localStorage.setItem('session_set', '1');
});


function delUser(id) {
    // alert(id);
    if (confirm("Are you sure to delete?")) {
        location.href = "web_queue.php?act=del&id=" + id;
    }
}
function editcase(url) {
    window.open(url, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=100,left=200,width=500,height=300");
}

$('.reset_button').click(function() {
  localStorage.clear();
  var Token = btoa('email_complaint');
    window.location.href='omni_channel.php?token='+encodeURIComponent(Token);

});
//javascript functions  for subjectpopup.php to check Mail and delete mail 
function cheackMail(url)
{
	$.ajax({
      url: 'checkMail.php',
      type: 'post',
      data: {'id': Mid,'type': 'email'},
      success: function(data, status) {
      	$("#success-msg").html(data);
      	if(data!='') { return false; } 
      	else 
      	{ 
      		window.opener.location = url; window.close(); 
      	}
      },
      error: function(xhr, desc, err) {
        console.log(xhr);
        console.log("Details: " + desc + "\nError:" + err);
      }
    }); // end ajax call
}
function deleteMail() {
    if (confirm("Are you sure to delete this mail?")) {
        $.ajax({
            url: 'checkMail.php',
            type: 'post',
            data: {'id': Mid, 'del': 'del', 'type': 'email'},
            success: function(data, status) {
                $("#success-msg").html(data);
                if (data != '') {
                    return false;
                } else {
                    // Reload the page
                    location.reload();
                }
            },
            error: function(xhr, desc, err) {
                console.log(xhr);
                console.log("Details: " + desc + "\nError:" + err);
            }
        });
    }
}
//function for web_twitter.php to move the tweet to junkbox
function movetojunkbox(caseid) {
    if (confirm("Are you sure, the case should move to junkbox?")) {
        $.ajax({
            url: 'web_case_status_update.php',
            type: 'post',
            data: {
                'id': caseid,
                'type': 'twitter'
            },
            success: function(data, status) {
                alert(data); //return false;
                var encodedToken = btoa('twitter');
                window.location = 'omni_channel.php?token='+ encodeURIComponent(encodedToken); 
                /*   setTimeout(function(){
                                     window.location.href='admin-twitter_requests1.php';
                                  },2000);*/

                //$("#success-msg").html(data);
                /*if(data!='') { return false; } 
                else 
                { 
                  window.opener.cfrm.submit(); window.close();
                }*/
            },
            error: function(xhr, desc, err) {
                console.log(xhr);
                console.log("Details: " + desc + "\nError:" + err);
            }
        }); // end ajax call
    }
}
//function to delete the user in twitter 
function delUser(id) {
    if (confirm("Are you sure to delete?")) {
        location.href = "<?=$_SERVER[PHP_SELF] ?>?act=del&id=" + id;
    }
}
// Function to refresh the page
function refreshPage() {
    location.reload();
}
// Set the interval for refresh (2000 milliseconds = 10 seconds)
// setInterval(refreshPage, 150000);

// Changing state of CheckAll checkbox 
$(".channel_type_post").click(function() {
    if($(this).data('id') == '1'){
        $('.facebook_titile').text('Facebook Post');
        $('.messenger_div').removeClass('channel_active');
        $('.post_div').addClass('channel_active');
    }else{
        $('.facebook_titile').text('Facebook Messanger');
        $('.messenger_div').addClass('channel_active');
        $('.post_div').removeClass('channel_active');
    }
});


/**
 * ============================================================
 * File Name       : omnichannel.js
 * Module          : Interaction Queue Report (Omnichannel)
 * Description     : Initializes & manages DataTable for Interaction Queue Report
 *                  with server-side processing, filters, auto refresh,
 *                  export buttons (CSV/Excel/PDF), and Colorbox popup support.
 *
 * Developer       : Aarti Ojha
 * Remasterd by    : Farhan Akhtar
 * Last Modified   : 13-01-2026
 *
 * Notes:
 *  - Filters are applied via ajax.reload() (no destroy/rebuild on submit)
 *  - Safe auto refresh every 10 seconds
 *  - PDF export supports optional base64 logo injection
 *  - Supports Colorbox iframe popup on table redraw
 * ============================================================
 */

var intract_queueReport = null;

/**
 * Initialize Interaction Queue Report DataTable
 */
function initInteractionQueueReportTable() {

    // If already initialized, just reload
    if ($.fn.DataTable.isDataTable('#interaction_report')) {
        intract_queueReport.ajax.reload(null, false);
        return;
    }

    intract_queueReport = $('#interaction_report').DataTable({
        processing: true,
        serverSide: true,
        destroy: true,
        order: [],
        pageLength: 25,
        lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        searching: false,
        paging: true,
        dom: "lBfrtip",
        responsive: true, 
        scrollX: true,      // Allow horizontal scroll if needed
        scrollCollapse: true,
        autoWidth: false,   // Stop Datatable from forcing widths
        // stable header
        fixedHeader: true,
        columnDefs: [
            { targets: [0, 9], className: "dt-center", orderable: false },
            { targets: [4], className: "dt-message-col" }
        ],
        buttons: [
            {
                extend: 'csvHtml5',
                text: '<i class="fa fa-file-excel-o"></i>',
                titleAttr: 'CSV',
                filename: 'Interaction_Queue_Report',
                title: $('.download_label').html() || 'Interaction Queue Report',
                exportOptions: { columns: ':visible' }
            },
            {
                extend: 'excelHtml5',
                text: '<i class="fa fa-file-excel-o"></i>',
                titleAttr: 'Excel',
                filename: 'Interaction_Queue_Report',
                title: $('.download_label').html() || 'Interaction Queue Report',
                exportOptions: { columns: ':visible' }
            },
            {
                extend: 'pdfHtml5',
                filename: ($('.report_name').text() || 'Interaction_Queue_Report'),
                messageTop: ($('.download_label').html() || 'Interaction Queue Report'),
                orientation: 'landscape',
                pageSize: 'A3',
                text: '<i class="fa fa-file-pdf-o"></i>',
                titleAttr: 'PDF',
                title: '.',
                exportOptions: { columns: ':visible' },

                customize: function (doc) {
                    var logoBase64 = document.getElementById('pdf-logo-base64')?.innerText || '';
                    doc.images = doc.images || {};

                    if (logoBase64) {
                        doc.images.logo = logoBase64;
                        doc.content.splice(1, 0, {
                            margin: [0, 0, 0, 5],
                            alignment: 'left',
                            image: 'logo',
                            width: 250
                        });
                    }
                }
            },
            {
                extend: 'colvis',
                text: '<i class="fa fa-columns"></i>',
                titleAttr: 'Columns',
                title: $('.download_label').html() || 'Interaction Queue Report',
                postfixButtons: ['colvisRestore']
            }
        ],

        ajax: {
            url: "omnichannel_config/fetchData.php",
            type: "POST",
            data: function (d) {
                d.startdatetime = $('#startdatetime').val();
                d.enddatetime   = $('#enddatetime').val();
                d.channel       = $('#channel').val();
                d.user_email    = $('#user_email').val();
                d.agent_n       = $('#agent_n').val();
                d.product       = $('#product').val();
                d.requesttype   = $('#requesttype').val();
                d.action        = 'interaction_report';
            }
        },

        drawCallback: function () {

            //  Fix header/body width mismatch after every redraw
            this.api().columns.adjust();
            this.api().responsive.recalc();
            // Reinitialize Colorbox after table redraw
            $(".ico-interaction2").colorbox({
                iframe: true,
                innerWidth: 1000,
                innerHeight: 450
            });
        }
    });
}

/**
 * Apply filters (reload table)
 */
function applyInteractionQueueFilters() {
    if (intract_queueReport && $.fn.DataTable.isDataTable('#interaction_report')) {
        intract_queueReport.ajax.reload(null, true); // true = reset to page 1
    } else {
        initInteractionQueueReportTable();
    }
}

//  Init table first time
$(document).ready(function () {

    initInteractionQueueReportTable();

    //  Submit form -> apply filters
    $('#intraction_report_form').on('submit', function (e) {
        e.preventDefault();
        applyInteractionQueueFilters();
    });

    //  Optional: Auto reload when filter changes (uncomment if needed)
    /*
    $('#startdatetime,#enddatetime,#agent_n,#channel,#user_email,#product,#requesttype').on('change', function () {
        applyInteractionQueueFilters();
    });
    */

    //  Auto refresh every 10 seconds (safe)
    setInterval(function () {
        if (intract_queueReport && $.fn.DataTable.isDataTable('#interaction_report')) {
            intract_queueReport.ajax.reload(null, false); // false = keep current page
        }
    }, 10000);

    $('#resetBtn').on('click', function () {
        $('#intraction_report_form')[0].reset();
        applyInteractionQueueFilters();
    });

});

$("#user_email").select2({
    placeholder: "Select Customer",
    allowClear: true,
    width: "100%"
});



// ###################### Twitter post assign flow-Aarti-03-04-2026 ###############################
 $(document).on('click', '.assign-first-alert', function (e) {
        e.preventDefault();
        alert("First assign this conversation to agent, then you will be able to work on it.");
    });
    // Select all
    $(document).on('change', '#selectAllTwitter', function () {
        $('.twitterRowCheckbox').prop('checked', $(this).prop('checked'));
        updateTwitterSelectedCount();
    });

    // Single checkbox change
    $(document).on('change', '.twitterRowCheckbox', function () {
        updateTwitterSelectedCount();
    });

    function updateTwitterSelectedCount() {
        let count = $('.twitterRowCheckbox:checked').length;
        if (count > 0) {
            $('#selected_countX').text(count + ' conversation(s) selected').show();
        } else {
            $('#selected_countX').hide().text('');
        }
    }
    // Handle assignment or reassignment action
    $('#assignNowBtn_tweet').on('click', function () {

        // Example for Twitter selected rows
        const selectedPosts = $('.twitterRowCheckbox:checked').map(function () {
            return $(this).val();
        }).get();
        var assignMode= 'agent';
        let payload = {
            action: 'check_existing_assignment',
            mode: assignMode,
            post_ids: selectedPosts
        };

        let targetId = null;

        // ===============================
        // ASSIGN TO AGENT
        // ===============================
        if (assignMode === 'agent') {
            const agentId = $('#agentSelect').val();
            targetId = agentId;

            if (!agentId) {
                alert('Please select agent');
                return;
            }

            payload.agent_id = agentId;

        // ===============================
        // ASSIGN TO QUEUE
        // ===============================
        } else if (assignMode === 'queue') {
            const queueId = $('#queueSelect').val();
            targetId = queueId;

            if (!queueId) {
                alert('Please select queue');
                return;
            }

            payload.queue_id = queueId;

        // ===============================
        // SELF ASSIGN
        // ===============================
        } else if ($('#agentSelect').length && $('#agentSelect').val()) {
            const agentId = $('#agentSelect').val();
            targetId = agentId;
            payload.agent_id = agentId;
            payload.mode = 'agent';
            assignMode = 'agent';

        } else {
            alert('Please select Assign Agent or Assign Queue');
            return;
        }

        if (selectedPosts.length === 0) {
            alert('Please select at least one post.');
            return;
        }

        // Lock UI
        $('#assignNowBtn_tweet').prop('disabled', true).text('Checking...');
        $('.twitterRowCheckbox').prop('disabled', true);

        // ===============================
        // STEP 1: CHECK EXISTING ASSIGNMENT
        // ===============================
        $.ajax({
            url: 'omnichannel_config/fetchData.php',
            method: 'POST',
            dataType: 'json',
            data: payload,
            success: function (checkResponse) {

                let forceReassign = false;

                if (checkResponse.status && checkResponse.alreadyAssigned.length > 0) {

                    let msg = "Some selected posts are already assigned:\n\n";

                    checkResponse.alreadyAssigned.forEach(function (item, index) {
                        let assignInfo = [];

                        if (item.agent_name) {
                            assignInfo.push("Agent: " + item.agent_name);
                        }

                        if (item.queue_name) {
                            assignInfo.push("Queue: " + item.queue_name);
                        }

                        msg += (index + 1) + ". Post ID: " + item.post_id + " → " + assignInfo.join(" | ") + "\n";
                    });

                    msg += "\nDo you want to reassign these posts?";

                    forceReassign = confirm(msg);

                    if (!forceReassign) {
                        resetAssignUI();
                        return;
                    }
                }

                // ===============================
                // STEP 2: ASSIGN / REASSIGN
                // ===============================
                $('#assignNowBtn_tweet').text(forceReassign ? 'Reassigning...' : 'Assigning...');

                $.ajax({
                    url: 'omnichannel_config/fetchData.php',
                    method: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'twitter_assign_agent',
                        post_ids: selectedPosts,
                        force_reassign: forceReassign,
                        mode: assignMode,
                        target_id: targetId
                    },
                    success: function (response) {
                        alert(response.message || 'Assignment complete.');

                        // refresh your twitter table
                        $('#twitter_table').DataTable().ajax.reload(null, false);
                    },
                    error: function (xhr, status, error) {
                        alert('Error occurred: ' + error);
                    },
                    complete: function () {
                        resetAssignUI();
                    }
                });
            },
            error: function (xhr, status, error) {
                alert('Error checking assignments: ' + error);
                resetAssignUI();
            }
        });
    });

    // Reset UI helper
    function resetAssignUI() {
        $('#assignNowBtn_tweet').prop('disabled', false).text('Assign');
        $('.twitterRowCheckbox').prop('disabled', false);
    }
    $('#unassignNowBtn_tweet').on('click', function () {
        let selectedIds = [];

        $('.twitterRowCheckbox:checked').each(function () {
            selectedIds.push($(this).val());
        });

        if (selectedIds.length === 0) {
            alert('Please select at least one conversation.');
            return;
        }

        $.ajax({
            url: 'omnichannel_config/fetchData.php',
            type: 'POST',
            data: {
                tweet_ids: selectedIds,
                action:'twitter_unassign_agent'
            },
            dataType: 'json',
            success: function (res) {
                if (res.status === 'success') {
                    alert(res.message);
                    $('#twitter_table').DataTable().ajax.reload(null, false);
                    $('#selectAllTwitter').prop('checked', false);
                    $('#selected_countX').hide().text('');
                } else {
                    alert(res.message || 'Unassign failed.');
                }
            },
            error: function () {
                alert('Something went wrong while unassigning.');
            }
        });
    });