let allEvents = [];

$(document).ready(function () {
  var file_name = getFileName();
  if(file_name == "settings.php"){
    RedirectToActiveTabEvents("base_cost");    
  }else if(file_name == "pending_payment.php"){
    $("#main_header_property_label").hide();
    $("#selectproperty").hide();
    getPendingPayments({ getPendingPayment: "yes"});
  }
  else{
    eventsDataRequest({ getEventsRequest: "yes",property_id:sessionStorage.getItem("propertyId") });
  }
});

function getFileName() {
    return window.location.pathname.split('/').pop();
}

function showSuccessGlobalToastMessage(errorMessage) {
    document.getElementById("globalSuccessToastMessage").style.display = "block";
    document.getElementById("globalSuccessMessage").textContent = errorMessage;
    var toastEl = document.getElementById("global_success_Toast");
    var toast = new bootstrap.Toast(toastEl, {
      delay: 3000,
      autohide: true,
    });
    toast.show();
  
    setTimeout(() => {
        closeSucessGlobalToastMessage();
    }, 4000);
}

function closeSucessGlobalToastMessage() {
    const toastEl = document.getElementById("globalSuccessToastMessage");
    toastEl.style.display = "none";
}

function closeErrorGlobalToastMessage() {
    const toastEl = document.getElementById("globalErrorToastMessage");
    toastEl.style.display = "none";
}

function showErrorGlobalToastMessage(errorMessage) {
    document.getElementById("globalErrorToastMessage").style.display = "block";
    document.getElementById("globalErrorMessage").textContent = errorMessage;
    const toastEl = document.getElementById("global_error_Toast");
    const toast = new bootstrap.Toast(toastEl, {
      delay: 3000,
      autohide: false,
    });
    toast.show();
  
    setTimeout(() => {
        closeErrorGlobalToastMessage();
    }, 4000);
}

function populateEventsModules(modules) {
  const moduleSelect = document.getElementById("event_modules");
  moduleSelect.innerHTML = '<option value="">Select a module</option>';
  modules.forEach((module) => {
    const option = document.createElement("option");
    option.value = module;
    option.textContent = `${module}`;
    moduleSelect.appendChild(option);
  });
}

function RedirectToActiveTabEvents(active, page_token=""){
    $(".nav-link").removeClass('active');
    $("#"+active+"-tab").addClass('active');
    $(".tab-pane").removeClass('show');
    $(".tab-pane").removeClass('active');
    $("#"+active).addClass('show');
    $("#"+active).addClass('active');
    var type = "";
    if(active == "calls-event"){
      type = "call";
    }
    else if(type = "message-event"){
      type = "message";
    }
    if((active == "calls-event") || (active == "message-event")){
      var start_date = $("#"+type+"_log_start_date").val();
      var end_date = $("#"+type+"_log_end_date").val();
      var property_id = $("#selectproperty").val();
      var page_size = 0;
      if(page_token != ""){
        if(page_token == 'next'){
          page_size = $("#"+type+"_event_page").val();
          page_size = Number(page_size) + 1;
          page_token = $("#next_btn_"+type+"_event_token").val();
        }
        else{
          page_size = $("#"+type+"_event_page").val();
          page_size = Number(page_size) - 1;
          page_token = $("#previous_btn_"+type+"_event_token").val();
        }
      }
      logEventsDataRequest({ getCallEventsRequest: "yes", property_id:property_id, start_date:start_date, end_date:end_date, page_size:page_size, page_token:page_token, type:type }, type);   
    }

    if((active == "call") || (active == "sms")){
      createCallSMSTable(active);
    }
    if(active == "org-events"){
      type = "org_evnts";
      logOrgDataRequest({ getOrgEventsRequest: "yes", type:type}, type); 
    }
    if(active == "admin-events"){
      type = "admin_evnts";
      logAdminDataRequest({ getAdminEventsRequest: "yes", type:type}, type); 
    }
    if(active == "referrals"){
      referralsTable({ getReferralsRequest: "yes", type:type}, type); 
    }
    if(active == "base_cost"){
      BaseCostData({ getBaseCost: "yes"})
    }
    if(active == "snapshot"){
      createSnapshotTable(active);
    }
    if(active == "variable_cost"){
      variable_cost();
    }
    if(active == "payment_history"){
      payment_history();
    }
    if(active == "invoice_history"){
      invoice_history();
    }
}

function logOrgDataRequest(data, type){
  $.ajax({
    url: "/include/support_tickets/events_requests.php",
    type: "post",
    data,
    success: function (response) {
      createOrgEventsTable(response, "#org_events_container", type);
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

function logAdminDataRequest(data, type){
  $.ajax({
    url: "/include/support_tickets/events_requests.php",
    type: "post",
    data,
    success: function (response) {
      createAdminEventsTable(response, "#admin_events_container", type);
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

function referralsTable(data, type){
  $.ajax({
    url: "/include/referrals/get_referrals.php",
    type: "post",
    data,
    success: function (response) {
      createReferralsTable(response, "#call_events_container", type);
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

function payment_history(){
  $.ajax({
    url: "/include/subscription/subscription.php",
    type: "post",
    data: {get_payment_history:'yes'},
    success: function (response) {
      createPaymentHistoryTable(response);
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

function invoice_history(){
  $.ajax({
    url: "/include/subscription/subscription.php",
    type: "post",
    data: {get_invoice_history:'yes'},
    success: function (response) {
      createInvoiceHistoryTable(response);
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

function logEventsDataRequest(data, type){
  $.ajax({
    url: "/include/support_tickets/events_requests.php",
    type: "post",
    data,
    success: function (response) {
      createCallEventsTable(response, "#call_events_container", type);
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

function eventsDataRequest(data) {
  $.ajax({
    url: "/include/support_tickets/events_requests.php",
    type: "post",
    data,
    success: function (response) {
      if (data?.getEventsRequest) {
        allEvents = response?.data;
        const modules = getAllModules(allEvents);
        populateEventsModules(modules);
        createEventsTable(response?.data, "#events_container");
      }
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

filterActionsOptions=['Login','Create','Update','Delete']

function getAllModules(data) {
  // Extract module names and ensure uniqueness
  const moduleNames = [...new Set(data.map((item) => item.module_name))];
  return moduleNames;
}

function createOrgEventsTable(response, tableId, type){
  let html = '';
  var data = response.data;
  if(data != ""){
    data.forEach((item) => {
        html += `
          <tr>
            <td>${item.action}</td>
            <td>${item.module_name}</td>
            <td>${item.user_email}</td>
            <td>${item.old_value}</td>
            <td>${item.new_value}</td>
            <td>${item.timestamp}</td>
            <td>${item.additional_info}</td>
          </tr>`;
      });
  }
  if ($.fn.DataTable.isDataTable("#org_events_table")) {
    $("#org_events_table").DataTable().destroy();
  }
  
  // Update table body
  const safeHtml = html;
  $("#org_events_container").html(safeHtml);
  load_datatable("org_events_table");
}

function createAdminEventsTable(response, tableId, type){
  let html = '';
  var data = response.data;
  if(data != ""){
    data.forEach((item) => {
        html += `
          <tr>
            <td>${item.action}</td>
            <td>${item.module_name}</td>
            <td>${item.user_email}</td>
            <td>${item.old_value}</td>
            <td>${item.new_value}</td>
            <td>${item.timestamp}</td>
            <td>${item.additional_info}</td>
          </tr>`;
      });
  }
  if ($.fn.DataTable.isDataTable("#admin_events_table")) {
    $("#admin_events_table").DataTable().destroy();
  }
  
  // Update table body
  $("#admin_events_container").html(html);
  load_datatable("admin_events_table");
}

function createReferralsTable(response, tableId, type){
  let html = '';
  var data = JSON.parse(response);
  if(data != ""){
    var properties = data.properties;
    var referred_property = data.referral_property;
    properties.forEach((item) => {

        html += `
          <tr>
            <td>${item.name}</td>
            <td>${referred_property.name}</td>
            <td>${item.referral_code}</td>
          </tr>`;
      });
  }
  if ($.fn.DataTable.isDataTable("#call_events_table")) {
    $("#call_events_table").DataTable().destroy();
  }
  
  // Update table body
  $("#call_events_container").html(html);
  load_datatable("call_events_table");
}

function createCallEventsTable(response, tableId, type) {
  $("#" + type + "_previous_btn").addClass('showHide');
  $("#" + type + "_next_btn").addClass('showHide');
  const tableSelector = "#" + type + "_events_table";
  let html = '';
  if(response != 0){
    const user_type = response.user_type;
    if(type == "call"){
      var logs_data = response.calls;
    }
    else{
      var logs_data = response.messages;
    }
    // Handle pagination tokens
    const next_page_uri = response.next_page_uri;
    const previous_page_uri = response.previous_page_uri;

    if (next_page_uri) {
      const nextPageToken = next_page_uri.split("PageToken=")[1].split("&StartTime")[0];
      $("#" + type + "_next_btn").removeClass('showHide');
      $("#next_btn_" + type + "_event_token").val(nextPageToken);
    }
    if (previous_page_uri) {
      const previousPageToken = previous_page_uri.split("PageToken=")[1].split("&StartTime")[0];
      $("#" + type + "_previous_btn").removeClass('showHide');
      $("#previous_btn_" + type + "_event_token").val(previousPageToken);
    }

    // Update page information
    $("#" + type + "_event_page").val(response.page);

    // Populate rows
    var item_price = 0;
    logs_data.forEach((item) => {

      var from = item.from;
      var to = item.to;
      var from_formatted_number = "N/A";
      var to_formatted_number = "N/A";
      // if(from.toLowerCase().startsWith('sip:')){
      //   from = "Sip";
      // }
      if(to.toLowerCase().startsWith('sip:')){
        to = "Sip";
        to_formatted_number = "Sip";
      }
      if(from.split("@sip.signalwire.com")[0]){
        from = from.split("@sip.signalwire.com")[0];
      }
      // if(to.split("@myautogate")[0]){
      //   to = to.split("@myautogate")[0];
      // }
      item_price = item.price * 2;
      
      if(from !== "" && from != "Sip"){
        from_formatted_number = callFormatPhoneNumber(from);
      }
      if(to !== "" && to != "Sip"){
        to_formatted_number = callFormatPhoneNumber(to);
      }
      html += `
        <tr>
          <td>${item.direction}</td>
          <td>${from_formatted_number}</td>
          <td>${to_formatted_number}</td>
          <td>${item.date_created || "N/A"}</td>
          <td>${item.status}</td>`;
      if(user_type != "user"){
          html += `<td>${item_price}</td>`;
      }
          
      if (type === "call") {
        html += `<td>${item.duration} sec</td>`;
      }
      if(item.is_ban == 0){
        html += `<td><a class="fas fa-ban text-danger mx-1" style="cursor: pointer;" title="Block" onclick="confirm_block_number('`+item.caller_cnam+`', '`+item.from+`', '`+type+`')"></a></td>`;
      }
      else{
        html += `<td><a class="fas fa-check text-success mx-1" style="cursor: pointer;" title="Un Block" onclick="delete_block_number('`+item.ban_id+`', '`+item.from+`', '`+type+`', 'log')"></a></td>`; 
      }
      html += `</tr>`;
      if((type === "call") && (item.cnam == 1)){
        html += `
          <tr>
            <td>Phone Number Lookup</td>
            <td>CNAM Lookup</td>
            <td></td>
            <td></td>
            <td></td>
            <td >0.016</td>
            <td ></td>
            <td ></td>
            `;
        html += `</tr>`;
      }

    });

    // Destroy existing DataTable instance if it exists
  }

  if ($.fn.DataTable.isDataTable(tableSelector)) {
    $(tableSelector).DataTable().destroy();
  }
  // Update table body
  $(tableSelector + " tbody").html(html);

  // Reinitialize DataTable
  $(tableSelector).DataTable({
    responsive: true,
    scrollCollapse: true,
    ordering: true,
    order: [],
    columnDefs: [
      { orderable: false, targets: -1 }, // Make last column not sortable
    ],
    paging: true,
    "pageLength": 10,
    searching: false,
    createdRow: function (row, data, dataIndex) {
      if (data[4] === "High") {
        $(row).addClass('highlight');
      }
    },
  });
}


function createEventsTable(responseData, tableId) {
  let data = responseData?.slice(0, 100);
  $(tableId).empty(); // Clear the existing content

  // Start creating the table structure
  let html = "";

  if (data.length != 0) {
    // <td><div style="background-color: green; text-align: center; color: white; padding: 4px 2px; font-size: 0.8rem; border-radius: 3px;">${item.status}</div></td>
    data.forEach(function (item) {
      const timeStamp= formatDateTime(item.timestamp);
      var old_val = item.old_value;
      if(old_val != null){
        var str_length = old_val.length;
        if(str_length > 26){
          old_val = old_val.slice(0, 26);
        }
      }
      else{
        old_val = "N/A";
      }
      var new_val = item.new_value;
      if(new_val != null){
        var str_length = new_val.length;
        if(str_length > 26){
          new_val = new_val.slice(0, 26);
        }
      }
      else{
        new_val = "N/A";
      }
      
      html += `
          <tr>
            <td>${item.action || "N/A"}</td>
            <td>${item.module_name || "N/A"}</td>
            <td>${item.user_email || "N/A"}</td>
            <td><span id='copy_old_event_`+item.old_value+`' style="display:none; color: green; margin-left: 10px;">Copied!<br></span><span title="${item.old_value}" onclick="copyText('`+item.old_value+`', 'copy_old_event_`+item.old_value+`')" style="cursor:pointer;">${old_val}</span></td>
            <td><span id='copy_new_event_`+item.new_value+`' style="display:none; color: green; margin-left: 10px;">Copied!<br></span><span title="${item.new_value}" onclick="copyText('`+item.new_value+`', 'copy_new_event_`+item.new_value+`')" style="cursor:pointer;">${new_val}</span></td>
            <td>${timeStamp || "N/A"}</td>
            <td>${item.additional_info}</td>
          </tr>
        `;
    });
  }

  if ($.fn.DataTable.isDataTable("#log_events_data_table")) {
    $("#log_events_data_table").DataTable().destroy();
  }
  
  $("#events_container").html(html);
  load_datatable("log_events_data_table");
}

function formatDateTimeEvents(dateString) {
  const date = new Date(dateString + "Z");
  const options = { weekday: "short" }; // "Sun", "Mon", "Tue", etc.
  const day = date.toLocaleDateString("en-US", options).toLocaleLowerCase();
  const time = date.toLocaleTimeString("en-US", {
    hour: "2-digit",
    minute: "2-digit",
    hour12: false, // 24-hour format
  });
  return { day, time };
}

function copyText(text, msg_id) {

  navigator.clipboard.writeText(text)
    .then(() => {
      const msg = document.getElementById(msg_id);
      msg.style.display = "inline";

      setTimeout(() => {
        msg.style.display = "none";
      }, 2000); // hide after 1.5 seconds
    })
    .catch(err => {
      console.error("Failed to copy text: ", err);
    });
}

function searchSystemEvents() {
  let searchValue = document
    .getElementById("searchEventsInput")
    ?.value.trim()
    .toLowerCase();
  let selectedModule = document.getElementById("event_modules")?.value;
  let startDate = document.getElementById("system_event_start_date")?.value;
  let endDate = document.getElementById("system_event_end_date")?.value;

  let textMatchedEvents = allEvents.filter(
    (event) =>
      !searchValue ||
      Object.values(event).some(
        (field) => field && field.toString().toLowerCase().includes(searchValue)
      )
  );

  let moduleFilteredEvents = textMatchedEvents.filter(
    (event) => !selectedModule || event.module_name === selectedModule
  );

  let dateFilteredEvents = moduleFilteredEvents.filter((event) => {
    let eventDate = new Date(event.timestamp); // Convert event timestamp to Date object
    let matchesStartDate = !startDate || eventDate >= new Date(startDate);
    let matchesEndDate = !endDate || eventDate <= new Date(endDate);
    return matchesStartDate && matchesEndDate;
  });
  createEventsTable(dateFilteredEvents, "#events_container");

  // Show "Clear filter" button if any filter is applied
  let clearButton = document.getElementById("systemEventsClearButton");
  if (searchValue || selectedModule || startDate || endDate) {
    clearButton.style.display = "inline-block";
  } else {
    clearButton.style.display = "none";
  }

}

function clearSystemEvents() {
  document.getElementById("searchEventsInput").value = "";
  document.getElementById("event_modules").value = "";
  document.getElementById("system_event_start_date").value = "";
  document.getElementById("system_event_end_date").value = "";
  document.getElementById("systemEventsClearButton").style.display = "none";
  createEventsTable(allEvents, "#events_container");
}

function block_call_sms_fields(val){
    $("#call_sms_block_modal").modal('show');
    $("#call_sms_block_number_type").val(val);
    $("#call_block_name").val('');
    $("#call_block_number").val('');
    var modal_heading = "";
    if(val == "call"){
      modal_heading = "Call Block Number";
    }
    else{
      modal_heading = "SMS Block Number";
    }
    const safeHtml = modal_heading;
    $("#call_sms_block_modal_heading").html(modal_heading);
}

function confirm_block_number(block_name, block_number, type){
  $("#call_block_name").val(block_name);
  $("#call_block_number").val(block_number);
  if(type == "message"){
    type = "sms";
  }
  $("#call_sms_block_number_type").val(type);
  $("#confirm_number_block_number").text(block_number);
  $("#confirm_block_number_modal").modal('show');
}

function block_number(is_type=""){
    var block_name = $("#call_block_name").val();
    var block_number = $("#call_block_number").val();
    var type = $("#call_sms_block_number_type").val();
    var is_valid = 1;
    if(is_type == "modal"){
      if(block_name == ""){
          is_valid = 0;
          $("#call_name_block_error_message").html("<span class='badge badge-danger'>Please add Name</span>");
      }
      else if(block_number == ""){
          is_valid = 0;
          $("#call_number_block_error_message").html("<span class='badge badge-danger'>Please add Number</span>");
      }
    }
    if(is_valid == 1){
      $.ajax({
        url: "/include/support_tickets/events_requests.php",
        type: "post",
        data: { save_blocked_number:'yes', 'block_name':block_name, 'block_number':block_number, 'type':type },
        success: function (response) {
          createCallSMSTable(type);
          if(response == 1){
            if(is_type == "modal"){
              $("#call_sms_block_modal").modal('hide');
            }
            else{
              $("#confirm_block_number_modal").modal('hide');
              if(type == "call"){
                type = "calls";
              }
              else if(type == "sms"){
                type = "message";
              }
              $("#"+type+"-event-tab").click();
            }
            $("#success_message").show();
            $("#success_message").html("<p class='alert alert-success mt-3'> "+ type +" blocked successfully of "+block_number+" </p>");
          }
          else{
            $("#error_sms_call_block_message").show();
            $("#error_sms_call_block_message").html("<p class='alert alert-danger mt-3'>"+response+"</p>")
          }

          setTimeout(function() {
              $("#error_sms_call_block_message").hide();
              $("#success_message").hide();
          }, 5000);
        }
      });
    }
}


function createCallSMSTable(type) {
  var container_id = "";
  var table_id = "";
  if(type == "call"){
    container_id = "call_block_container";
    table_id = "#call_block_table";
  }
  else{
    container_id = "sms_block_container";
    table_id = "#sms_block_table";
  }

  $.ajax({
    url: "/include/support_tickets/events_requests.php",
    type: "post",
    data: { get_block_data:'yes', 'type':type},
    success: function (response) {
      createCallBlockTable(response, container_id, table_id, type);
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

function createSnapshotTable(type) {
  var container_id = "";
  var table_id = "";
  container_id = "snapshot_list_container";
  table_id = "#snapshot_list_table";

  $.ajax({
    url: "/include/support_tickets/events_requests.php",
    type: "post",
    data: { get_snap_shot_data:'yes'},
    success: function (response) {
      createSnapTable(response, container_id, table_id);
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}


function createSnapTable(response, container_id, table_id) {
  let html = "";

  response.forEach((item) => {
    var event_name = escapeHTML(item.eventName);
    var event_type = escapeHTML(item.eventType);
    var event_detail = escapeHTML(item.eventDetail);
    var timestamp = escapeHTML(item.timestamp);
    var camera_snap = escapeHTML(item.camera_snap);
    var property_id = escapeHTML(item.property_id);
    var file_name = item.file_name;
    var camera_cell;
    if (file_name && file_name.trim() !== "" && file_name.toLowerCase() !== "null" && file_name.toLowerCase() !== "undefined") {
        var camera_snap = `/shared/snapshot_image.php?property_id=${property_id}&image_name=${file_name}`;
        camera_cell = `
          <div onclick="show_image_modal('snapImageModal', 'snapshotImage', '${camera_snap}')"> 
            <img src="${camera_snap}" alt="Snap" class="camera-snap-clickable" style="width: 90px; height: 90px; cursor: pointer;" title="Click to view larger image" data-image='${camera_snap}' data-name='Camera Snap'>
          </div>
        `;
    } else if (camera_snap && camera_snap.trim() !== "" && camera_snap.toLowerCase() !== "null" && camera_snap.toLowerCase() !== "undefined") {
      camera_cell = `<span class="badge badge-danger">${camera_snap}</span>`;
    }
    else{
      camera_cell = `<span class="badge badge-danger">No Image</span>`; 
    }
    html += `
      <tr>
        <td style="vertical-align: middle;">
          ${camera_cell}
        </td>
        <td>${event_name}</td>
        <td>${event_detail}</td>
        <td>${timestamp}</td>
        <td>${item.from_number || "N/A"}</td>
        <td>${item.to_number || "N/A"}</td>
        <td>${item.cnam || "N/A"}</td>
        <td>${item.released_by || "N/A"}</td>
        
      </tr>`;
  });

  if ($.fn.DataTable.isDataTable(table_id)) {
    $(table_id).DataTable().destroy();
  }

  // Update table body safely
  $(table_id + " tbody").html(html);

  // Reinitialize DataTable
  $(table_id).DataTable({
    "responsive": true,
    "order": [],
    "paging": true,
    "pageLength": 10,
    // "lengthMenu": [ [10, 25, 50, 100], [10, 25, 50, 100] ],
    "searching": false,
  });

}

function show_image_modal(model_id, image_id, image){
  document.getElementById(image_id).src = image;
  $("#"+model_id).modal('show');
}

function escapeHTML(str) {
  return String(str).replace(/[&<>"'`=\/]/g, function (s) {
    return ({
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#39;',
      '/': '&#x2F;',
      '`': '&#x60;',
      '=': '&#x3D;'
    })[s];
  });
}

// function createCallBlockTable(response, container_id, table_id, type){
//   html = "";
//   response.forEach((item) => {
//     html += `
//       <tr>
//         <td>${item.name}</td>
//         <td>${item.number}</td>
//         <td>${item.property_name}</td>
//         <td>${item.firstname+ " "+item.lastname}</td>
//         <td>
//             <a class="fas fa-trash text-danger mx-1" style="cursor: pointer;" title="Delete" onclick="delete_block_number('`+item.id+`', '`+item.number+`', '`+type+`', 'not_log')"></a>
//         </td>
//       </tr>`;
//   });

//   if ($.fn.DataTable.isDataTable(table_id)) {
//     $(table_id).DataTable().destroy();
//   }

//   // Update table body
//   $(table_id+" tbody").html(html);

//   // Reinitialize DataTable
//   $(table_id).DataTable({
//     responsive: true,
//     scrollCollapse: true,
//     ordering: true,
//     order: [],
//     columnDefs: [
//       { orderable: false, targets: -1 }, // Make last column not sortable
//     ],
//     paging: true,
//     "pageLength": 10,
//     searching: false,
//     createdRow: function (row, data, dataIndex) {
//       if (data[4] === "High") {
//         $(row).addClass('highlight');
//       }
//     },
//   });
// }

function createCallBlockTable(response, container_id, table_id, type) {
  let html = "";

  response.forEach((item) => {
    const name = escapeHTML(item.name);
    var number = escapeHTML(item.formatted_number);
    if(number != ""){
      number = callFormatPhoneNumber(number);
    }
    const property_name = escapeHTML(item.property_name);
    const full_name = escapeHTML(item.firstname + " " + item.lastname);
    const id = escapeHTML(item.id);
    const safeType = escapeHTML(type);

    html += `
      <tr>
        <td>${name}</td>
        <td>${number}</td>
        <td>${property_name}</td>
        <td>${full_name}</td>
        <td>
          <a class="fas fa-trash text-danger mx-1" style="cursor: pointer;" title="Delete"
             onclick="delete_block_number('${id}', '${number}', '${safeType}', 'not_log')"></a>
        </td>
      </tr>`;
  });

  if ($.fn.DataTable.isDataTable(table_id)) {
    $(table_id).DataTable().destroy();
  }

  // Update table body safely
  $(table_id + " tbody").html(html);

  // Reinitialize DataTable
  $(table_id).DataTable({
    responsive: true,
    scrollCollapse: true,
    ordering: true,
    order: [],
    columnDefs: [
      { orderable: false, targets: -1 }, // Last column not sortable
    ],
    paging: true,
    pageLength: 10,
    searching: false,
    createdRow: function (row, data, dataIndex) {
      if (data[4] === "High") {
        $(row).addClass('highlight');
      }
    },
  });
}

function delete_block_number(number_id, number, type, is_log){
  if(type == "message"){
    type = "sms";
  }
  $("#removed_number_type_modal").val(type);
  $("#removed_number_id_modal").val(number_id);
  $("#confirm_number_block").text(number);
  $("#number_remove_number").val(number);
  $("#is_log_hidden_unblock").val(is_log);
  $("#delete_block_number_modal").modal('show');
}

function remove_from_block(){
  var type = $("#removed_number_type_modal").val();
  var number_id = $("#removed_number_id_modal").val();
  var number = $("#number_remove_number").text();
  var is_log = $("#is_log_hidden_unblock").val();
  $.ajax({
    url: "/include/support_tickets/events_requests.php",
    type: "post",
    data: { removed_block_number:'yes', 'type':type, 'number_id':number_id},
    success: function (response) {
      $("#delete_block_number_modal").modal('hide');
      $("#success_message").show();
      $("#success_message").html("<p class='alert alert-success mt-3'> "+ type +" unblocked successfully of "+number+" </p>");
      if(is_log == "log"){
        if(type == "sms"){
          type = "message";
        }
        else if(type == "call"){
          type = "calls";
        }
        $("#"+type+"-event-tab").click();
      }
      else{
        createCallSMSTable(type);
      }
      setTimeout(function() {
          $("#success_message").hide();
      }, 5000);
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

function showBaseCostForm(modal_type, type){
  $(".sub_modal_value").val("");
  
    $.ajax({
      url: "/include/subscription/subscription.php",
      type: "post",
      data: {'getBaseCost':'yes'},
      success: function (response) {
        var json_parse = JSON.parse(response);
        var user_layer = json_parse.user_layer;
        var base_sub = json_parse.base_sub;
        var property_sub = json_parse.property_sub;
        var property_cameras = json_parse.property_cameras;
        var property_numbers = json_parse.property_numbers;
        var property_doors = json_parse.property_doors;
        var minimum_balance = base_sub.minimum_balance;
        var property_balance = json_parse.property_balance;
        var balance = 0;
        // if(user_layer == "admin" || user_layer == "super_admin"){
        //   if(base_sub == 0){
        //     $("#base_cost_btn").removeClass("showHide");
        //   }
        // }
        var dealer_sub_fee = base_sub.sub_fee;
        var dealer_camera_add = base_sub.camera_add;
        var dealer_number_add = base_sub.number_add;
        var dealer_door_add = base_sub.door_add;
        var msrp_sub_fee = base_sub.msrp_sub_fee;
        var msrp_camera_add = base_sub.msrp_camera_add;
        var msrp_number_add = base_sub.msrp_number_add;
        var msrp_door_add = base_sub.msrp_door_add;
        
        if(property_sub.sub_fee != 0 && property_sub.sub_fee != undefined){
          dealer_sub_fee = property_sub.sub_fee;
        }
        if(property_sub.camera_add != 0 && property_sub.camera_add != undefined){
          dealer_camera_add = property_sub.camera_add;
        }
        if(property_sub.number_add != 0 && property_sub.number_add != undefined){
          dealer_number_add = property_sub.number_add;
        }
        if(property_sub.door_add != 0 && property_sub.door_add != undefined){
          dealer_door_add = property_sub.door_add;
        }
        if(property_sub.msrp_sub_fee != 0 && property_sub.msrp_sub_fee != undefined){
          msrp_sub_fee = property_sub.msrp_sub_fee;
        }
        if(property_sub.msrp_camera_add != 0 && property_sub.msrp_camera_add != undefined){
          msrp_number_add = property_sub.msrp_camera_add;
        }
        if(property_sub.msrp_number_add != 0 && property_sub.msrp_number_add != undefined){
          msrp_number_add = property_sub.msrp_number_add;
        }
        if(property_sub.msrp_door_add != 0 && property_sub.msrp_door_add != undefined){
          msrp_door_add = property_sub.msrp_door_add;
        }
        if(property_balance != 0){
          if(property_balance.minimum_balance != 0 && property_balance.minimum_balance != undefined){
            minimum_balance = property_balance.minimum_balance;
          }
        }
        if(user_layer == "admin" || user_layer == "super_admin" || user_layer == "dealer"){
            $("#msrp_sub_fee").val(msrp_sub_fee);
            $("#msrp_camera_add").val(msrp_camera_add);
            $("#msrp_number_add").val(msrp_number_add);
            $("#msrp_door_add").val(msrp_door_add);
        }
        if(user_layer == "admin" || user_layer == "super_admin"){
            // $("#sub_added_id").val(base_sub.id);
          if(modal_type == "base"){
            $("#sub_fee").val(dealer_sub_fee);
            $("#camera_add").val(dealer_camera_add);
            $("#number_add").val(dealer_number_add);
            $("#door_add").val(dealer_door_add);
          }
          else if(modal_type == "balance"){
            $("#minmum_balance").val(minimum_balance);
          }
        }
        
      },
      error: function (xhr, status, error) {
        console.error("Failed to fetch data:", status, error);
      },
    }); 
  
  if(modal_type == "base"){ 
    $("#sub_cost_modal").modal('show');
  }
  else if(modal_type == "balance"){
    $("#balance_cost_modal").modal('show');
  }
}

function save_subscription(type){
  if(type == "base_cost"){

    $(".subscription_error").addClass("showHide");
    var edited_by = $("#edited_by").val();
    var msrp_sub_fee = $("#msrp_sub_fee").val();
    var msrp_camera_add = $("#msrp_camera_add").val();
    var msrp_number_add = $("#msrp_number_add").val();
    var msrp_door_add = $("#msrp_door_add").val();
    var msrp_cellular_sim = $("#msrp_cellular_sim_add").val();
    var sub_fee ="";
    var camera_add ="";
    var number_add ="";
    var door_add ="";
    var cellular_sim ="";
    if(edited_by == "admin" || edited_by == "super_admin"){
      sub_fee = $("#sub_fee").val();
      camera_add = $("#camera_add").val();
      number_add = $("#number_add").val();
      door_add = $("#door_add").val();
      cellular_sim = $("#cellular_sim_add").val();
      
      if(sub_fee == ""){
        $("#sub_fee_error").removeClass("showHide");
      }
      else if(camera_add == ""){
        $("#camera_add_error").removeClass("showHide");
      }
      else if(number_add == ""){
        $("#number_add_error").removeClass("showHide");
      }
      else if(door_add == ""){
        $("#door_add_error").removeClass("showHide");
      }
      else if(cellular_sim == ""){
        $("#cellular_sim_add_error").removeClass("showHide");
      }
    }
    
    if(msrp_sub_fee == ""){
      $("#msrp_sub_fee_error").removeClass("showHide");
    }
    else if(msrp_camera_add == ""){
      $("#msrp_camera_add_error").removeClass("showHide");
    }
    else if(msrp_number_add == ""){
      $("#msrp_number_add_error").removeClass("showHide");
    }
    else if(msrp_door_add == ""){
      $("#msrp_door_add_error").removeClass("showHide");
    }
    else if(msrp_cellular_sim == ""){
      $("#msrp_cellular_sim_add_error").removeClass("showHide"); 
    }
    else{
      var subscription_type = $("#subscription_type").val();
      $.ajax({
        url: "/include/subscription/subscription.php",
        type: "post",
        data: {'save_sub_form':'yes', 'sub_fee':sub_fee, 'camera_add':camera_add, 'number_add':number_add, 'door_add':door_add, 'msrp_sub_fee':msrp_sub_fee, 'msrp_camera_add':msrp_camera_add, 'msrp_number_add':msrp_number_add, 'msrp_door_add':msrp_door_add, cellular_sim:cellular_sim, msrp_cellular_sim:msrp_cellular_sim, 'subscription_type':subscription_type, 'edited_by':edited_by},
        success: function (response) {
          if(response == 1){
            $("#sub_cost_modal").modal('hide');
            $("#base_cost_btn").addClass('showHide');
            RedirectToActiveTabEvents('base_cost');
          }
          else{
            $("#error_sub_message").removeClass("showHide");
          }
        },
        error: function (xhr, status, error) {
          console.error("Failed to fetch data:", status, error);
        },
      });
    }
  }
  else if(type == "balance"){
    $("#minmum_balance_error").addClass("showHide");
    $("#minmum_balance_error_message").addClass("showHide");
    var minimum_balance = $("#minmum_balance").val();
    if(minimum_balance == ""){
      $("#minmum_balance_error").removeClass("showHide");
    }
    else{
      $.ajax({
        url: "/include/subscription/subscription.php",
        type: "post",
        data: {'save_balance_form':'yes', 'minimum_balance':minimum_balance, 'sub_id':sub_id},
        success: function (response) {
          console.log(response);
          if(response == 1){
            $("#balance_cost_modal").modal('hide');
            RedirectToActiveTabEvents('base_cost');
          }
          else{
            $("#minmum_balance_error_message").removeClass("showHide");
          }
        },
        error: function (xhr, status, error) {
          console.error("Failed to fetch data:", status, error);
        },
      });
    }
  }
}

function recharge_wallet(){
  $("#recharge_modal").modal('show');
}

function save_recharge_photo(){
  $("recharge_amount_message").addClass('showHide');
  var check_photo = $("#recharge_photo")[0].files;
  var recharge_amount = $("#recharge_amount").val();
  if(recharge_amount == 0 || recharge_amount == "" || recharge_amount == undefined){
    $("#recharge_amount_message").removeClass("showHide");
  }
  else if (check_photo.length > 0) {
    var formData = new FormData();
    formData.append("payment_proof", "yes");
    formData.append("payment_image", check_photo[0]);
    formData.append("recharge_amount", recharge_amount);

    $.ajax({
      url: "/include/subscription/subscription.php",
      type: "POST",
      data: formData,
      contentType: false,   // ✅ must be false for file upload
      processData: false,   // ✅ must be false for file upload
      success: function (response) {
        if(response == '1'){
          $("#recharge_modal").modal('hide');
          $("#recharge_photo").val("");
          $("#recharge_amount").val("");
          showSuccessGlobalToastMessage("Payment Proof uploaded successfully. Please wait from admin approval")
        }
        else{
          showErrorGlobalToastMessage("Something went wrong. Image not uploaded");
        }
      },
    });
  }
  else {
    $("#recharge_balance_error_message").html('Please add proof of payment');
    $("#recharge_balance_error_message").removeClass('showHide');
    setTimeout(function() {
        $("#recharge_balance_error_message").addClass('showHide');
    }, 5000);
    
  }
}

function createPaymentHistoryTable(response){
  let html = '';
  var data = JSON.parse(response);
  var histories = data.histories;
  var user_type = data.user_type;
  if(histories != ""){

    histories.forEach((item) => {
      var image_location = item.payment_image && typeof item.payment_image === 'string' ? item.payment_image : "";
      var fileExtension = image_location ? image_location.substring(image_location.lastIndexOf('.') + 1).toLowerCase() : '';

      var imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'jfif'];

      var payment_image = '';
      if (imageExtensions.includes(fileExtension)) {
          var imagePath = "/shared/serve_image.php?path=" + encodeURIComponent(image_location) + "&type=all_images";
          payment_image =`<div onclick="show_image_modal('paymentImageModal', 'paymentImage', '${imagePath}')"> 
            <img src="${imagePath}" alt="Payment Image" class="camera-snap-clickable" style="width: 90px; height: 90px; cursor: pointer;" title="Click to view larger image" data-image='${imagePath}' data-name='Payment Image'>
          </div>
        `;
      }

        html += `
          <tr>
            <td>${payment_image}</td>
            <td>${item.amount}</td>
            <td>${item.created_at}</td>`;
            
            if(user_type == "admin" || user_type == "super_admin"){
              html += `<td>` + item.firstname + item.lastname + `</td>`;
            }

          html += `</tr>`;
      });
  }
  if ($.fn.DataTable.isDataTable("#payment_history_table")) {
    $("#payment_history_table").DataTable().destroy();
  }
  
  // Update table body
  $("#payment_history_container").html(html);
  load_datatable("payment_history_table");
}

function createInvoiceHistoryTable(response){
  let html = '';
  var data = JSON.parse(response);
  var invoice_dates = data.invoice_dates;
  var property_id = data.property_id;
  if(invoice_dates != ""){
    invoice_dates.forEach((item) => {
      html += `
        <tr>
          <td><span onclick="show_invoice_modal('${item.last_date}')" style="cursor:pointer;"><b>${item.last_date} </b></span></td>
          <td><span onclick="show_invoice_modal('${item.last_date}')" style="cursor:pointer;"><b>Monthly Statement for ${item.label}</b></span></td>
          <td><button class="btn btn-primary mr-1" onclick="show_invoice_modal('${item.last_date}')" style="cursor:pointer;" title="Monthly Statement for ${item.label}"><i class="fa fa-eye"></i></button></td>
        </tr>`;
    });
  }
  if ($.fn.DataTable.isDataTable("#invoice_history_table")) {
    $("#invoice_history_table").DataTable().destroy();
  }
  
  // Update table body
  $("#invoice_history_container").html(html);
  load_datatable("invoice_history_table");
}

function show_invoice_modal(invoice_date){
  var type = "";
  var is_invoice = 1;
  BaseCostData({ getBaseCost: "yes", invoice_date:invoice_date}, type="", invoice_date, is_invoice);
  $("#invoice_modal").modal('show');
}

// Usage:
function getPendingPayments(data){
  $.ajax({
    url: "/include/subscription/subscription.php",
    type: "post",
    data,
    success: function (response) {
        pendingPaymentTable(response);
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

function pendingPaymentTable(response){
  let html = '';
  var data = JSON.parse(response);
  if(data != ""){

    data.forEach((item) => {
      var image_location = item.payment_image && typeof item.payment_image === 'string' ? item.payment_image : "";
      var fileExtension = image_location ? image_location.substring(image_location.lastIndexOf('.') + 1).toLowerCase() : '';

      var imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'jfif'];

      var payment_image = '';
      if (imageExtensions.includes(fileExtension)) {
          var imagePath = "/shared/serve_image.php?path=" + encodeURIComponent(image_location) + "&type=all_images";
          payment_image =`<div onclick="show_image_modal('pendingImageModal', 'pendingPaymentImage', '${imagePath}')"> 
            <img src="${imagePath}" alt="Payment Image" class="camera-snap-clickable" style="width: 90px; height: 90px; cursor: pointer;" title="Click to view larger image" data-image='${imagePath}' data-name='Payment Image'>
          </div>
        `;
      }

        html += `
          <tr>
            <td>${payment_image}</td>
            <td>${item.name}</td>
            <td>${item.amount}</td>
            <td>${item.created_at}</td>
            <td><button class='btn btn-success mr-1' onclick="approve_payment(` + item.id + `, `+item.amount+`, '`+item.name+`')" title='Approve'><i class='fa fa-check'></i></button></td>
          </tr>`;
      });
  }
  if ($.fn.DataTable.isDataTable("#pendingPaymentTable")) {
    $("#pendingPaymentTable").DataTable().destroy();
  }
  
  // Update table body
  $("#PendingPaymentTableBody").html(html);
  load_datatable("pendingPaymentTable");
}

function approve_payment(payment_id, amount, name){
  $("#pending_payment_amount").val(amount);
  $("#pending_payment_property").html(name);
  $("#pending_payment_id").val(payment_id);
  $("#approve_pending_payment_model").modal('show');
}

function approve_pending_payment(){
  var amount = $("#pending_payment_amount").val();
  var payment_id = $("#pending_payment_id").val();
  if(amount != ""){
    $.ajax({
      url: "/include/subscription/subscription.php",
      type: "post",
      data: {approve_pending_payment:'yes', payment_id:payment_id, amount:amount},
      success: function (response) {
          $("#approve_pending_payment_model").modal('hide');
          if(response == 1){
            showSuccessGlobalToastMessage("Amount added successfully into your wallet");
          }
          else{
            showErrorGlobalToastMessage("Something went wrong.");
          }
          getPendingPayments({ getPendingPayment: "yes"});

      },
      error: function (xhr, status, error) {
        console.error("Failed to fetch data:", status, error);
      },
    });
  }
}

function edit_callular_sim(){
  $("#cellular_sim_qty_message").addClass("showHide");
  $("#cellular_sim_qty_error_message").addClass("showHide");
  var total_sim = $("#total_callular_sim").val();
  $("#cellular_sim_qty").val(total_sim);
  $("#callular_modal").modal('show');
}

function save_cellular_sim_qty(){
  var qty = $("#cellular_sim_qty").val();
  $.ajax({
    url: "/include/subscription/subscription.php",
    type: "post",
    data: {add_sim:'yes', qty:qty},
    success: function (response) {
        if(response == 1){
          showSuccessGlobalToastMessage("Data saved successfully");
          BaseCostData({ getBaseCost: "yes"});
          $("#callular_modal").modal('hide');

        }
        else{
          showErrorGlobalToastMessage("Something went wrong.");
        }

    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}
