let currentPageName = (window.location.href).split('/').pop().split('?')[0];
let all_checkboxes_val = [];
let current_query = null;
let current_total_record = 0;

$(".custom-select-picker").select2();
$(".custom-select-picker-ajax").each(function () {
  const $this = $(this);
  const key = $this.data("search") || $this.attr("name"); // safer and simpler
  let paramData = $this.data("param") ? $this.data("param") : null;
  // console.log(key);
  // console.log(paramData);
  
  // ✅ Trigger AJAX data load on page load
  $.ajax({
    url: location.origin + "/fun/search_select",
    type: "GET",
    dataType: "json",
    data: { [key]: "", param_data:JSON.stringify(paramData), first_time: true }, // empty search term
    success: function (data) {
      // console.log(data);
      if (Array.isArray(data)) {
        $this.append(new Option('', '', false, false));
        data.forEach(function (item) {
          const option = new Option(item.title, item.id, false, false);
          $this.append(option);
        });
        // Refresh select2 so options appear in dropdown
        // $this.trigger("change");
        // ✅ Set default value (example)
        const defaultId = paramData && paramData.default ? paramData.default : null;
        if (defaultId) {
          // console.log('defaultId:', defaultId);
          $this.val(defaultId).trigger('change');
        }
      }
    },
  });

  $this.select2({
    ajax: {
      url: location.origin + "/fun/search_select",
      type: "GET",
      dataType: "json",
      delay: 250,
      data: function (params) {
        const requestData = {};
        requestData[key] = params.term || ''; // ✅ ensure defined
        requestData.param_data = JSON.stringify(paramData);
        // console.log("Request Data:", requestData); // debug
        return requestData;
      },
      processResults: function (data) {
        return {
          results: data.map(function (item) {
            return {
              id: item.id,
              text: item.title,
            };
          }),
        };
      },
    },
    tags: $this.attr('tags') === 'true'
  });
  
});
let previousDates = [];
const fp = flatpickr(".flatpickr_date", {
  mode: "range",
  enableTime: true,
  dateFormat: "Y-m-d H:i",
  minDate: "",
  maxDate: "",
  defaultDate: ["", ""],
  onChange: function (selectedDates, dateStr, instance) {
    // Function to strip time and keep only the date part
    function stripTime(date) {
      return date ? new Date(date.getFullYear(), date.getMonth(), date.getDate()) : null;
    }

    // Strip time from the current selected dates
    const currentDates = selectedDates.map(stripTime);

    // Check if the date part has changed compared to the previous dates
    if (
      previousDates.length === currentDates.length &&
      currentDates.every((date, index) => +date === +(previousDates[index] || 0))
    ) {
      return; // No change in the date part, do nothing
    }

    // Update the previous dates with the current dates
    previousDates = [...currentDates];
    // console.log("🚀 ~ previousDates:", previousDates)

    // If only one date is selected, set the time to 12:00 am (00:00)
    if (selectedDates.length === 1) {
      const firstDate = selectedDates[0];
      firstDate.setHours(0, 0, 0, 0);
      instance.setDate([firstDate, ""]);
    }

    // If two dates are selected, set the time for the second date to 11:59 pm (23:59)
    if (selectedDates.length === 2) {
      const secondDate = selectedDates[1];
      secondDate.setHours(23, 59, 0, 0);
      instance.setDate([selectedDates[0], secondDate]);
    }
  },
});
$("#checkAll").click(function (e) {
  e.stopPropagation();
  $("input.checkboxes").not(this).prop("checked", this.checked);
  get_all_checked_ids();
});

$(document).on('click', 'input.checkboxes', function () {
  if (this.checked) {
    all_checkboxes_val.push(this.value);
  } else {
    let indexToRemove = all_checkboxes_val.indexOf(this.value);
    all_checkboxes_val.splice(indexToRemove, 1);
  }
});

async function get_all_checked_ids() {
  if ($("#checkAll").is(':checked')) {
    await $.ajax({
      url: 'fun/get_checkAll',
      type: 'get',
      data: { currentPageName, current_query },
      dataType: 'json',
      success: function (res) {
        all_checkboxes_val = res;
      }
    });
    // console.log(all_checkboxes_val);
  } else {
    all_checkboxes_val = [];
  }
}
function handle_checkboxes() {
  if (all_checkboxes_val.length > 0) {
    $('input.checkboxes').each((index, element) => {
      if (all_checkboxes_val.includes(element.value)) {
        element.checked = true;
      } else {
        element.checked = false;
      }
    });
  }
}


function column_count() {
  // let tds, sum;
  // if(['profile_campaigns','alert_campaigns'].includes(currentPageName)){
  //   let upto = $('.dataTables_scrollHeadInner .dataTable th');
  //   for(let i=0; i<upto.length; i++){

  //     tds = $(`#basic-datatable tr td:nth-of-type(${i+1})`);
  //     sum = 0;
  //     let num = 0;
  //     if(Number.isInteger(+($(tds[0]).text()))){
  //       for(let j=0; j<tds.length; j++){
  //         num = +(tds[j].textContent);
  //         // console.log(num);
  //         sum += num;
  //       }
  //       // console.log(num);
  //       $(upto[i]).children('.count_column').remove();
  //       $(upto[i]).append(` <span class='count_column'>(${sum})</span>`);
  //       // console.log('next');
  //     }
  //   }

  // }
}

var oldExportAction = function (self, e, dt, button, config) {

  var data = dt.buttons.exportData();

  // ############################################################# Customizing data before export
  var newData = [];
  var newHeader = [];
  let newHeader_insert = true;
  data.body.forEach(function (row, index) {
    var newRow = [];
    // Split the values for each column
    row.forEach(function (cell, cellIndex) {
      // Split cell by a delimiter (for example, a comma or space)
      var values = ('' + cell).split('\n');
      // Add each split value as a new column
      values.forEach(function (value) {
        let comb_val_insert = value;
        let comb_head_insert = data.header[cellIndex].trim();
        let combined_value = ('' + value).split(': ');
        // console.log(combined_value);

        if (combined_value.length == 2) {
          comb_head_insert = combined_value[0].trim();
          comb_val_insert = combined_value[1].trim();
        } else if (combined_value.length == 1) {
          comb_head_insert = data.header[cellIndex].trim()
          comb_val_insert = combined_value[0];
        }
        // console.log(`${data.header[cellIndex]} => ${value}`);
        if (newHeader_insert) {
          newHeader.push(comb_head_insert)
        }
        newRow.push(comb_val_insert)
      });
    });
    newHeader_insert = false;
    newData.push(newRow);
  });
  // ############################################################# Customizing data before export


  // ################################################## remove empty values from header and data based on header
  let empty_header = [];
  // Check for any empty or undefined headers
  newHeader.forEach((header, index) => {
    if (header === '' || header === undefined) {
      empty_header.push(index);
    }
  });

  empty_header = empty_header.reverse();
  empty_header.forEach((val, ind) => {
    newHeader.splice(val, 1);
  });

  newData.forEach((row, index) => {
    empty_header.forEach((val, ind) => {
      row.splice(val, 1);
    });
  });
  // ################################################## remove empty values from header and data based on header

  // ############################################################# actual export functionality
  let blob;
  if (button[0].className.indexOf('buttons-csv') >= 0) {
    // ######################################################################### old
    // if ($.fn.dataTable.ext.buttons.csvHtml5.available(dt, config)) {
    //     $.fn.dataTable.ext.buttons.csvHtml5.action.call(self, e, dt, button, newConfig);
    // }else {
    //     $.fn.dataTable.ext.buttons.csvFlash.action.call(self, e, dt, button, newConfig);
    // }
    // ######################################################################### old


    // ######################################################################### new
    let exportString = "";
    // Add header row
    exportString += '"' + newHeader.join('","') + '"' + "\n";
    // Add data rows
    newData.forEach(row => {
      exportString += '"' + row.join('","') + '"' + "\n";
    });
    // console.log("🚀 ~ oldExportAction ~ exportString:", exportString)

    blob = new Blob([exportString], { type: "text/csv;charset=utf8" });
    file_name = `${currentPageName}.csv`;
    // ######################################################################### new

  } else if (button[0].className.indexOf('buttons-excel') >= 0) {
    // ######################################################################### old
    // if ($.fn.dataTable.ext.buttons.excelHtml5.available(dt, config)) {
    //   $.fn.dataTable.ext.buttons.excelHtml5.action.call(self, e, dt, button, newConfig);
    // }else {
    //     $.fn.dataTable.ext.buttons.excelFlash.action.call(self, e, dt, button, newConfig);
    // }
    // ######################################################################### old


    // ######################################################################### new
    let excelString = "";
    // Add header row
    excelString += newHeader.join("\t") + "\n";
    // Add data rows
    newData.forEach(row => {
      excelString += row.join("\t") + "\n";
    });

    blob = new Blob([excelString], { type: "text/tab-separated-values;charset=utf8" });
    file_name = `${currentPageName}.tsv`;
    // ######################################################################### new
  }
  // ############################################################# actual export functionality



  // Create a downloadable link
  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = file_name; // Change filename as needed
  link.click();

  // Revoke the object URL to avoid memory leaks
  URL.revokeObjectURL(link.href);

};


var newExportAction = function (e, dt, button, config) {

  let old_per_page = dt.page.len();
  let self = this
  var currentSearch = dt.search();

  // Define a draw callback function
  var firstDrawCallback = function () {
    // Remove the first draw callback
    dt.off('draw', firstDrawCallback);

    oldExportAction(self, e, dt, button, config);

    dt.page.len(old_per_page).draw();
    dt.search(currentSearch).draw();
  };

  dt.page.len(current_total_record).draw();
  dt.search(currentSearch).draw();

  // Attach the first draw callback
  dt.on('draw', firstDrawCallback);

};


function loadTable(table_id = "#basic-datatable", url = "", columns = [], default_index = [0, "desc"], where = null, extra_where = null) {
  let table_instance = null;
  // console.log('loadTable');
  // console.log(table_id, columns, where);
  if (table_instance !== null) {
    table_instance.destroy();
  }

  $.fn.dataTable.ext.errMode = 'throw';
  const options = {
    destroy: true,
    autoWidth: false,
    deferRender: true,
    processing: true,
    scrollX: true,
    serverSide: true,
    stateSave: true,
    ajax: {
      url: url,
      type: "GET",
      data: function (data) {
        data.where_condition = where,
          data.extra_where = extra_where,
          data.isset = 1
      }
    },
    columns: columns,
    order: [default_index],
    search: {
      regex: true,
      return: true
    },
    dom: '<"top"lBf>rt<"bottom"ip>',
    buttons: [
      {
        extend: 'colvis',
        columns: 'th:nth-child(n)'
      }, {
        extend: 'csvHtml5',
        text: 'Download CSV',
        exportOptions: {
          columns: ':visible'
        },
        action: newExportAction
      },
      // {
      //   extend:'excelHtml5', 
      //   text:'Download Excel',
      //   exportOptions: {
      //     columns: ':visible'
      //   },
      //   action: newExportAction
      // }
    ],
    colReorder: true,
    rowReorder: false,
    fixedHeader: {
      header: true,
      headerOffset: $('.navbar').outerHeight() - 6,
    },
    keys: true,
    responsive: false,
    // responsive: {
    //   breakpoints: [
    //     // { name: 'xl', width: Infinity },
    //     // { name: 'lg', width: 1200 },
    //     // { name: 'md', width: 992 },
    //     // { name: 'sm', width: 768 },
    //     { name: 'xs', width: 576 }
    //   ],
    //   details: false
    // },
    // select: {
    //   style: 'multi',
    //   items: 'cell'
    // },
    // initComplete: function(settings, json) {
    //   console.log( 'DataTables has finished its initialisation.' );
    // }
    // pageLength: 100,              // default selected value
    // lengthMenu: [10, 25, 50, 100], // dropdown options
    drawCallback: async function (settings) {
      current_query = settings.json.query;
      current_total_record = settings.json.recordsFiltered;
      // console.log(settings.json)
      // console.log(current_query);
      await get_all_checked_ids();
      handle_checkboxes();
      column_count();
    },
    // error: function (xhr, error, thrown) {
    //   console.log('Ajax error:', xhr, error, thrown);
    // },
  }
  table_instance = $(`${table_id}`).on('preXhr.dt', function (e, settings, data) {
    // console.log("🚀 ~ file: custom.js:211 ~ data:", JSON.stringify(data))
    // console.log("🚀 ~ file: custom.js:212 ~ data:", data)
  }).DataTable(options);
  // console.log(table_instance);
}

function search_select_data(search_field, select_id) {
  let searchVal = $(`${search_field}`).val();
  let search_len = searchVal.length;
  if (search_len >= 2) {
    if ($(`#select2-${select_id}-results`).length > 0) {
      debounceCheck({
        select_id: select_id,
        select_results_id: search_field,
        search_val: searchVal,
      });
    }
  }
}

// calling debounce
const debounceCheck = debounce((obj) => {
  let select_id = obj.select_id;
  let select_results_id = obj.select_results_id;
  let search_val = obj.search_val;

  $.ajax({
    url: "fun/search_select",
    type: "GET",
    data: {
      [select_id]: search_val,
    },
    cache: false,
    success: function (result) {
      result = "<option></option>" + result;
      let selectElem = $(`#${select_id}`);
      selectElem.html(result);
      selectElem.select2("destroy");
      selectElem.select2();
      selectElem.select2("open");
      // $(`#${select_results_id}`).parent().prev().find('.select2-search__field').val(search_val)
      $(`${select_results_id}`).val(search_val);
    },
    error: function (res) {
      //   alert(res + "sertgbn");
    },
  });
}, 250);

//  debounce function
function debounce(cb, delay = 1000) {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      cb(...args);
    }, delay);
  };
}



// ##############################################

$(document).ready(function () {
  if ((window.location.href).indexOf('?') == -1) {

    let filter_cookie = localStorage.getItem(currentPageName);
    if (filter_cookie != null) {
      filter_cookie = JSON.parse(filter_cookie);
      // console.log(filter_cookie);
      for (let [key, value] of Object.entries(filter_cookie)) {
        // console.log(key, value, Array.isArray(value));
        let nodeName = $(`[name='${key}']`).prop("nodeName");
        let isdate = $(`[name='${key}']`).attr("data-isdate");
        let name = key;
        // console.log(nodeName, name);
        if (nodeName == "SELECT" && Array.isArray(value) && value.length != 0 && value[0] != '') {
          $(`[name='${name}'] option:selected`).each((index, ele) => {
            $(ele).prop("selected", false);
          });
          // $(`[name='${name}']`).trigger("change");
          value.forEach(val => {
            $(`[name='${name}'] option[value='${val}']`)
              .prop("selected", true);
          });
          $(`[name='${name}']`).trigger("change");
        } else if (nodeName == "SELECT" && !Array.isArray(value) && value.length != 0 && value[0] != '') {
          // console.log(name, value);
          $(`[name='${name}'] option:selected`).prop("selected", false);
          $(`[name='${name}'] option[value='${value}']`)
            .prop("selected", true)
            .trigger("change");
          // } else if (nodeName == "INPUT" && isdate=='true') {
          // $(`[name='${name}']`).set(value, true);
        } else if (nodeName == "INPUT") {
          $(`[name='${name}']`).val(value);
        } else {
        }

      }
    }

  }

});


let form_fields = $("#filter_block").find("input, select");
let setArray = [];

function clear_filter(element) {
  let val = $(element).val();

  if (Array.isArray(val) && val.length != 0 && val[0] != '') {
    $(element).val([]);
  } else {

    let nodeName = $(element).prop("nodeName");
    let name = $(element).attr("name");
    // console.log(nodeName, name);
    if (nodeName == "SELECT") {
      $(`[name='${name}'] option`)
        .first()
        .prop("selected", true)
        .trigger("change");
    } else if (nodeName == "INPUT") {
      $(`[name='${name}']`).val("");
    } else {
    }

  }
  $("#search_filter").click();
}

$("#clear_filter").click(function () {
  form_fields.each(function () {
    clear_filter(this);
  });
});

$(document).on("click", ".remove_filter", function () {
  let filter_selector = $(this).parent().attr('data-filter_selector');
  clear_filter($(`${filter_selector}`));
  $(this).parent().remove();
});

function search_filter(element) {

  if (
    $(element).attr('data-isLGOperator') == 'true' ||
    $(element).attr('data-isLikeSOperator') == 'true' ||
    $(element).attr('data-isLikeEOperator') == 'true'
  ) {
    return false;
  }

  let id = $(element).attr('id');
  let label_text = $(`label[for=${id}]`).text();

  let val = ($(element).val()).trim();
  let name = $(element).attr('name');
  let isDate = $(element).attr('data-isDate');
  let comma_separated = $(element).attr('data-comma_separated');
  let isLG = $(element).attr('data-isLG');
  let isLike = $(element).attr('data-isLike');
  let isBetween = $(element).attr('data-isBetween');
  let isInterval = $(element).attr('data-isInterval');
  let custom_filter = $(element).attr('data-custom_filter');

  let label_value = '';
  let nodeName = $(element).prop("nodeName");
  if (nodeName == 'SELECT' && Array.isArray(val)) {
    let selectedOptions = $(element).children("option:selected");
    label_value = selectedOptions.map(function () {
      return $(this).text();
    }).get().join(", ");
  } else if (nodeName == 'SELECT' && !Array.isArray(val)) {
    label_value = $(element).children("option").filter(":selected").text();
  } else {
    label_value = val;
  }


  // ########################################### set Filters in Cookie
  let filter_cookie = localStorage.getItem(currentPageName);
  if (filter_cookie != null) {
    filter_cookie = JSON.parse(filter_cookie);
  } else {
    filter_cookie = {};
  }
  // console.log(filter_cookie);
  // console.log(val);
  filter_cookie[name] = val;
  filter_cookie = JSON.stringify(filter_cookie);
  localStorage.setItem(currentPageName, filter_cookie)
  // ########################################### set Filters in Cookie

  let field = '';
  if (Array.isArray(val) && val.length != 0 && val[0] != '') {
    if (comma_separated == 'true') {
      val = val.join(",");
      field = `CONCAT(',', ${name}, ',') LIKE '%,${val},%'`;
    } else {
      val = "'" + val.join("','") + "'";
      field = `${name} IN(${val})`;
    }
  } else if (val != '') {
    if (comma_separated == 'true') {
      field = `CONCAT(',', ${name}, ',') LIKE '%,${val},%'`;
    } else if (isDate == 'true') {
      let date = val.split("to");
      field = `${name} between '${date[0].trim()}:00' and '${date[1].trim()}:59'`;
    } else if (isLG == 'true') {
      let operator = $(`[name=${name}_operator]`).val();
      label_value = `${operator} ${label_value}`
      field = `${name}${operator}'${val}:00'`;
    } else if (isInterval == 'true') {
      field = `${name}>now()-INTERVAL ${val}`;
    } else if (isBetween == 'true') {
      let b_col = name.split("_to_");
      field = `'${val}' between '${b_col[0]}' and '${b_col[1]}'`;
    } else {
      field = `${name}='${val}'`;
    }
  }

  if (field != '') {
    setArray.push(field);
    $("#filter_options").append(`<button type="button" data-filter_selector="[name=${name}]" class="btn btn-filter text-white px-2 py-1 d-flex align-items-center justify-content-center"><span>${label_text} : ${label_value}</span><i class="uil uil-times-circle ml-2 remove_filter"></i></button>`);
  }
}











// $(document).on('keyup', ".select2-search__field", function() {
//     let input_ele;
//     for (const item of ["employees","managers"]) {
//         input_ele = $(`[aria-controls="select2-${item}-results"]`);
//         if (input_ele.length > 0) {
//             search_select_data(`[aria-controls="select2-${item}-results"]`, item);
//         }
//     }
// });