// let verifyData = {
//     id: '',
//     channel: '',
//     level: '',
//     file: ''
// };


let ckeditorInstance = null;

ClassicEditor
    .create(document.querySelector('#V_Content'), {
        toolbar: [
            'heading',
            '|',
            'bold', 'italic',
            '|',
            'bulletedList', 'numberedList',
            '|',
            'link',
            '|',
            'undo', 'redo'
        ],
        restrictedEditing: {
            allowedCommands: ['bold', 'italic', 'link']
        },
        htmlSupport: {
            allow: [
                {
                    name: /.*/,
                    attributes: true,
                    classes: true,
                    styles: true
                }
            ]
        }
    })
    .then(editor => {

        ckeditorInstance = editor;
        window.ckeditorInstance = editor;

        if (typeof DEFAULT_MAIL_SIGNATURE !== "undefined") {

            const editorHtml = `
                <p><br></p>
                <div data-cke-restricted-editing-exception="true"
                     class="mail-signature"
                     style="border-top:1px solid #ddd; padding-top:8px; margin-top:10px;">
                    ${DEFAULT_MAIL_SIGNATURE}
                </div>
            `;

            editor.setData(editorHtml);
        }
    })
    .catch(error => {
        console.error("CKEditor init error:", error);
    });


var img_path = '/assets/images/loading.gif';
   var base_url = window.location.origin;
    // Aarti : 20-12-2023 : get count list 
  function get_count_of_list(campaign_id) {
    var campaign_id = campaign_id ;
    $.ajax({
         type: "GET",
         url: "omnichannel_config/bulk_function.php",
         data: {
               'campaign_id': campaign_id,
               'action': 'ajax_campaign_contact_count',
            },
        success: function(data) {
          console.log('ajax_campaign_contact_count');
          console.log(data);
          $('#show-counts').empty();
          $('#show-counts').html(data);
                     
        },
        error: function(xhr, desc, err) {
        }
     });
  }
$(document).ready(function(){
  // var $jq = jQuery.noConflict();//added this line of code to correct the search by mobile no. for whatsapp and  sms bulk [vastvikta][06-12-2024]
  $('.select2bs4s').select2({
    theme: 'bootstrap4',
    maximumSelectionLength: 20
  })
  $('.selectchannel').select2({
    theme: 'bootstrap4',
    maximumSelectionLength: 10
  })
  $("#scheduletime2").on('change', function(event) {
    console.log('check date ');
    if($(this).is(':checked')){
      // $("#bulk_send_button").val('Save');
      $("#datepicker_div").show();
    }
    else{
      // $("#bulk_send_button").val('Send Now');
      $("#datepicker_div").hide();
    }
  });
  $('#custom-content-above-profile-tab').on('click',function(){
   $('#custom-content-above-home').removeClass('show');
  })

   // Aarti : 20-12-2023 : Save Bulk Upload File 
  $("#select_file_name").on('change', function(){
    var selected_val = $(this).val();
    if(selected_val != '0'){
      $("#upload_file_div").hide();
      $("#file_name_div").hide();
      $("#desc_div").hide();
      $("#divider_row").hide();
    }else{
      $("#upload_file_div").show();
      $("#file_name_div").show();
      $("#desc_div").show();
      $("#divider_row").show();
    }
    $("#file").val('');
  });
  function validateBulkForm() {

    let channel = $("input[name='channel_type']").val(); // SMS / Email / WhatsApp
    let isEdit  = $("#edit_id").val() !== "";

    let message = $(".messagebulk").val().trim();
    let subject = $("#description").val()?.trim();
    let campaign = $("#list_name").val().trim();
    let fileSelected = $("#file").val();
    let oldFile = $("#old_file").val();

    // Campaign name required
    if (campaign === "") {
        alert("Campaign name is required");
        $("#list_name").focus();
        return false;
    }

    // Message required
    if (message === "") {
        alert("Message is required");
        $("#message").focus();
        return false;
    }

    // Email requires subject
    if (channel === "Email" && subject === "") {
        alert("Email Subject is required");
        $("#description").focus();
        return false;
    }

    // File validation
    if (!isEdit && oldFile === "") {
        // Create mode → file mandatory
        if (fileSelected === "") {
            alert("Please select a CSV file");
            $("#file").focus();
            return false;
        }
    } else {
        // Edit mode → at least old or new file
        if (fileSelected === "" && oldFile === "") {
            alert("Please select a CSV file");
            $("#file").focus();
            return false;
        }
    }

    // File type check
    if (fileSelected !== "") {
        let ext = fileSelected.split('.').pop().toLowerCase();
        if (ext !== "csv") {
            alert("Only CSV files are allowed");
            $("#file").val("");
            return false;
        }
    }

    return true;
}
// multi-file upload with file name display and a close (remove) icon [Aarti][01-05-2025]
const fileInput = document.getElementById('fileInput');
const fileList = document.getElementById('fileList');

let filesArray = [];

fileInput.addEventListener('change', (event) => {
  for (let file of event.target.files) {
    filesArray.push(file);
  }
  renderFileList();
  fileInput.value = ''; // allow same file reselect
});

function renderFileList() {
  fileList.innerHTML = '';
  filesArray.forEach((file, index) => {
    const item = document.createElement('div');
    item.className = 'file-item';
    item.innerHTML = `
      <span class="file-name">${file.name}</span>
      <span class="remove-file" onclick="removeFile(${index})">&times;</span>
    `;
    fileList.appendChild(item);
  });
}

// function removeFile(index) {
//   filesArray.splice(index, 1);
//   renderFileList();
// }
// ✅ Event delegation
fileList.addEventListener('click', function (e) {
  if (e.target.classList.contains('remove-file')) {
    const index = e.target.dataset.index;
    filesArray.splice(index, 1);
    renderFileList();
  }
});
$(document).on("click","#cancelEditBtn",function(){
    resetBulkForm();
});
$('#import_form').on('submit', function (event) {
    event.preventDefault();

    if (!validateBulkForm()) return;

    const listName = $('#list_name').val().trim();
    const editId   = $('#edit_id').val() || 0;

    // 🔍 Check duplicate campaign name FIRST
    $.ajax({
        url: "omnichannel_config/bulk_function.php",
        type: "POST",
        data: {
            action: 'check_campaign_name',
            list_name: listName,
            edit_id: editId
        },
        success: function (res) {

            let obj;
            try {
                obj = JSON.parse(res);
            } catch (e) {
                alert("Invalid response");
                return;
            }

            if (obj.status === 'fail') {
                alert(obj.message);
                $('#list_name').focus();
                return;
            }

            // ✅ Name OK → proceed with actual save
            submitBulkForm();
        }
    });
});
function submitBulkForm() {

    const $btn = $("#bulk_send_button");
    $btn.prop('disabled', true).val('Please Wait...');

    let formData = new FormData($('#import_form')[0]);

    formData.delete('attachments[]');

    filesArray.forEach(file => {
        formData.append('attachments[]', file);
    });

    $.ajax({
        url: "omnichannel_config/bulk_function.php",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,

        success: function (res) {

            $btn.prop('disabled', false).val('Save');

            let obj;
            try {
                obj = JSON.parse(res);
            } catch (e) {
                alert("Invalid server response");
                return;
            }

            if (obj.status === 'fail') {
                alert(obj.message || 'Error occurred');
                return;
            }

            // ✅ SUCCESS
            alert(obj.message || 'Saved successfully');

            if ($.fn.DataTable.isDataTable('#bulks_report')) {
                intract_queueReport.ajax.reload(null, false);
            }

            resetBulkForm();
        },

        error: function () {
            $btn.prop('disabled', false).val('Save');
            alert('Server error. Please try again.');
        }
    });
}

// Aarti : 20-12-2023 : Save Bulk Upload File 
// $('#import_form').on('submit', function (event) {
//       event.preventDefault();

//       if (!validateBulkForm()) return;

//       const $btn = $("#bulk_send_button");
//       $btn.prop('disabled', true).val('Please Wait...');

//       // ✅ Full form data
//       let formData = new FormData(this);

//       // ✅ Remove native attachment field (avoid duplicates)
//       formData.delete('attachments[]');

//       // ✅ Append custom attachment array
//       filesArray.forEach(file => {
//           formData.append('attachments[]', file);
//       });

//       $.ajax({
//           url: "omnichannel_config/bulk_function.php",
//           type: "POST",
//           data: formData,
//           processData: false,
//           contentType: false,

//           success: function (res) {
//               $btn.prop('disabled', false).val('Save');

//               let obj;
//               try {
//                   obj = JSON.parse(res);
//               } catch (e) {
//                   alert("Invalid server response");
//                   return;
//               }

//               if (obj.status === 'fail') {

//                   // Clear old errors
//                   $('.error').html('');

//                   $.each(obj.msg, function (key, value) {
//                       $('.' + key + '_error').html(value);
//                   });

//                   // Overwrite confirm
//                   if (obj.error_type === '1') {
//                       if (confirm('Overwrite existing list?\nOK = overwrite\nCancel = new upload')) {
//                           $("#file_upload_type").val('overwrite');
//                       } else {
//                           $("#file_upload_type").val('no_new');
//                       }
//                       $('#import_form').trigger('submit');
//                   }

//                   // allow submit normally
//                   $('#list_name').prop('readonly', false)
//                                  .removeClass('bg-light');

//                   // hide cancel after submit
//                   $('#cancelEditBtn').addClass('d-none');

//                   return;
//               }

//               // ✅ SUCCESS FLOW
//               alert(obj.message || 'Saved successfully');

//               // 🔁 Reload DataTable WITHOUT page refresh
//               if ($.fn.DataTable.isDataTable('#bulks_report')) {
//                   intract_queueReport.ajax.reload(null, false);
//               }

//               // ♻️ Reset form
//               resetBulkForm();

//           },

//           error: function () {
//               $btn.prop('disabled', false).val('Save');
//               alert('Server error. Please try again.');
//           }
//       });
//   });

  function resetBulkForm() {
      // Reset form fields
      $('#import_form')[0].reset();

      // Reset mode
      $('#form_mode').val('create');
      $('#edit_id').val('');

      // Clear attachments UI
      filesArray = [];
      $('#fileList').html('');

      // Reset select2
      // $('#selecttemplate, #select_file_name').val('0').trigger('change');

      // 🔥 FIX: Hide existing attachment properly
        $('#oldAttachmentBox').hide();
        $('#oldAttachmentLink').text('').attr('href', '');

        // allow submit normally
        $('#list_name').prop('readonly', false)
                   .removeClass('bg-light');

       $('#list_name').removeClass('bg-light');

      // Hide old file box
      $('#oldFileBox').hide();
      $('#oldFileLink').text('').attr('href', '');
      $('#old_file').val('');

      // Clear editor
      // if (typeof CKEDITOR !== 'undefined' && CKEDITOR.instances.V_Content) {
      //     CKEDITOR.instances.V_Content.setData('');
      // } else {
      //     $('#V_Content').val('');
      // }

      ckeditorInstance.setData(
          DEFAULT_MAIL_SIGNATURE
      );

      // Hide schedule picker
      $('#scheduletime2').prop('checked', false);
      $('#datepicker_div').hide();

       $('#cancelEditBtn').addClass('d-none');

      // Reset button text
      $('#bulk_send_button').val('Create Campaign');
  }

  $("#quickForm").submit(function (e) {
        $("[class$='_error']").html("");
        $(".custom_loader").html('<img src="' + img_path + '">');
        var url = $(this).attr('action'); // the script where you handle the form input.
        $("#single_send_button").prop('disabled', true).text('Please Wait...');
        $.ajax({
            type: "POST",
            dataType: 'JSON',
            url:"omnichannel_config/bulk_function.php",
            data: $("#quickForm").serialize(), // serializes the form's elements.
            success: function (data){
               console.log(data);
               if (data.st === 1) {
                 $.each(data.msg, function (key, value) {
                     $('.' + key + "_error").html(value);
                 });
               }else if (data.st === 2) {
                  errorMsg(data.msg);
               } else {
                  $(".custom_sms").html(data.msg);
                  setTimeout(function(){
                    location.reload();
                  },2000);
               }
               $(".custom_loader").html("");
               $("#single_send_button").prop('disabled', false).text('Save');
            },
            error: function (jqXHR, textStatus, errorThrown){
               $("#single_send_button").prop('disabled', false).text('Save');
               $(".custom_loader").html("");   
            }
        });
        e.preventDefault(); // avoid to execute the actual submit of the form.
  });


  /* 
    * AUTHOR :: FARHAN AKHTAR
    * LAST MODIFIED ON :: 13-02-2025
    * PURPOSE :: TO IMPLEMENT FUNCTIONALLITY FOR GENERATE LIST (EXCEL SHEET) OF EMAILS (DATE WISE). 
  */

  $("#BulkEmailSubmit").click(function(event) {
    var startDate = $("#BulkEmailStartDate").val();
    var endDate = $("#BulkEmailEndDate").val();
    var dateTimePattern = /^(\d{2})-(\d{2})-(\d{4}) (\d{2}):(\d{2}):(\d{2})$/;

    // Check if both fields are filled
    if (startDate === "" || endDate === "") {
        alert("Both Start Date and End Date are required.");
        return;
    }

    // Validate the format dd-mm-yyyy hh:mm:ss
    if (!dateTimePattern.test(startDate) || !dateTimePattern.test(endDate)) {
        alert("Please enter the date and time in dd-mm-yyyy hh:mm:ss format.");
        return;
    }

    // Redirect to PHP script for CSV download
    window.location.href = "omnichannel_config/bulk_function.php?startDate=" + startDate + "&endDate=" + endDate + "&action=GET-EMAIL-LIST";
});
$(document).on('click','.bulkDownload',function(){

    $('#bulk_queue_session').val($(this).data('session'));
    $('#bulk_campaign_name').val($(this).data('name'));

    $('#BulkEmailStartDate').val('');
    $('#BulkEmailEndDate').val('');

    $('#bulkDownloadModal').modal('show');
});


  // END

});
// If condition work for reply section 
//Initialize Select2 Elements : Multiple select
$(function() {
    $('.select2bs4').select2({
        ajax: {
            delay: 250,
            url: 'omnichannel_config/bulk_function.php',
            dataType: 'json',
            data: function(params) {
                var queryParameters = {
                    q: params.term,
                    'action':'get_contact_list'
                }

                return queryParameters;
            },
            processResults: function(data) {
                // Transforms the top-level key of the response object from 'items' to 'results'
                return {
                    results: data
                };
            }
        },
        placeholder: 'Search for a contact',
        minimumInputLength: 3,
        maximumSelectionLength: 100
    });
});
// for Schedule toggle : Checkbox 
  $("#scheduletime").click(function () {
      if ($(this).is(":checked")) {
        $("#single_send_button").text('Save');
       $("#hi").show();
      } else {
        $("#single_send_button").text('Send Now');
       $("#hi").hide();
      }
  });
   // aarti::  Template Redirect in textarea with Current Value :21-12-2023
  $( "input[name='customRadio2']" ).on( "click", function() {
   var tempname = $("input:checked").val();
   var currentVal = $("#output").val();
   console.log('currentVal '+currentVal);
   console.log('tempname '+tempname);
    
   $.ajax({
        url: "omnichannel_config/bulk_function.php",
        type: "POST",
        data : {"tempname" : tempname,'action':'get_template_content'},
        success: function(data) {
          var obj = JSON.parse(data);
          var temp_content = obj.template_content;
         // $("#message").val(currentVal+'\n'+temp_content);     
        },
        error: function(xhr, desc, err) {
          console.log(xhr);
          console.log("Details: " + desc + "\nError:" + err);
        }
    });
  });
    $(document).on('change', '#select_file_name', function () {
        var campaign_id = $(this).val();
        if (!campaign_id || campaign_id === '0') return;

        $.ajax({
            url: "omnichannel_config/bulk_function.php",
            type: "POST",
            data: {
                action: "get_campaign_content",
                campaign_id: campaign_id
            },
            success: function (res) {

                let obj;
                try {
                    obj = JSON.parse(res);
                } catch (e) {
                    console.error("Invalid JSON:", res);
                    return;
                }

                /* ========= MODE ========= */
                // $('#form_mode').val('edit');
                // $('#edit_id').val(obj.id);

                // selected file upload
                // lock file unless replaced
                var file= obj.file_name;;

                // show old file
                if(file != "" && file != null){
                    $("#oldFileBox").show();
                    $("#oldFileLink")
                        .text(file)
                        .attr("href","../../storage/bulkcampaign/"+file);

                    $("#old_file").val(file);
                }else{
                    $("#oldFileBox").hide();
                    $("#old_file").val("");
                }

                /* ========= CAMPAIGN NAME ========= */
                $('#list_name').val(obj.list_name);
                
                //subject for email
                 $("#description").val(obj.slug);

                /* ========= MESSAGE (CKEditor) ========= */
                if (ckeditorInstance && obj.description) {
                    ckeditorInstance.setData(obj.description);
                }

                /* ========= FILE NAME ========= */
                // if (obj.file_name) {
                    // $('#select_file_name').val(obj.file_name).trigger('change.select2');
                // }

                /* ========= SCHEDULE ========= */
                if (obj.is_scheduled == 1 && obj.scheduled_time !== '0000-00-00 00:00:00') {

                    $('#scheduletime2').prop('checked', true);
                    $('#datepicker_div').show();

                    // // Convert DB datetime → 27-01-2026 14:45
                    // let dt = moment(obj.scheduled_time, 'YYYY-MM-DD HH:mm:ss')
                    //             .format('DD-MM-YYYY HH:mm');
                     let schedule = obj.scheduled_time; // "31-01-2026 14:57"
                    // $('#pickdate')
                    // .datetimepicker('setOptions', { value: schedule });

                    // $('#pickdate').val(dt);
                    $("#pickdatenew").val(schedule);
                } else {
                    $('#scheduletime2').prop('checked', false);
                    $('#datepicker_div').hide();
                    $('#pickdatenew').val('');
                }

                /* ========= EXISTING ATTACHMENT ========= */
                if (obj.attachments) {
                    $('#oldAttachmentBox').show();
                    $('#oldAttachmentLink')
                        .text(obj.attachments.split('/').pop())
                        .attr('href', '../../' + obj.attachments);
                    $('#old_file').val(obj.attachments);
                } else {
                    $('#oldAttachmentBox').hide();
                }

                /* ========= BUTTON TEXT ========= */
                // $('#bulk_send_button').val('Update Campaign');
            }
        });
    });


   // aarti::  Template Redirect in textarea with Current Value :02-01-2025
let userTypedText = "";
let lastTemplate = "";

$("#message").on("input", function () {
    // Save only when no template is selected
    if ($("#selecttemplate").val() == "0") {
        userTypedText = $(this).val();
    }
});

$("#selecttemplate").on("change", function () {

    let tempname = $(this).val();

    // If template is unselected → restore user text
    if (tempname == "") {
        $("#message").val(userTypedText);
        lastTemplate = "";
        return;
    }

    $.ajax({
        url: "omnichannel_config/bulk_function.php",
        type: "POST",
        data: { tempname: tempname, action: 'get_template_content' },
        success: function (data) {
            let obj = JSON.parse(data);
            let template = obj.template_content || "";

            // Replace previous template instead of appending
            $(".messagebulk").val(userTypedText + "\n" + template);
            lastTemplate = template;

            if (!template || !ckeditorInstance) return;

            let formattedContent =
                '<p>' + template.replace(/\n/g, '</p><p>') + '</p>';

            ckeditorInstance.setData(
                formattedContent +  DEFAULT_MAIL_SIGNATURE
            );

        }
    });
});


  // aarti::  Get hidden Value textarea  :21-12-2023
  $(".messagebulk").keyup(function(event){
    event.preventDefault();
      // Getting the current value of textarea
      var currentText = $(this).val();
      console.log('currentText');
      console.log(currentText);
      // Setting the Div content
      $("#outputid").val(currentText);
  });
  $('.pickdate').datetimepicker({
    format : 'd-m-Y H:i',
    formatTime: 'H:i',
    formatDate : 'd-m-Y',
    step : 30,
    minDate:new Date()
  });

/**
 * ============================================================
 * 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       : 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 initBulkQueueReportTable() {

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

    intract_queueReport = $('#bulks_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",

        buttons: [
            {
                extend: 'csvHtml5',
                text: '<i class="fa fa-file-excel-o"></i>',
                titleAttr: 'CSV',
                filename: 'Bulk_Queue_Report',
                title: $('.download_label').html() || 'Bulk Report',
                // exportOptions: { columns: ':visible' }
                exportOptions: {
                    columns: ':visible:not(:last-child)'
                },
            },
            {
                extend: 'excelHtml5',
                text: '<i class="fa fa-file-excel-o"></i>',
                titleAttr: 'Excel',
                filename: 'Bulk_Queue_Report',
                title: $('.download_label').html() || 'Bulk Report',
                // exportOptions: { columns: ':visible' },
                exportOptions: {
                    columns: ':visible:not(:last-child)'
                },
            },
            {
                extend: 'pdfHtml5',
                filename: ($('.report_name').text() || 'Bulk_Queue_Report'),
                messageTop: ($('.download_label').html() || 'Bulk Report'),
                orientation: 'landscape',
                pageSize: 'A3',
                text: '<i class="fa fa-file-pdf-o"></i>',
                titleAttr: 'PDF',
                title: '.',
                // exportOptions: { columns: ':visible' },
                exportOptions: {
                    columns: ':visible:not(:last-child)'
                },

                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/bulk_function.php",
            type: "POST",
            data: function (d) {
                d.campaign = $('#channel_type').val();
                d.action        = 'bulkcampaign_report';
            }
        },

        drawCallback: function () {
            // Reinitialize Colorbox after table redraw
            $(".ico-interaction2").colorbox({
                iframe: true,
                innerWidth: 1000,
                innerHeight: 450
            });
           // Only if dropdown closes instantly due to table redraw
            $('.dropdown-toggle').on('click', function (e) {
                e.stopPropagation();
            });
        }
    });
}

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

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

    initBulkQueueReportTable();

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

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

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

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

});
// let verifyData = {};

// // open modal
// $(document).on('click', '.verify-post', function () {

//     verifyData.id      = $(this).data('id');
//     verifyData.channel = $(this).data('channel_type');
//     verifyData.post    = $(this).data('post');
//     verifyData.level    = $(this).data('level');

//     $('#verifyPostContent').text(verifyData.post);
//     $('#verifyRemark').val('');

//     $('#verifyPostModal').modal('show');
// });


// function for verification modal close of the  post [vastvikta][23-12-2025]
$(document).on('click', '#cancelVerifyModal', function () {
    $('#verifyPostModal').modal('hide');
});
function submitPostAction(actionType){
    let remark = $('#verifyRemark').val().trim();
    if(remark==""){
        alert("Please enter remark");
        return;
    }
    $.ajax({
        url: 'omnichannel_config/bulk_function.php',
        type: 'POST',
        data: {
            action: 'level_second_final_approve_bulk',
            id: verifyData.id,
            channel_type: verifyData.channel,
            remark: remark,
            level: verifyData.level,
            action_type: actionType   // VERIFY / REJECT
        },
        success: function (res) {
            $('#verifyPostModal').modal('hide');
            alert(actionType + " Success");
            $('#viewModal').modal('hide');
            // 🔁 Reload DataTable WITHOUT page refresh
            if ($.fn.DataTable.isDataTable('#bulks_report')) {
              intract_queueReport.ajax.reload(null, false);
            }
        },
        error: function () {
            alert('Failed to process');
        }
    });
}
$(document).on('click','#confirmVerifyBtn',function(){
    submitPostAction("VERIFY");
});

$(document).on('click','#rejectPostBtn',function(){
    submitPostAction("REJECT");
});
$(document).on('click','.view-remarks',function(){

    let json = $(this).attr('data-remarks');

    if(json=="" || json=="null"){
        alert("No remarks found");
        return;
    }

    let data = JSON.parse(json);
    let html = "";

    data.forEach(function(r){
        html += `
            <tr>
                <td>${r.user_id}</td>
                <td><b>${r.action}</b></td>
                <td>${r.channel}</td>
                <td>${r.remark}</td>
                <td>${r.datetime}</td>
            </tr>
        `;
    });

    $("#remarksTable").html(html);
    $("#remarksModal").modal("show");
});

$(document).on("click",".editBulk",function(){

    let id = $(this).data("id");  
    // Open collapse form on edit click
  if (!$("#bulkFormBody").is(":visible")) {
    $("#bulkFormBody").slideDown(250);
    $("#bulkToggleIcon").removeClass("fa-plus").addClass("fa-minus");
}
     $("#bulk_send_button")
        .val("Update Campaign")
        .removeClass("btn-info")
        .addClass("btn-warning");
    
    $("#form_mode").val("edit");

    $("#form_action").val("update_bulk_campaign");

    $("#edit_id").val(id);
    $("#list_name").val($(this).data("list_name"));

    $("#import_form").append('<input type="hidden" name="edit_id" id="edit_id" value="'+id+'">');


    // $("#list_name").val($(this).data("subject"));
    var formattedContent = $(this).data("message");
    if (!formattedContent || !ckeditorInstance) return;
      ckeditorInstance.setData(
          formattedContent 
      );
    $("#description").val($(this).data("subject"));

    console.log($(this).data("schedule"));
     if ($(this).data("sflag") == '1') {
        $("#scheduletime2").prop("checked", true);
        $("#datepicker_div").show();
        $("#pickdatenew").val($(this).data("schedule"));

        // let schedule = $(this).data("schedule"); // "31-01-2026 14:57"
        // $('#pickdate').datetimepicker('setOptions', { value: schedule });

        // $('#pickdate').datetimepicker('setOptions', {
        //     minDate: false,
        //     value: schedule
        // });
    } else {
        $("#scheduletime2").prop("checked", false);
        $("#datepicker_div").hide();
        $("#pickdatenew").val('');
    }
    // 🔒 Make campaign name readonly
    $('#list_name').prop('readonly', true)
                   .addClass('bg-light');

    // lock file unless replaced
    var file= $(this).data("file");

    // show old file
    if(file != "" && file != null){
        $("#oldFileBox").show();
        $("#oldFileLink")
            .text(file)
            .attr("href","../../storage/bulkcampaign/"+file);

        $("#old_file").val(file);
    }else{
        $("#oldFileBox").hide();
        $("#old_file").val("");
    }
    let attachment = $(this).data("attachments");
    if(attachment){
        $("#oldAttachmentBox").show();
        $("#oldAttachmentLink").text(attachment.split('/').pop())
                               .attr("href","../../"+attachment);
        $("#old_attachments").val(attachment);
    } else {
        $("#oldAttachmentBox").hide();
        $("#old_attachments").val('');
    }
    $('#cancelEditBtn').removeClass('d-none');
    $("html,body").animate({scrollTop:0},300);

});


$("#removeOldFile").on("click",function(){
    $("#oldFileBox").hide();
    $("#old_file").val("");
});
$("#removeOldAttachment").on("click",function(){
    $("#oldAttachmentBox").hide();
    $("#old_attachments").val('');
});

  // ✅ Prevent entering more than 12 digits in the Select2 search box
$(document).on('input', '.select2-search__field', function () {
  let val = $(this).val();
  // added this so this code doesn't triggers for email search[vastvikta][07-11-2025]
  if (select.hasClass('email-select') || select.attr('id') === 'email') return;

  // Allow only numbers
  if (!/^\d*$/.test(val)) {
    alert('Only numeric characters are allowed.');
    $(this).val(val.replace(/\D/g, '')); // remove non-numeric characters
    return;
  }

  // Limit to 12 digits
  if (val.length > 12) {
    alert('You cannot enter more than 12 digits.');
    $(this).val(val.slice(0, 12)); // trim to 12 digits
  }
});

//In email field, matching emails should move to the top,and if the email doesn’t exist, it should be added as a new entry.[Roshni][10-11-2025]
 $(document).ready(function() {
    $('#email').select2({
      tags: true,
      placeholder: "Select or type email",
      allowClear: true,
      createTag: function (params) {
        var term = $.trim(params.term);
        if (term === '' || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(term)) {
          return null;
        }
        return {
          id: term,
          text: term,
          newTag: true
        }
      },
      sorter: function(data) {
        var query = $('.select2-search__field').val().toLowerCase();
        
        if (!query) {
          return data;
        }
        
        // Sort results: exact matches first, then starts with, then contains
        return data.sort(function(a, b) {
          var aText = a.text.toLowerCase();
          var bText = b.text.toLowerCase();
          
          // New tags (manually entered emails) go to bottom
          if (a.newTag && !b.newTag) return 1;
          if (!a.newTag && b.newTag) return -1;
          
          // Exact match
          var aExact = aText === query ? 1 : 0;
          var bExact = bText === query ? 1 : 0;
          if (aExact !== bExact) return bExact - aExact;
          
          // Starts with query
          var aStarts = aText.indexOf(query) === 0 ? 1 : 0;
          var bStarts = bText.indexOf(query) === 0 ? 1 : 0;
          if (aStarts !== bStarts) return bStarts - aStarts;
          
          // Contains query
          var aContains = aText.indexOf(query) !== -1 ? 1 : 0;
          var bContains = bText.indexOf(query) !== -1 ? 1 : 0;
          if (aContains !== bContains) return bContains - aContains;
          
          // Alphabetical order
          return aText.localeCompare(bText);
        });
      }
    });
    
    const maxChars = '<?=$maxLength?>';

    $("#message").on('input', function() {
        var text = $(this).val();

        if (text.length > maxChars) {
            text = text.substring(0, maxChars);
            $(this).val(text);
        }

        // Update hidden textarea
        $("#output").val(text);

        // Update live character count
        $("#char-count").text(text.length + " / " + maxChars + " characters");
    });
});

$(document).ready(function() {  

  var activeTab = localStorage.getItem('activeTab');
  if (activeTab) {
      $('.btn-tab').removeClass('active');
      $('.tab-pane').removeClass('show active');

      $('.btn-tab[data-tab="' + activeTab + '"]').addClass('active');
      $($('.btn-tab[data-tab="' + activeTab + '"]').data('target')).addClass('show active');
  }

  // TAB SWITCHING  
  $('.btn-tab').click(function(e) {  
    e.preventDefault();  
    
    var tabKey = $(this).data('tab');
    localStorage.setItem('activeTab', tabKey);

    $('.btn-tab').removeClass('active');  
    $(this).addClass('active');  

    $('.tab-pane').hide();  
    var target = $(this).data('target');  

    if (target === '#custom-content-above-profile') {  
      $('#custom-content-above-tabContent').hide();  
      $('#custom-content-above-profile').show();  
    } else {  
      $('#custom-content-above-tabContent').show();  
      $('#custom-content-above-profile').hide();  
      $(target).show();  
    }  
  });  

  // EDIT MODAL OPEN  
  $(document).on('click', '.viewMsg', function() { 
    const msg = $(this).data('msg');
    $('#viewModalBody').text(msg);
    $('#viewModal').modal('show'); 
  });
  $(document).on('click', '.editMsg', function() {  
    var id = $(this).data('id');  
    var msg = $(this).data('msg');  
    var schedule = $(this).data('schedule');  

    $('#edit_id').val(id);  
    $('#edit_message').val(msg);  

    if (schedule && schedule != '0000-00-00 00:00:00') {  
      var dt = new Date(schedule);  
      var local = dt.toISOString().slice(0,16);  
      $('#edit_schedule').val(local);  
    } else {  
      $('#edit_schedule').val('');  
    }  

    $('#editModal').modal('show');  
  });  

  // CLOSE EDIT MODAL  
  $('#closeEditModal').click(function(){  
    $('#editModal').modal('hide');  
  });  

  // FORM SUBMIT  
  $('#editForm').submit(function(e){  
    e.preventDefault();  
    var id = $('#edit_id').val();  
    var message = $('#edit_message').val();  
    var schedule = $('#edit_schedule').val();  
    var channel =  $('#channelsingle').val(); 
    $.ajax({  
      url: '',  // same page  
      type: 'POST',  
      data: { action: 'update_sms', id: id, message: message, schedule: schedule,channel:channel },  
      success: function(response){  
        alert("Message Updated Successfully");  
        window.location.reload();  
      }  
    });  
  });  

  // CLOSE VIEW MODAL  
  $('#closeModal').click(function(){  
    $('#viewModal').modal('hide');  
  });  

  // DELETE MESSAGE  
  $(document).on('click', '.deleteMsg', function(e) {  
    e.preventDefault();  
    var id = $(this).data('id');  
    var channel  = $(this).data('channel');
    var row = $('#row_' + id);

    if (!confirm("Are you sure you want to delete this message?")) {  
      return;  
    }  

    $.ajax({  
      url: '', // same page  
      type: 'POST',  
      data: { action: 'delete_sms', id: id ,channel:channel},  
      success: function(response) {  
        alert("Record Deleted Successfully"); 

        row.fadeOut(300, function () {
            $(this).remove();
        }); 
        // window.location.reload();  
      },  
      error: function() {  
        alert('Error contacting server.');  
      }  
    });  
  });  
});  

// $(document).on('click', '.viewMsg', function () {

//     let subject     = $(this).data('subject');
//     let message     = $(this).data('message');   // HTML message
//     let attachments = $(this).data('attachments'); // string or JSON
//     let channel     = $(this).data('channel');

//     /* SUBJECT */
//     if (channel === 'Email') {
//         $("#viewSubjectBox").show();
//         $("#viewSubject").text(subject);
//     } else {
//         $("#viewSubjectBox").hide();
//     }

//     /* MESSAGE (HTML RENDER FIX) */
//     $("#viewMessage").html(message);  // ✅ NOT .text()

//     /* ATTACHMENTS */
//     $("#viewAttachments").html('');
//     if (attachments) {
//         $("#viewAttachmentBox").show();

//         let files = attachments.split(',');

//         files.forEach(file => {
//             let filePath = "../../" + file.trim();
//             let ext = file.split('.').pop().toLowerCase();

//             let previewHtml = '';

//             if (['jpg','jpeg','png','gif','webp'].includes(ext)) {
//                 previewHtml = `
//                     <div class="attachment-item">
//                         <img src="${filePath}">
//                         <div>${file.split('/').pop()}</div>
//                     </div>`;
//             } 
//             else if (ext === 'pdf') {
//                 previewHtml = `
//                     <div class="attachment-item">
//                         <iframe src="${filePath}"></iframe>
//                         <div>${file.split('/').pop()}</div>
//                     </div>`;
//             } 
//             else {
//                 previewHtml = `
//                     <div class="attachment-item">
//                         <a href="${filePath}" target="_blank">📎 ${file.split('/').pop()}</a>
//                     </div>`;
//             }

//             $("#viewAttachments").append(previewHtml);
//         });

//     } else {
//         $("#viewAttachmentBox").hide();
//     }

//     $("#viewModal").modal("show");
// });
let verifyData = {};
$(document).on('click', '.viewMsg', function () {

    let id      = $(this).data('id');
    let channel = $(this).data('channel');

    $('#deleteMsgbulk')
        .attr('data-id', id)
        .attr('data-channel_type', channel);

    verifyData.id      = $(this).data('id');
    verifyData.channel = $(this).data('channel');
    verifyData.level   = $(this).data('level');
    verifyData.file    = $(this).data('file');

    let subject   = $(this).data('subject');
    let message   = $(this).data('message');
    let attach    = $(this).data('attachments');

    /* SUBJECT */
    if (verifyData.channel === 'Email') {
        $("#viewSubjectBox").show();
        $("#viewSubject").text(subject);
    } else {
        $("#viewSubjectBox").hide();
    }

    // Message (HTML safe)
    $('#viewMessage').html(message);

    // Attachments
    if (attach) {
        let files = attach.split(',');
        let html = '';
        files.forEach(f => {
            html += `<div>
                <a href="../../${f}" target="_blank">${f.split('/').pop()}</a>
            </div>`;
        });
        $('#viewAttachments').html(html);
        $('#viewAttachmentBox').show();
    } else {
        $('#viewAttachmentBox').hide();
    }

    // Download file
    if (verifyData.file) {
        $('#downloadFileBtn')
            .show()
            .attr('href', '../../unistorage/2224/bulkcampaign/' + verifyData.file);
    } else {
        $('#downloadFileBtn').hide();
    }

    let canVerify = $(this).data('can_verify');
    let level     = $(this).data('level');

    if (canVerify == 1) {
        $('#confirmVerifyBtn').show().data('level', level);
        $('#rejectPostBtn').show().data('level', level);
        $('#deletePostBtn').show();
         $('.verifyRemarked').show();
    } else {
        $('#confirmVerifyBtn').hide();
        $('#rejectPostBtn').hide();
        $('#deletePostBtn').hide();
        $('.verifyRemarked').hide();
    }

    $('#verifyRemark').val('');
    $('#viewModal').modal('show');
});



  $(document).on('click', '.editMsgbulk', function() {  
    var id = $(this).data('id');  
    var msg = $(this).data('msg');  
    var schedule = $(this).data('schedule');  
    var queue_session = $(this).data('queue_session');  

    $('#edit_idbulk').val(id);  
    $('#edit_messagebulk').val(msg);  
    $('#queue_session').val(queue_session);

    if (schedule && schedule != '0000-00-00 00:00:00') {  
      var dt = new Date(schedule);  
      var local = dt.toISOString().slice(0,16);  
      $('#edit_schedulebulk').val(local);  
    } else {  
      $('#edit_schedulebulk').val('');  
    }  

    $('#editModalbulk').modal('show');  
  });  

  // CLOSE EDIT MODAL  
  $('#closeEditModalbulk').click(function(){  
    $('#editModalbulk').modal('hide');  
  });  

  // FORM SUBMIT  
  // $('#editFormbulk').submit(function(e){  
  $('#editFormbulk').off('submit').on('submit', function(e){
    e.preventDefault();  
    var id = $('#edit_idbulk').val();  
    var message = $('#edit_messagebulk').val();  
    var schedule = $('#edit_schedulebulk').val(); 
    var channel =  $('#channelbulk').val(); 
    var queue_session = $('#queue_session').val();

    $.ajax({  
      url:"omnichannel_config/bulk_function.php", 
      type: 'POST',  
      data: { 
        action: 'update_bulk', 
        id: id, 
        message: message, 
        schedule: schedule,
        channel: channel,
        queue_session:queue_session
      },   
      success: function(response){  
        alert("Message Updated Successfully");  
        window.location.reload();  
      }  
    });  
  });  

  // CLOSE VIEW MODAL  
  $('#closeModalbulk').click(function(){  
    $('#viewModalbulk').modal('hide');  
  });  

  // DELETE MESSAGE  
 // DELETE BULK MESSAGE (NO RELOAD)
$(document).on('click', '.deleteMsgbulk', function (e) {

    e.preventDefault();

    let btn     = $(this);
    let id      = btn.data('id');
    let table   = $('#bulks_report').DataTable();
    let row     = btn.closest('tr');

    if (!confirm("Are you sure you want to delete this bulk message?")) {
        return;
    }

    // btn.prop('disabled', true).text('Deleting...');

    $.ajax({
        url: "omnichannel_config/bulk_function.php",
        type: "POST",
        dataType: "json",
        data: {
            action: 'delete_bulk',
            id: id
        },
        success: function (res) {

            if (res.status === 'success') {
                $('#viewModal').modal('hide');
                // ✅ Remove row safely from DataTable
                table
                    .row(row)
                    .remove()
                    .draw(false);

            } else {
                alert(res.message || 'Delete failed');
                btn.prop('disabled', false).text('Delete');
            }
        },
        error: function () {
            alert('Server error');
            btn.prop('disabled', false).text('Delete');
        }
    });
});
$(document).on('click', '.dropdown-toggle', function (e) {
    e.stopPropagation();
    $(this).dropdown('toggle');
});

 // Open modal
$('#openDbCsvModal').on('click', function () {
    $('#dbCsvModal').modal('show');
});

// Load fields on module change
$('#module').change(function () {
    let module = $(this).val();
    $('#fieldBox').html('');

    if (!module) return;

    $.ajax({
        url: 'omnichannel_config/bulk_function.php',
        type: 'POST',
        data: { action:'get_csv_fields', module: module },
        success: function (res) {
            let obj = JSON.parse(res);

            if (obj.status === 'success') {
                let html = '';
                obj.fields.forEach(function (field) {
                    html += `
                        <label class="mr-3 d-inline-block">
                            <input type="checkbox" class="csvField" value="${field}">
                            ${field}
                        </label>
                    `;
                });
                $('#fieldBox').html(html);
            } else {
                alert(obj.message);
            }
        }
    });
});

// Generate CSV
$('#generateCsvBtn').on('click', function () {

    let fields = [];
    $('.csvField:checked').each(function () {
        fields.push($(this).val());
    });

    if (!$('#module').val()) {
        alert('Please select module');
        return;
    }
    if (!$('#csv_start').val() || !$('#csv_end').val()) {
        alert('Please select date range');
        return;
    }
    if (fields.length === 0) {
        alert('Please select at least one field');
        return;
    }

    $.ajax({
        url: 'omnichannel_config/bulk_function.php',
        type: 'POST',
        data: {
            action: 'generate_csv_from_db',
            module: $('#module').val(),
            start: $('#csv_start').val(),
            end: $('#csv_end').val(),
            fields: fields
        },
        success: function (res) {

            let obj = JSON.parse(res);
            if (obj.status !== 'success') {
                alert(obj.message);
                return;
            }

            $('#oldFileBox').show();
            $('#oldFileLink')
                .text(obj.filename)
                .attr('href', '../../' + obj.path);

            $('#old_file').val(obj.filename);

            $('#dbCsvModal').modal('hide');
        }
    });
});
  
$('#file').on('change', function (e) {
    const file = e.target.files[0];
    if (!file) return;

    const fileName = file.name.toLowerCase();

    if (!fileName.endsWith('.csv')) {
        $('#excelHeadersBox').html('<span class="text-danger">Please upload CSV file only for header preview.</span>');
        return;
    }

    const reader = new FileReader();

    reader.onload = function (event) {
        const text = event.target.result;

        // get first line only
        const firstLine = text.split(/\r\n|\n/)[0];

        if (!firstLine) {
            $('#excelHeadersBox').html('<span class="text-danger">CSV header row not found.</span>');
            return;
        }

        let headers = parseCSVLine(firstLine);

        headers = headers.map(h => h.trim().replace(/^"|"$/g, '')).filter(h => h !== '');

        renderHeaderTags(headers);

        // optional hidden field store headers
        $('#csv_headers').val(JSON.stringify(headers));

        $("#csv_file_path").val("");
        resetPreviewValidation();
    };

    reader.readAsText(file);
});

// simple CSV parser for first line
function parseCSVLine(line) {
    let result = [];
    let current = '';
    let inQuotes = false;

    for (let i = 0; i < line.length; i++) {
        let char = line[i];

        if (char === '"') {
            inQuotes = !inQuotes;
        } else if (char === ',' && !inQuotes) {
            result.push(current);
            current = '';
        } else {
            current += char;
        }
    }
    result.push(current);

    return result;
}
function renderHeaderTags(headers) {
    if (!headers || headers.length === 0) {
        $('#excelHeadersBox').html('<span class="text-danger">No headers found</span>');
        return;
    }

    let html = '';

    headers.forEach(function (header) {
        let safeHeader = header.trim();
        html += `<span class="header-tag" data-header="${safeHeader}">+${safeHeader}</span>`;
    });

    $('#excelHeadersBox').html(html);
}
$(document).on('click', '.header-tag', function () {
    const header = $(this).data('header');
    const placeholder = ` <<${header}>>`;

    if (ckeditorInstance) {
        insertPlaceholderInCKEditor(placeholder);
    } else {
        insertAtCursor('V_Content', placeholder);
    }
});
function insertPlaceholderInCKEditor(placeholder) {
    if (!ckeditorInstance) return;

    ckeditorInstance.editing.view.focus();

    ckeditorInstance.model.change(writer => {
        const selection = ckeditorInstance.model.document.selection;
        const position = selection.getFirstPosition();

        writer.insertText(placeholder, position);
    });
}

function insertAtCursor(fieldId, text) {
    let txtarea = document.getElementById(fieldId);
    if (!txtarea) return;

    txtarea.focus();

    if (typeof txtarea.selectionStart === "number") {
        let start = txtarea.selectionStart;
        let end = txtarea.selectionEnd;
        let value = txtarea.value;

        txtarea.value = value.substring(0, start) + text + value.substring(end);
        txtarea.selectionStart = txtarea.selectionEnd = start + text.length;
    } else {
        txtarea.value += text;
    }

    $(txtarea).trigger('input');
}


// 
let previewRows = [];
let previewIndex = 0;
let previewValidated = false;

// -----------------------------------------
// Preview & Validate button click
// -----------------------------------------
$("#previewTemplateBtn").on("click", function () {

    let templateContent = "";

    if (typeof ckeditorInstance !== "undefined" && ckeditorInstance) {
        templateContent = ckeditorInstance.getData();
    } else {
        templateContent = $("#message").val();
    }

    if (!templateContent || !templateContent.trim()) {
        alert("Please select or type template content first.");
        return;
    }

    // If file already uploaded before, use saved path
    let csvFile = $("#csv_file_path").val();

    // If no uploaded file path yet, upload selected file first
    if (!csvFile) {
        let fileInput = $("#file")[0];

        if (!fileInput.files || fileInput.files.length === 0) {
            alert("Please select CSV file first.");
            return;
        }

        uploadCsvThenPreview(templateContent);
        return;
    }

    // If already uploaded, directly preview
    loadTemplatePreview(templateContent, csvFile);
});
function uploadCsvThenPreview(templateContent) {
    let fileInput = $("#file")[0];

    if (!fileInput.files || fileInput.files.length === 0) {
        alert("Please select CSV file first.");
        return;
    }

    let file = fileInput.files[0];

    // Optional: CSV validation
    let fileName = file.name.toLowerCase();
    if (!fileName.endsWith(".csv")) {
        alert("Please select only CSV file.");
        return;
    }

    let formData = new FormData();
    formData.append("action", "upload_preview_csv");
    formData.append("file", file);

    $("#previewTemplateBtn").prop("disabled", true).text("Uploading CSV...");

    $.ajax({
        url: "omnichannel_config/bulk_function.php",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function (res) {
            if (!res.status || res.status !== "success") {
                $("#previewTemplateBtn").prop("disabled", false).text("Preview & Validate");
                alert(res.message || "CSV upload failed.");
                return;
            }

            // Save uploaded server path
            $("#csv_file_path").val(res.filepath);

            // Now call preview
            loadTemplatePreview(templateContent, res.filepath);
        },
        error: function (xhr) {
            $("#previewTemplateBtn").prop("disabled", false).text("Preview & Validate");
            console.log(xhr.responseText);
            alert("Error uploading CSV.");
        }
    });
}function uploadCsvThenPreview(templateContent) {
    let fileInput = $("#file")[0];

    if (!fileInput.files || fileInput.files.length === 0) {
        alert("Please select CSV file first.");
        return;
    }

    let file = fileInput.files[0];

    // Optional: CSV validation
    let fileName = file.name.toLowerCase();
    if (!fileName.endsWith(".csv")) {
        alert("Please select only CSV file.");
        return;
    }

    let formData = new FormData();
    formData.append("action", "upload_preview_csv");
    formData.append("file", file);

    $("#previewTemplateBtn").prop("disabled", true).text("Uploading CSV...");

    $.ajax({
        url: "omnichannel_config/bulk_function.php",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function (res) {
            if (!res.status || res.status !== "success") {
                $("#previewTemplateBtn").prop("disabled", false).text("Preview & Validate");
                alert(res.message || "CSV upload failed.");
                return;
            }

            // Save uploaded server path
            $("#csv_file_path").val(res.filepath);

            // Now call preview
            loadTemplatePreview(templateContent, res.filepath);
        },
        error: function (xhr) {
            $("#previewTemplateBtn").prop("disabled", false).text("Preview & Validate");
            console.log(xhr.responseText);
            alert("Error uploading CSV.");
        }
    });
}
function resetPreviewValidation() {
    previewValidated = false;
    // $("#finalSubmitBulkBtn").hide();
}

// -----------------------------------------
// Render preview record
// -----------------------------------------
function renderPreviewRecord(index) {
    if (!previewRows.length || !previewRows[index]) return;

    let row = previewRows[index];

    $("#previewCurrentIndex").text(index + 1);

    // Rendered content (HTML)
    $("#previewContentBox").html(row.rendered_content);

    // Raw CSV table
    let rawHtml = '<table class="table table-bordered table-sm">';
    if (row.raw_data) {
        $.each(row.raw_data, function (key, value) {
            rawHtml += `
                <tr>
                    <th style="width:40%; background:#f5f5f5;">${escapeHtml(key)}</th>
                    <td>${escapeHtml(value)}</td>
                </tr>
            `;
        });
    }
    rawHtml += '</table>';
    $("#previewRawDataBox").html(rawHtml);

    // Missing placeholders warning
    if (row.missing_placeholders && row.missing_placeholders.length > 0) {
        $("#previewWarningBox")
            .show()
            .html(
                "<strong>Warning:</strong> Missing CSV headers for placeholders: " +
                row.missing_placeholders.map(function(p){ return "&lt;&lt;" + escapeHtml(p) + "&gt;&gt;"; }).join(", ")
            );
    } else {
        $("#previewWarningBox").hide().html("");
    }

    // Nav buttons
    $("#previewPrevBtn").prop("disabled", index === 0);
    $("#previewNextBtn").prop("disabled", index === previewRows.length - 1);
}

// -----------------------------------------
// Prev / Next
// -----------------------------------------
$("#previewPrevBtn").on("click", function () {
    if (previewIndex > 0) {
        previewIndex--;
        renderPreviewRecord(previewIndex);
    }
});

$("#previewNextBtn").on("click", function () {
    if (previewIndex < previewRows.length - 1) {
        previewIndex++;
        renderPreviewRecord(previewIndex);
    }
});
// -----------------------------------------
// Helper: escape html
// -----------------------------------------
function escapeHtml(text) {
    return $('<div>').text(text || '').html();
}
function loadTemplatePreview(templateContent, csvFile) {

    let channel = $("#channel_type").val();

    $("#previewTemplateBtn").prop("disabled", true).text("Loading Preview...");

    $.ajax({
        url: "omnichannel_config/bulk_function.php",
        type: "POST",
        dataType: "json",
        data: {
            action: "preview_template_with_csv",
            template_content: templateContent,
            csv_file: csvFile,
            channel: channel
        },
        success: function (res) {
            $("#previewTemplateBtn").prop("disabled", false).text("Preview & Validate");

            if (!res.status || res.status !== "success") {
                alert(res.message || "Preview failed.");
                return;
            }

            previewRows = res.preview_rows || [];
            previewIndex = 0;
            previewValidated = false;

            if (previewRows.length === 0) {
                alert("No valid preview rows found in CSV.");
                return;
            }

            $("#previewTotalCount").text(previewRows.length);

            renderPreviewRecord(previewIndex);

            $("#finalSubmitBulkBtn").show();
            previewValidated = true;

            $("#templatePreviewModal").modal("show");
        },
        error: function (xhr) {
            $("#previewTemplateBtn").prop("disabled", false).text("Preview & Validate");
            console.log(xhr.responseText);
            alert("Error generating preview.");
        }
    });
}
$(document).on('click', '.pauseBulkAction', function () {
    let id = $(this).data('id');
    var channel_type = $("#channel_type").val();
    if (!confirm("Pause this campaign?")) return;

    $.post("omnichannel_config/bulk_function.php", {
        action: 'pause_bulk_campaign',
        id: id,
        channel_type:channel_type
    }, function (res) {
        alert(res);
        $('#bulks_report').DataTable().ajax.reload(null, false);
    });
});

$(document).on('click', '.runBulkAction', function () {
    let id = $(this).data('id');
    var channel_type = $("#channel_type").val();
    if (!confirm("Run this campaign?")) return;

    $.post("omnichannel_config/bulk_function.php", {
        action: 'run_bulk_campaign',
        id: id,
        channel_type:channel_type
    }, function (res) {
        alert(res);
        $('#bulks_report').DataTable().ajax.reload(null, false);
    });
});
$(document).on("click", ".resumeBulkAction", function () {
    let id = $(this).data("id");
    var channel_type = $("#channel_type").val();
    if (!confirm("Are you sure you want to resume this bulk campaign?")) return;

    $.ajax({
        url: "omnichannel_config/bulk_function.php",
        type: "POST",
        dataType: "json",
        data: {
            action: "resume_bulk_campaign",
            id: id,
            channel_type:channel_type
        },
        success: function (res) {
            alert(res);
            $('#bulks_report').DataTable().ajax.reload(null, false);
        },
        error: function (xhr) {
            console.log(xhr.responseText);
            alert("Error while resuming bulk campaign.");
        }
    });
});

$(document).ready(function () {
    $("#toggleBulkForm").on("click", function () {
        $("#bulkFormBody").slideToggle(250, function () {
            if ($(this).is(":visible")) {
                $("#bulkToggleIcon").removeClass("fa-plus").addClass("fa-minus");
            } else {
                $("#bulkToggleIcon").removeClass("fa-minus").addClass("fa-plus");
            }
        });
    });
});
function collapseBulkFormAndShowRecent() {
    $("#bulkFormBody").slideUp(250, function () {
        $("#bulkToggleIcon").removeClass("fa-minus").addClass("fa-plus");

        $('html, body').animate({
            scrollTop: $("#recentUploadsCard").offset().top - 70
        }, 500);
    });
}
  $(document).on('show.bs.dropdown', '.dropdown', function () {

    const $dropdown = $(this);
    const dropdownOffset = $dropdown.offset().top;
    const dropdownHeight = $dropdown.find('.dropdown-menu').outerHeight();
    const windowHeight = $(window).height();
    const scrollTop = $(window).scrollTop();

    // If dropdown would overflow bottom
    if (dropdownOffset + dropdownHeight > windowHeight + scrollTop) {
        $dropdown.addClass('dropup');
    } else {
        $dropdown.removeClass('dropup');
    }
});
