let isTested = false;
let allCameras = [];
let isCameraCardView = false;

$(document).ready(async function () {
  const sessionPreferences = sessionStorage.getItem("preferences");
  if(sessionPreferences){
    const preferencesData = await parseJSONData(sessionPreferences);
    preferencesData?.is_card_view==1? isCameraCardView = true:isCameraCardView = false;
  }else {
    const preferences = await asyncGetPreferencesRequestForView({
      get_preferences_for_property_user: true,
      property_id: sessionStorage.getItem("propertyId"),
    });
    if(preferences?.length>0) sessionStorage.setItem("preferences",JSON.stringify(preferences[0])); 
    if(preferences?.length>0 && preferences[0]?.is_card_view==1) isCameraCardView = true;
  }
  
  $("#createRTSPUrl").hide();
  const urlParams = new URLSearchParams(window.location.search);
  const sub_tab = urlParams.get("sub_tab");
  if (sub_tab === "cam") {
    const profileTabTrigger = document.querySelector('#profile-tab');
    if (profileTabTrigger) {
      new bootstrap.Tab(profileTabTrigger).show(); // Use Bootstrap's JS API to activate tab
    }
  }
  sendRequest({
    getSettingsData: "yes",
    property_id: sessionStorage.getItem("propertyId"),
  });

  toggleFtpInputs();
  
});

$(document).on('click', '.copy-btn', function () {
  const targetId = $(this).data('copy-target');
  const el = document.getElementById(targetId);
  const text = el?.value || el?.textContent;
  if (!text) return;

  const icon = $(this).find('i');
  const originalClass = icon.attr('class');

  navigator.clipboard.writeText(text).then(() => {
    icon.removeClass().addClass('fa-solid fa-check text-success');

    setTimeout(() => {
      icon.attr('class', originalClass);
    }, 1500);
  });
});

function changeCameraView() {
  const search_camera_container = document.getElementById("search_camera_value");
  const search_camera_tab = document.getElementById("searchCameraInput");
  if (window.innerWidth <= 600 || isCameraCardView){
    search_camera_container.style.display="flex";
    search_camera_tab.style.display="none";
    createCameraCardView(allCameras);
  }else {
    search_camera_container.style.display="none";
    search_camera_tab.style.display="flex";
    createStreamingTable(allCameras);
  }
}

function createCameraCardView(data) {
  $("#settings_table").empty();
  if (!data || data.length === 0) {
    const noDataHtml = `
      <div class="text-center p-4">
        <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
        <h5 class="text-muted">No Cameras Found</h5>
        <p class="text-muted">There are no cameras to display.</p>
      </div>
    `;
    document.getElementById("settings_table").innerHTML=DOMPurify.sanitize(noDataHtml);
    return;
  }

  let html = "";
  html += `<div class="row">`;
  data.forEach(function (item) {
    html += `<div class="col-lg-6 col-md-12 col-sm-12">
                <div class="card mb-3">
                    <div class="card-header d-flex align-items-center">
                        <h5 class="mb-0">${item?.cameraName}</h5>
                        <div class="ml-auto">
                          <i class="fa-solid fa-eye cursor_pointer mr-2 view-camera" data-id="${item.id}"> </i>
                          <i class='fas fa-edit text-primary mr-2 edit-streaming cursor_pointer' data-id="${item.id}"></i>
                          ${item.ftp_host?`<i class="fa-solid fa-video mr-2 text-success cursor_pointer redirect-playback" data-id="${item.id}"></i>`:''}
                          <i class='fas fa-trash-alt text-danger delete-streaming cursor_pointer' data-id="${item.id}"></i>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="d-flex flex-wrap">
                            <div class="single_info">
                                <p class="m-0 p-0"><strong class="pr-1">Model:</strong> ${
                                  item?.cameraModel || "N/A"
                                }</p>
                            </div>
                            <div class="single_info">
                                <p class="m-0 p-0"><strong class="pr-1">Image port:</strong> ${
                                  item?.liveImagePort || "N/A"
                                }</p>
                            </div>
                            <div class="single_info">
                                <p class="m-0 p-0"><strong class="pr-1">Ip:</strong> ${
                                  item?.IP || "N/A"
                                }</p>
                            </div>
                            <div class="single_info">
                                <p class="m-0 p-0"><strong class="pr-1">Image Url:</strong> ${
                                  item?.liveImageURL || "N/A"
                                }</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>`;
    // --- Save for later --- \\
    // html += `<div class="col-lg-6 col-md-12 col-sm-12">
    //     <div class="card mb-3">
    //         <div class="card-header d-flex align-items-center">
    //             <h5 class="mb-0">${item?.cameraName}</h5>
    //             <div class="ml-auto">
    //               <i class="fa-solid fa-eye cursor_pointer mr-2 view-camera" data-id="${item.id}"> </i>
    //               <i class='fas fa-edit text-primary mr-2 edit-streaming cursor_pointer' data-id="${item.id}"></i>
    //               ${item.ftp_host?`<i class="fa-solid fa-video mr-2 text-success cursor_pointer redirect-playback" data-id="${item.id}"></i>`:''}
    //               <i class='fas fa-trash-alt text-danger delete-streaming cursor_pointer' data-id="${item.id}"></i>
    //             </div>
    //         </div>
    //         <div class="card-body">
    //             <div class="d-flex flex-wrap">
    //                 <div class="single_info">
    //                     <p class="m-0 p-0"><strong class="pr-1">Model:</strong> ${
    //                       item?.cameraModel || "N/A"
    //                     }</p>
    //                 </div>
    //                 <div class="single_info">
    //                     <p class="m-0 p-0"><strong class="pr-1">RTSP:</strong>${
    //                       item?.streamingUrl || "N/A"
    //                     }</p>
    //                 </div>
    //                 <div class="single_info">
    //                     <p class="m-0 p-0"><strong class="pr-1">RTSP port:</strong>${
    //                       item?.RTSP_PORT || "N/A"
    //                     }</p>
    //                 </div>
    //                 <div class="single_info">
    //                     <p class="m-0 p-0"><strong class="pr-1">Image port:</strong> ${
    //                       item?.liveImagePort || "N/A"
    //                     }</p>
    //                 </div>
    //                 <div class="single_info">
    //                     <p class="m-0 p-0"><strong class="pr-1">Ip:</strong> ${
    //                       item?.IP || "N/A"
    //                     }</p>
    //                 </div>
    //                 <div class="single_info">
    //                     <p class="m-0 p-0"><strong class="pr-1">Image Url:</strong> ${
    //                       item?.liveImageURL || "N/A"
    //                     }</p>
    //                 </div>
    //             </div>
    //         </div>
    //     </div>
    // </div>`;
  });
  html += `</div>`;
  document.getElementById("settings_table").innerHTML = DOMPurify.sanitize(html);
  bindStreamingTableEvents();
}

function createStreamingTable(responseData) {
  let data = responseData;
  document.getElementById("settings_table").innerHTML="";
  // Start creating the table structure
  let html = `
    <div class="table-responsive">
      <table id="camera_data_table" class="table table-bordered table-head-fixed text-nowrap table-hover" style="width:100%;">
        <thead>
          <tr>
            <th>Name</th>
            <th>Model</th>
            <th>Image URL</th>
            <th>IP</th>
            <th>Image Port</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
  `;
  // --- Save for later --- \\
  // let html = `
  //   <div class="table-responsive">
  //     <table id="camera_data_table" class="table table-bordered table-head-fixed text-nowrap table-hover" style="width:100%;">
  //       <thead>
  //         <tr>
  //           <th>Camera Name</th>
  //           <th>Camera Model</th>
  //           <th>Streaming URL</th>
  //           <th>Image URL</th>
  //           <th>IP</th>
  //           <th>RTSP Port</th>
  //           <th>Image Port</th>
  //           <th>Action</th>
  //         </tr>
  //       </thead>
  //       <tbody>
  // `;

  if (data.length === 0) {
    html +=
      "<tr><td colspan='10' class='text-center'>No data available</td></tr>";
  } else {
    data.forEach(function (item) {
      html += `
        <tr>
          <td>${item.cameraName || ""}</td>
          <td>${item.cameraModel || ""}</td>
          <td>${item.liveImageURL || ""}</td>
          <td>${item.IP || ""}</td>
          <td>${item.liveImagePort || ""}</td>
          <td>
            <i class="fa-solid fa-eye cursor_pointer mr-2 view-camera" data-id="${item.id}"> </i>
            <i class='fas fa-edit text-primary mr-2 edit-streaming cursor_pointer' data-id="${item.id}"></i>
            ${item.ftp_host?`<i class="fa-solid fa-video mr-2 text-success cursor_pointer redirect-playback" data-id="${item.id}"></i>`:''}
            <i class='fas fa-trash-alt text-danger delete-streaming cursor_pointer' data-id="${item.id}"></i>
          </td>
        </tr>
      `;
    });
    // --- Save for later --- \\
    // data.forEach(function (item) {
    //   html += `
    //     <tr>
    //       <td>${item.cameraName || ""}</td>
    //       <td>${item.cameraModel || ""}</td>
    //       <td>${item.streamingUrl || ""}</td>
    //       <td>${item.liveImageURL || ""}</td>
    //       <td>${item.IP || ""}</td>
    //       <td>${item.RTSP_PORT || ""}</td>
    //       <td>${item.liveImagePort || ""}</td>
    //       <td>
    //         <i class="fa-solid fa-eye cursor_pointer mr-2 view-camera" data-id="${item.id}"> </i>
    //         <i class='fas fa-edit text-primary mr-2 edit-streaming cursor_pointer' data-id="${item.id}"></i>
    //         ${item.ftp_host?`<i class="fa-solid fa-video mr-2 text-success cursor_pointer redirect-playback" data-id="${item.id}"></i>`:''}
    //         <i class='fas fa-trash-alt text-danger delete-streaming cursor_pointer' data-id="${item.id}"></i>
    //       </td>
    //     </tr>
    //   `;
    // });
  }

  // Close the tbody and table tags
  html += `
        </tbody>
      </table>
    </div>
  `;

  // Insert the entire table structure into the specified element

  document.getElementById("settings_table").innerHTML = DOMPurify.sanitize(html);
  bindStreamingTableEvents();
  if (
    !$.fn.DataTable.isDataTable("#camera_data_table") &&
    data?.length
  ) {
    // new DataTable('#command_center_complete_data_table');
    $("#camera_data_table").DataTable({
      "responsive": true,
      "order": [],
      "paging": false,
      "pageLength": -1,
      // "lengthMenu": [ [10, 25, 50, 100], [10, 25, 50, 100] ],
      "searching": false,
    });
  } else if (data?.length > 0) {
    $("#camera_data_table").DataTable().order([]).draw();
  }
}

function bindStreamingTableEvents() {
  const $container = $("#settings_table");
  $container.off("click", ".view-camera");
  $container.off("click", ".edit-streaming");
  $container.off("click", ".redirect-playback");
  $container.off("click", ".delete-streaming");
  $container.on("click", ".view-camera", function () {
    const id = $(this).data("id");
    viewModeOfCamera(id);
  });
  $container.on("click", ".edit-streaming", function () {
    const id = $(this).data("id");
    editStreaming(id);
  });
  $container.on("click", ".redirect-playback", function () {
    const id = $(this).data("id");
    redirect_playback(id);
  });
  $container.on("click", ".delete-streaming", function () {
    const id = $(this).data("id");
    deleteStreaming(id);
  });
}

function resetForm() {
  $("#addSettingForm")[0].reset();
  isRTSPStreaming();
  isFtpServer();
  document.getElementById("testCameraStatusIcon").innerHTML="";
  isTested = false;
  document.getElementById("AddSetting").innerHTML="Add";
  $("#AddSetting").text("Add");
  document.getElementById("settingId").value = "";
}

function redirect_playback(id) {
  if (!id) return;
  const url = `/playback.php?id=${id}`;
  window.location.href = url;
}

function editStreaming(id) {
  sendRequest({ getSettingDataById: "yes", settingId: id });
}

function addSettings(event) {
  event.preventDefault();
  let cameraName = document.getElementById("cameraName").value;
  let streamingUrl = document.getElementById("StreamingUrl").value;
  let cameraModel = document.getElementById("cameraModel").value;
  let userName = document.getElementById("Username").value;
  let password = document.getElementById("Password").value;
  let IP = document.getElementById("IP").value;
  let RTSP_PORT = document.getElementById("RTSP_PORT").value;
  let liveImagePort = document.getElementById("liveImagePort").value;
  let liveImageURL = document.getElementById("liveImageUrlId").value;
  let camera_ftp_folder = document.getElementById("camera_ftp_folder").value;
  let ftp_host = document.getElementById("ftp_host").value;
  let ftp_user = document.getElementById("ftp_user").value;
  let ftp_password = document.getElementById("ftp_password").value;
  let ftp_port = document.getElementById("ftp_port").value;
  let property_id=sessionStorage.getItem("propertyId");
  if (!isTested) {
    document.getElementById("testingError").innerHTML="Please test the image first";
    const errorEl = document.getElementById("testingError");
    if (errorEl) {
      errorEl.scrollIntoView({ behavior: "smooth", block: "center" });
    }
    return;
  }

  let ftp_mode = "";
  let ftp_managed_id = null;
  let ftp_managed_folder = "";

  if (document.getElementById("haveFTPServer").checked) {
    if (document.getElementById("ftpManaged").checked) {
      ftp_mode = "managed";
      ftp_managed_id = document.getElementById("ftp_managed_select").value || null;
      ftp_managed_folder = document.getElementById("camera_folder_name").value || null;
    } else if (document.getElementById("ftpCustom").checked) {
      ftp_mode = "custom";
    }
  }

  let formValues = {
    cameraName,
    streamingUrl,
    userName,
    password,
    cameraModel,
    IP,
    RTSP_PORT,
    liveImagePort,
    liveImageURL,
    property_id,
    camera_ftp_folder,
    ftp_host,
    ftp_user,
    ftp_password,
    ftp_port,
    ftp_mode,
    ftp_managed_id,
    ftp_managed_folder
  };

  if (ftp_mode === "custom") {
    formValues.ftp_host = ftp_host;
    formValues.ftp_user = ftp_user;
    formValues.ftp_password = ftp_password;
    formValues.ftp_port = ftp_port;
  }
  
  let isEditing = $("#AddSetting")?.text()?.trim() === "Update";
  if (!isEditing) formValues.addForm = "yes";
  else {
    formValues.updateSettings = "yes";
    formValues.settingsId = document.getElementById("settingId").value;
  }
  sendRequest(formValues);
}

// function deleteStreaming(id) {
//   if (!confirm("Are you sure you want to delete")) return;
//   sendRequest({ deleteSetting: "yes", settingId: id, property_id:sessionStorage.getItem("propertyId")});
// }
function deleteStreaming(id) {
  showConfirmModal(
    "Are you sure you want to delete?",
    function () {
      sendRequest({
        deleteSetting: "yes",
        settingId: id,
        property_id: sessionStorage.getItem("propertyId"),
      });
    }
  );
}


function sendRequest(data) {
  $.ajax({
    url: "include/dashboard/settings_requests.php",
    type: "post",
    data,
    success: function (response) {
      if (data?.getSettingsData){
        allCameras=response?.data;
        changeCameraView();
      } 
      if (data?.addForm || data?.deleteSetting || data?.updateSettings) {
        $("#addNewSetting").modal("hide");
        sendRequest({
          getSettingsData: "yes",
          property_id: sessionStorage.getItem("propertyId")
        });
      }
      if (data?.getSettingDataById) {
        editRecord(response);
      }
      if (response?.error) console.log("got error", response);
    },
    error: function (xhr, status, error) {
      if (xhr?.responseJSON?.error)
        show_camera_toast_message(xhr?.responseJSON?.error);
      else show_camera_toast_message(JSON.stringify(error));
    },
  });
}

function show_camera_toast_message(errorMessage, delayTime = 4000) {
  document.getElementById("cameraToastMessage").style.display = "block";
  document.getElementById("cameraErrorToast").innerHTML = errorMessage;
  var toastEl = document.getElementById("camera_hardware_Toast");
  var toast = new bootstrap.Toast(toastEl, {
    delay: delayTime,
    autohide: false,
  });
  toast.show();

  setTimeout(() => {
    closeCameraToastMessage();
  }, delayTime);
}

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

function toggleFtpOptions() {
  const checked = document.getElementById("haveFTPServer").checked;
  $("#ftpManagedDropdownContainer").hide();
  $("#managedCredsBtnWrap").hide();
  $("#ftpOptions").toggle(checked);
  if (!checked) {
    document.getElementById("ftpManaged").checked = false;
    document.getElementById("ftpCustom").checked = false;
    $("#ftpCustomInputs").hide();
    $("#ftpManagedDropdownContainer").hide();
  }
}

function refreshManagedCredsButton(mode, bindingValues) {
  const isEdit = !!document.getElementById("settingId").value; // edit if has id
  const wrap   = document.getElementById("managedCredsBtnWrap");
  const btn    = document.getElementById("viewFtpCredsBtn");
  const hint   = document.getElementById("managedCredsHint");

  if (!wrap || !btn || !hint) return;

  const show = isEdit && (mode === "managed");
  wrap.style.display = show ? "block" : "none";

  if (!show) return;

  const hasManagedCreds = !!(
    bindingValues?.ftp_host &&
    bindingValues?.ftp_user &&
    bindingValues?.ftp_password &&
    bindingValues?.ftp_port
  );

  btn.disabled = !hasManagedCreds;
  hint.style.display = hasManagedCreds ? "none" : "inline";
}

function toggleFtpInputs() {
  const isCustom = document.getElementById("ftpCustom").checked;
  const isManaged = document.getElementById("ftpManaged").checked;
  const originalMode = (document.getElementById("original_ftp_mode").value || '').toLowerCase();

  $("#ftpCustomInputs").toggle(isCustom);
  $("#ftpManagedDropdownContainer").toggle(isManaged);

  const folderInput = document.getElementById("camera_folder_name");
  if (isManaged) {
    folderInput.removeAttribute("disabled");
    folderInput.setAttribute("required", "required");
  } else {
    folderInput.setAttribute("disabled", "disabled");
    folderInput.removeAttribute("required");
  }

  if (originalMode === 'managed' && isCustom) {
    const ok = window.confirm(
      "Switching away from Managed FTP will delete the virtual user and the limited camera folder on the FTP server. This cannot be undone. Continue?"
    );
    document.getElementById("confirm_switch_ftp").value = ok ? "1" : "0";
    if (!ok) {
      document.getElementById("ftpManaged").checked = true;
      document.getElementById("ftpCustom").checked  = false;
      $("#ftpCustomInputs").hide();
      $("#ftpManagedDropdownContainer").show();
      $("#ftpCredentialsContainer").show();
    }
  } else {
    document.getElementById("confirm_switch_ftp").value = "0";
  }
  refreshManagedCredsButton(isManaged ? "managed" : "custom", {});
}

function editRecord(setting) {
  $("#haveRTSPStreaming").prop("checked", false);
  document.getElementById("cameraName").value = setting.cameraName;
  document.getElementById("StreamingUrl").value = setting.streamingUrl;
  document.getElementById("Username").value = setting.userName;
  document.getElementById("Password").value = setting.password;
  document.getElementById("cameraModel").value = setting.cameraModel;
  document.getElementById("settingId").value = setting.id;
  document.getElementById("IP").value = setting.IP;
  document.getElementById("RTSP_PORT").value = setting.RTSP_PORT;
  document.getElementById("liveImagePort").value = setting?.liveImagePort;
  document.getElementById("liveImageUrlId").value = setting?.liveImageURL || "";
  document.getElementById("testCameraStatusIcon").innerHTML="";
  let hiddenIdField = document.getElementById("settingId");
  if (hiddenIdField) {
    hiddenIdField.value = setting.id;
  }
  isTested = false;
  if(setting.RTSP_PORT){
    $("#haveRTSPStreaming").prop("checked", true);
    isRTSPStreaming();
  }

  if (setting.ftp_host || setting.ftp_mode) {
    $("#haveFTPServer").prop("checked", true);
    isFtpServer(setting);
  } else {
    document.getElementById("haveFTPServer").checked = false;
    isFtpServer();
  }
  
  $("#addNewSetting").modal("show");
  $("#AddSetting").text("Update");
}

function create_RTSP_URL() {
  let userName = document.getElementById("Username").value;
  let password = document.getElementById("Password").value;
  let IP = document.getElementById("IP").value;
  let port = document.getElementById("liveImagePort").value;
  let RTSP_PORT = document.getElementById("RTSP_PORT").value;
  let liveImageUrl = `http://${userName}:${password}@${IP}:${port}/snap.jpg`;
  document.getElementById("liveImageUrlId").value = liveImageUrl;
  let haveRTSPStreaming = document.getElementById("haveRTSPStreaming").checked;
  if (haveRTSPStreaming) {
    let rtspURL = `rtsp://${userName}:${password}@${IP}:${RTSP_PORT}`;
    document.getElementById("StreamingUrl").value = rtspURL;
  }
}

function isRTSPStreaming() {
  let haveRTSPStreaming = document.getElementById("haveRTSPStreaming").checked;
  if (haveRTSPStreaming) {
    $("#createRTSPUrl").show();
  } else {
    $("#createRTSPUrl").hide();
    document.getElementById("RTSP_PORT").value = '';
    document.getElementById("StreamingUrl").value = '';
  }
}

function isFtpServer(bindingValues = null) {
  document.getElementById("original_ftp_mode").value = (bindingValues?.ftp_mode || "").toLowerCase();
  const haveFTPServer = document.getElementById("haveFTPServer").checked;
  $("#ftpOptions").toggle(haveFTPServer);

  const mode = (bindingValues?.ftp_mode || "custom").toLowerCase();
  if (haveFTPServer) {
    document.getElementById("ftpManaged").checked = mode === "managed";
    document.getElementById("ftpCustom").checked = mode === "custom";
    toggleFtpInputs();
  }

  if (mode === "managed") {
    loadFtpServerOptions(bindingValues?.ftp_managed_id || null, bindingValues?.ftp_managed_folder || null, bindingValues?.ftp_port || null, bindingValues?.ftp_host || null, bindingValues?.ftp_user || null, bindingValues?.ftp_password || null);
  } else {
    loadFtpServerOptions();
  }

  document.getElementById("camera_ftp_folder").value = bindingValues?.camera_ftp_folder || '';
  refreshManagedCredsButton(mode, bindingValues);
}

$(document).on("click", "#viewFtpCredsBtn", function (e) {
  e.preventDefault();
  e.stopPropagation();

  const cameraId = document.getElementById("settingId")?.value;
  if (!cameraId) return;

  clearFtpCredsModal();

  $("#ftpCredsModal").modal({ backdrop: 'static', keyboard: false });

  $.post("include/dashboard/settings_requests.php", { getFtpCreds: "yes", camera_id: cameraId })
   .done(function (resp) {
      if (!resp || resp.error) {
        closeFtpCredsModal();
        showToast(resp?.error || "Failed to fetch FTP credentials.");
        return;
      }

      $("#ftpModalHost").val(resp.host || "");
      $("#ftpModalPort").val(resp.port || "");
      $("#ftpModalUser").val(resp.user || "");
      $("#ftpModalPass").val(resp.password || "");
      $("#ftpModalFolder").val(resp.folder || "");
    })
   .fail(function () {
      closeFtpCredsModal();
      showToast("Network error while fetching credentials.");
    });
});

$(document).on("click", ".copy-btn", function (e) {
  e.preventDefault();
  e.stopPropagation();
  const targetId = this.getAttribute("data-copy-target");
  const el = document.getElementById(targetId);
  if (!el) return;
  navigator.clipboard.writeText(el.value || el.textContent || "")
    .then(() => showToast("Copied"))
    .catch(() => showToast("Copy failed"));
});

$(document).on("click", "#togglePassVis", function (e) {
  e.preventDefault();
  e.stopPropagation();
  const inp = document.getElementById("ftpModalPass");
  if (!inp) return;
  const showing = inp.getAttribute("type") === "text";
  inp.setAttribute("type", showing ? "password" : "text");
});

$(document).on('hidden.bs.modal', '.modal', function () {
  if ($('.modal.show').length) {
    $('body').addClass('modal-open');
  }
});

function clearFtpCredsModal() {
  $("#ftpModalHost, #ftpModalPort, #ftpModalUser, #ftpModalPass, #ftpModalFolder").val("");
}
function closeFtpCredsModal() {
  clearFtpCredsModal();
  $("#ftpCredsModal").modal("hide");
}
function showToast(msg, delayMs = 4000) {
  try {
    show_camera_toast_message(msg, delayMs);
  } catch (e) {
    console.log(msg);
  }
}

function loadFtpServerOptions(selectedId = null, folderName = null, ftpPort = null, ftpHost = null, ftpUser = null, ftpPass = null) {
  $.post("include/dashboard/settings_requests.php", { getFtpServers: "yes" }, function (servers) {
    const select = document.getElementById("ftp_managed_select");
    const fld = document.getElementById("camera_folder_name");
    select.innerHTML = "";

    const placeholderOption = document.createElement("option");
    placeholderOption.value = "";
    placeholderOption.textContent = "Please Select a Server";
    placeholderOption.disabled = true;
    placeholderOption.selected = !selectedId;
    select.appendChild(placeholderOption);
    select.disabled = false;
    fld.disabled = false;

    if (!servers || !Array.isArray(servers)) return;

    servers.forEach(server => {
      const opt = document.createElement("option");
      opt.value = server.id;
      opt.textContent = server.label;
      if (selectedId && parseInt(selectedId) === parseInt(server.id)) {
        opt.selected = true;
        placeholderOption.selected = false;

        if (folderName) {
          select.disabled = true;
          fld.disabled = true;
          if (fld) fld.value = folderName;
        }
      }
      select.appendChild(opt);
    });
  });
}

function testLiveImageUrl() {
  let imageUrl = document.getElementById("liveImageUrlId").value;
  const Password = document.getElementById("Password").value;
  const Username = document.getElementById("Username").value;
  if(!Password || !Username){
    show_camera_toast_message("Please enter the password and username");
    return;
  }
  if(!imageUrl){
    show_camera_toast_message("Please enter the image url");
    return;
  }
  document.getElementById("loadingIndicator").style.display = "inline-block";
  document.querySelector(
    "button[onclick='testLiveImageUrl()']"
  ).disabled = true;
  sendServerRequest({ singleImage: "yes", imageUrl, Password, Username });
}

function sendServerRequest(data) {
  const testCameraStatusIcon=document.getElementById("testCameraStatusIcon");
  $.ajax({
    url: "include/dashboard/server.php",
    type: "post",
    data,
    success: function (response) {
      document.getElementById("loadingIndicator").style.display = "none";
      document.querySelector(
        "button[onclick='testLiveImageUrl()']"
      ).disabled = false;
      if (response?.error) {
        console.log("got error", response);
        $("#testingError").text(response?.error);
        isTested = false;
        return;
      }

      if (data?.singleImage) {
        if (isBase64Image(response?.image)) {
          isTested = true;
          $("#testingError").text(
            ""
          );
          testCameraStatusIcon.style.display = "block";
          testCameraStatusIcon.innerHTML =
            '<i class="fas fa-check" style="color: white; margin-left: 5px;"></i>';

        } else {
          isTested = false;
          testCameraStatusIcon.style.display = "none";
          $("#testingError").text(
            "Url is correct but its not giving the image"
          );
        }
      }
    },
    error: function (xhr, status, error) {
      document.querySelector(
        "button[onclick='testLiveImageUrl()']"
      ).disabled = false;
      document.getElementById("loadingIndicator").style.display = "none";
      $("#testingError").text("Url is not correct");
      testCameraStatusIcon.style.display = "none";
      isTested = false;
    },
  });
}

function isBase64Image(base64String) {
  const imageStartRegex = /^\/9j|^iVBORw0KGgo|^R0lGODlh|^Qk/;
  const imageRegex =
    /^(data:image\/(png|jpeg|jpg|gif);base64,)?[A-Za-z0-9+/=]+$/;
  const isImage =
    imageStartRegex.test(base64String) || imageRegex.test(base64String);
  return isImage;
}

let debounceCameraTimer;
function searchCameraDevices() {
  clearTimeout(debounceCameraTimer);
  debounceCameraTimer = setTimeout(() => {
    const searchValue = document.getElementById("search_camera_value").value;
    let matchedCameras = allCameras.filter(
      (event) =>
        !searchValue ||
        Object.values(event).some(
          (field) =>
            field && field.toString().toLowerCase().includes(searchValue)
        )
    );
    createCameraCardView(matchedCameras);
  }, 170);
}


function viewModeOfCamera(cameraId) {
  const setting = allCameras.find(ele => ele.id == cameraId);
  // Populate fields with updated IDs for view mode
  document.getElementById("cameraNameView").value = setting.cameraName || "";
  document.getElementById("StreamingUrlView").value = setting.streamingUrl || "";
  document.getElementById("UsernameView").value = setting.userName || "";
  document.getElementById("PasswordView").value = setting.password || "";
  document.getElementById("cameraModelView").value = setting.cameraModel || "";
  document.getElementById("IPView").value = setting.IP || "";
  document.getElementById("RTSP_PORTView").value = setting.RTSP_PORT || "";
  document.getElementById("liveImagePortView").value = setting.liveImagePort || "";
  document.getElementById("liveImageUrlView").value = setting.liveImageURL || "";

  // Checkbox state
  $("#haveRTSPStreamingView").prop("checked", !!setting.RTSP_PORT);
  $("#haveFTPServerView").prop("checked", !!setting.ftp_host);
  isRTSPStreamingView();
  // if(setting.ftp_host){
  //   $("#haveFTPServerView").prop("checked", true);
  //   isFtpServerViewFunc(setting);
  // }else {
  //   document.getElementById("haveFTPServerView").checked = false;
  //   isFtpServerViewFunc();
  // }
  if (setting.ftp_host || setting.ftp_mode) {
    $("#haveFTPServerView").prop("checked", true);
    isFtpServerViewFunc(setting);
  } else {
    document.getElementById("haveFTPServerView").checked = false;
    isFtpServerViewFunc();
  }
  $('#viewSettingForm input, #viewSettingForm select, #viewSettingForm textarea').prop('disabled', true);
  $("#viewCameraModal").modal("show");
}


function isRTSPStreamingView() {
  const haveRTSPStreaming = document.getElementById("haveRTSPStreamingView").checked;
  if (haveRTSPStreaming) {
    $("#createRTSPUrlView").show();
  } else {
    $("#createRTSPUrlView").hide();
    document.getElementById("RTSP_PORTView").value = '';
    document.getElementById("StreamingUrlView").value = '';
  }
}

function toggleFtpInputsView() {
  const isCustom = document.getElementById("ftpCustomView").checked;
  $("#ftpCustomInputsView").toggle(isCustom);
}

// function isFtpServerViewFunc(bindingValues=null) {
//   let haveFTPServer = document.getElementById("haveFTPServerView").checked;
//   document.getElementById("camera_ftp_folderView").value = bindingValues?.camera_ftp_folder || '';
//   document.getElementById("ftp_hostView").value = bindingValues?.ftp_host || '';
//   document.getElementById("ftp_userView").value = bindingValues?.ftp_user || '';
//   document.getElementById("ftp_passwordView").value = bindingValues?.ftp_password || '';
//   document.getElementById("ftp_portView").value = bindingValues?.ftp_port || '';
//   if (haveFTPServer) {
//     $("#isFtpServerView").show();
//   } else {
//     $("#isFtpServerView").hide();
//   }
// }
function isFtpServerViewFunc(bindingValues = null) {
  const haveFTPServer = document.getElementById("haveFTPServerView").checked;
  const mode = bindingValues?.ftp_mode || "custom";

  $("#ftpOptionsView").toggle(haveFTPServer);
  if (haveFTPServer) {
    document.getElementById("ftpManagedView").checked = mode === "managed";
    document.getElementById("ftpCustomView").checked = mode === "custom";
    toggleFtpInputsView();
  }

  document.getElementById("camera_ftp_folderView").value = bindingValues?.camera_ftp_folder || '';
  document.getElementById("ftp_hostView").value = bindingValues?.ftp_host || '';
  document.getElementById("ftp_userView").value = bindingValues?.ftp_user || '';
  document.getElementById("ftp_passwordView").value = bindingValues?.ftp_password || '';
  document.getElementById("ftp_portView").value = bindingValues?.ftp_port || '';
}