let allPropertySettings = [];
let all_property_users = [];
let all_camera_permissions = [];
let all_cameras_for_permissions = [];
let default_permissions = [];
let isPropertySettingsCardView = false;
let propertySettingsDebounceTimer = null;

$(document).ready(async function () {
  const sessionPreferences = sessionStorage.getItem("preferences");
  if(sessionPreferences){
    const preferencesData = await parseJSONData(sessionPreferences);
    preferencesData?.is_card_view==1? isPropertySettingsCardView = true:isPropertySettingsCardView = 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) isPropertySettingsCardView = true;
  }
  window.scrollTo({
    top: 0,
    behavior: "smooth",
  });

  await asyncGetPropertyUsersRequest({
    get_property_users_request: true,
    property_id: sessionStorage.getItem("propertyId"),
  });

  send_property_settings_request({
    get_property_settings_request: true,
    property_id: sessionStorage.getItem("propertyId"),
  });

  send_property_settings_request({
    get_property_settings_doors_request: true,
    property_id: sessionStorage.getItem("propertyId"),
  });

  // ============= camera ===========
  send_property_settings_request({
    get_cameras_for_permissions: true,
    property_id: sessionStorage.getItem("propertyId"),
  });
  send_property_settings_request({
    get_permissions_for_cameras: true,
    property_id: sessionStorage.getItem("propertyId"),
  });
  // addSwitchPropertyCameraView();
  $(`#multi_camera_select`).select2({
    theme: "bootstrap4",
    placeholder: "Select input",
    allowClear: true,
  });
});

async function asyncGetPropertyUsersRequest(data) {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: "/include/property_builder/property_settings/property_settings_request.php",
      type: "post",
      data,
      success: function (resp) {
        populateUsersOptions(resp.data);
        all_property_users = resp.data;
        populateUsersOptionsForCamera(resp.data);
        resolve(resp.data);
      },
      error: function (xhr, status, error) {
        console.log("error : ", error);
        reject(error);
      },
    });
  });
}

function searchPropertySettings() {
  if(!isPropertySettingsCardView){
    searchTable('property_settings_data_table', 'searchPermissionInput');
    return;
  }
  clearTimeout(propertySettingsDebounceTimer);
  propertySettingsDebounceTimer = setTimeout(() => {
    const searchInput = document.getElementById("searchPermissionInput");
    if (!searchInput) {
      console.warn("Search input not found: searchPermissionInput");
      return;
    }
    
    const searchValue = searchInput.value.toLowerCase();
    
    let matchedSettings = allPropertySettings.filter(
      (setting) =>
        !searchValue ||
        Object.values(setting).some(
          (field) => field && field.toString().toLowerCase().includes(searchValue)
        )
    );
    
    // Re-render based on current view
    if (window.innerWidth <= 600 || isPropertySettingsCardView) {
      createPropertySettingsCardsPreview(matchedSettings);
    } else {
      createPropertySettingsTablePreview(matchedSettings);
    }
  }, 200);
}

function send_property_settings_request(data) {
  $.ajax({
    url: "/include/property_builder/property_settings/property_settings_request.php",
    type: "post",
    data,
    success: function (resp) {
      if (data?.get_property_settings_request) {
        allPropertySettings = resp.data;
        default_permissions = resp.default;
        
        const valid_users_permissions=get_valid_users_door_permissions(allPropertySettings)
        if (window.innerWidth <= 600){
          createPropertySettingsCardsPreview(valid_users_permissions);
        }else if(isPropertySettingsCardView) createPropertySettingsCardsPreview(valid_users_permissions);
        else createPropertySettingsTablePreview(valid_users_permissions);
      } else if (data?.get_property_settings_doors_request) {
        populateDoorOptions(resp.data);
      }else if (
        data?.save_property_settings ||
        data?.delete_property_setting ||
        data?.edit_property_settings
      ) {
        $("#setPermissionsModal").modal("hide");
        send_property_settings_request({
          get_property_settings_request: true,
          property_id: sessionStorage.getItem("propertyId"),
        });
      } else if (data?.get_cameras_for_permissions) {
        //===== camera permissions===
        all_cameras_for_permissions = resp?.data;
        populateCameraSelectBox(resp?.data);
      } else if (
        data?.add_permissions_for_cameras ||
        data?.delete_camera_permission ||
        data?.edit_permissions_for_cameras
      ) {
        send_property_settings_request({
          get_permissions_for_cameras: true,
          property_id: sessionStorage.getItem("propertyId"),
        });
        $("#setPermissionsForCameraModal").modal("hide");
      } else if (data?.get_permissions_for_cameras) {
        all_camera_permissions = resp;
        const valid_cameras_permissions_data = getPropertySettingsCameraData(all_camera_permissions?.data);
        if (window.innerWidth <= 600){
          createCameraPermissionsCardsPreview(valid_cameras_permissions_data,all_camera_permissions?.global_permissions);
        }else if(isPropertySettingsCardView) createCameraPermissionsCardsPreview(valid_cameras_permissions_data,all_camera_permissions?.global_permissions);
        else createCameraPermissionsTablePreview(valid_cameras_permissions_data,all_camera_permissions?.global_permissions);
        // changePropertyCameraView();
      } else if (data?.edit_global_permissions_for_cameras) {
        showSuccessGlobalToastMessage(resp?.message);
        send_property_settings_request({
          get_permissions_for_cameras: true,
          property_id: sessionStorage.getItem("propertyId"),
        });
        $("#setPermissionsForCameraModal").modal("hide");
      }
    },
    error: function (xhr, status, error, responseJSON) {
      console.log("xhr errror : ", xhr);
      if (xhr?.responseJSON?.error)
        show_settings_toast_message(xhr?.responseJSON?.error);
      else show_settings_toast_message(JSON.stringify(error));
    },
  });
}

function get_valid_users_door_permissions(data){
  let valid_users_door_permissions = [];
  all_property_users.forEach(user => {
    data?.forEach(permission => {      
      if(user?.email == permission?.user_email){
        valid_users_door_permissions.push(permission);
      }
    });
  });
  return valid_users_door_permissions;
}

function populateUsersOptions(users) {
  const user_select = document.getElementById("user_select_id");
  user_select.innerHTML = '<option value="" disabled>Select a user</option>';

  users.forEach((user) => {
    const option = document.createElement("option");
    option.value = user.id;
    option.textContent =
      user.firstname + " " + user.lastname + " (" + user.email + ")";
    option.dataset.userSource = user.user_source;
    user_select.appendChild(option);
  });
}

function populateDoorOptions(doors) {
  const doorSelect = document.getElementById("door_id");
  doorSelect.innerHTML = '<option value="" disabled>Select a Door</option>';

  doors.forEach((door) => {
    const option = document.createElement("option");
    option.value = door.hardware_setting_id;
    option.textContent = `${door.door_name} (${door?.device_model})`;
    doorSelect.appendChild(option);
  });
}

function createPropertyCommandsButtons(commands) {
  try {
    const decodedData = commands.replace(/&quot;/g, '"');
    let data = JSON.parse(decodedData);
    return data;
  } catch (error) {
    return "";
  }
}

function Commands_Buttons(commands) {
  let buttonsHtml = "";
  Object.keys(commands).forEach((command) => {
    if (commands[command] === true) {
      buttonsHtml += `<button class="btn btn-sm btn-primary mx-1">${command}</button>`;
    }
  });
  return buttonsHtml;
}

function Commands_Buttons_with_checks(commands) {
  let switchesHtml = "";
  switchesHtml += `<div class="d-flex align-items-center">`;
  Object.keys(commands).forEach((command) => {
    switchesHtml += `
    <div class="form-group mx-1">
      <input 
        type="checkbox" 
        class="custom-bootstrap-switch" 
        data-on-text="Yes" 
        data-off-text="No" 
        data-on-color="success" 
        data-size="mini"
        data-off-color="danger" 
        onchange="handle_individual_change('${command}')" 
        id="switch_${command}" 
        ${commands[command] ? "checked" : ""} 
        disabled
      >
      <label for="switch_${command}" style="font-size: 14px;">${command}</label>
    </div>
    `;
  });
  switchesHtml += `</div>`;
  return DOMPurify.sanitize(switchesHtml);
}

function filterTrueValues(commands) {
  const result = {};
  Object.keys(commands).forEach((key) => {
    if (commands[key] === true) {
      result[key] = commands[key];
    }
  });
  return result;
}

function createPropertySettingsCardsPreview(dataArray) {
  let data = dataArray;

  // Generate cards
  let html = `<div>`;

  // Global Permissions Section
  if(default_permissions){
    let trueCommands = createPropertyCommandsButtons(
      default_permissions?.actions_to_perform
    );
    let commandButtons = Commands_Buttons_with_checks(trueCommands);
    html += `
    <div class="card mb-4">
      <div class="card-header">
        <h5 class="mb-0"><i class="fa-solid fa-globe" style="padding-right: 5px;"></i> Global Default Permissions</h5>
      </div>
      <div class="card-body">
        <div class="d-flex justify-content-center w-100">
          <div class="card mb-3 mr-3">
            <div class="card-header">
              <div class="d-flex justify-content-between align-items-center">
                <span><i class="fa-solid fa-globe" style="padding-right: 5px;"></i> Global Default Permissions</span>
                <div>
                  <i class='fas fa-edit text-primary edit-global-permission-btn cursor_pointer' title='Edit Global Permissions'></i>
                </div>
              </div>
            </div>
            <div class="card-body">
              <p class="text-center mb-2">All new users and doors will have the permissions</p>
              <div class="d-flex flex-wrap justify-content-center">
                ${commandButtons}
                <p class="mx-2"> ${
                  default_permissions?.is_keep_open_to == 1
                    ? "<i class='fas fa-check-circle text-success' title='Can Keep Open'></i>"
                    : "<i class='fas fa-times-circle text-danger' title='Cannot Keep Open'></i>"
                } <label style="font-size: 14px;">Schedule</label>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    `;
  } else {
    // Show when no default permissions are found
    html += `
    <div class="card mb-4">
      <div class="card-header">
        <h5 class="mb-0"><i class="fa-solid fa-globe" style="padding-right: 5px;"></i> Global Default Permissions</h5>
      </div>
      <div class="card-body">
        <div class="text-center p-4">
          <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
          <h5 class="text-muted">No Defualt permission configured</h5>
          <p class="text-muted">New users and doors will only have basic Open command available.</p>
        </div>
      </div>
    </div>
    `;
  }

  // Individual Permissions Section
  html += `
    <div class="card mb-4">
      <div class="card-header">
        <h5 class="mb-0"><i class="fa-solid fa-users" style="padding-right: 5px;"></i> Individual User Permissions</h5>
      </div>
      <div class="card-body can_ban_view">
        <div class="row">
  `;

  // Clear the existing content
  $("#property_settings_table").empty();

  if (data.length === 0) {
    html += `
      <div class="col-12">
        <div class="text-center p-4">
          <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
          <h5 class="text-muted">No Individual Permissions Found</h5>
          <p class="text-muted">There are no individual permissions to display.</p>
        </div>
      </div>`;
  } else {
    data.forEach((item) => {
      let trueCommands = createPropertyCommandsButtons(item.actions_to_perform);
      let commandButtons = Commands_Buttons_with_checks(trueCommands);

      let permIcon = "";
      if (item?.is_individual === 0) {
        permIcon =
          '<i class="fa-solid fa-globe" title="Global Permission" style="padding-right: 5px;"></i>';
      } else {
        permIcon =
          '<i class="fa-regular fa-user" title="Individual Permission" style="padding-right: 5px;"></i>';
      }

      html += `
        <div class="col-12 col-lg-6 mb-3">
          <div class="card h-100 property_card">
            <div class="card-header">
              <div class="d-flex justify-content-between">
                <span class="text-break">${permIcon} ${
        item?.firstname || "N/A"
      } ${item?.lastname || "N/A"}</span>
                <div>
                  <i class='fas fa-edit text-primary edit-permission-btn cursor_pointer' data-id='${item.permission_id}'></i>
                  <i class='fas fa-trash-alt text-danger delete-permission-btn cursor_pointer' data-id='${item.permission_id}'></i>
                </div>
              </div>
            </div>
            <div class="card-body">
              <div class="d-flex flex-wrap justify-content-between mb-2">
                <div class="info_box mr-3">
                  <div class="title">Door:</div>
                  <div class="description"><span> ${
                    item.door_name || "N/A"
                  }</span>${
        item.device_model
          ? `<span  class=" text-secondary">(${item.device_model})</span>`
          : "" || ""
      }</div>
                </div>
                <div class="info_box">
                  <div class="title">Schedule:</div>
                  <div class="description">
                    ${
                      item?.is_keep_open_to == 1
                        ? "<i class='fas fa-check-circle text-success' title='Can add schedule'></i>"
                        : "<i class='fas fa-times-circle text-danger' title='Cannot add schedule'></i>"
                    }
                  </div>
                </div>
              </div>
              <div class="d-flex flex-wrap">
                ${commandButtons}
              </div>
            </div>
          </div>
        </div>`;
    });
  }

  html += `
        </div>
      </div>
    </div>
  `;

  html += `</div>`;

  // Insert the cards into the specified element
  $("#property_settings_table").html(DOMPurify.sanitize(html));
  bindPropertySettingsEvents();
  $(".custom-bootstrap-switch").bootstrapSwitch();
}

function bindPropertySettingsEvents() {
  const $container = $("#property_settings_table");
  $container.off("click", ".edit-permission-btn");
  $container.off("click", ".delete-permission-btn");
  $container.off("click", ".edit-global-permission-btn");

  $container.on("click", ".edit-permission-btn", function () {
    const id = $(this).data("id");
    editPermissionSetting(id);
  });

  $container.on("click", ".delete-permission-btn", function () {
    const id = $(this).data("id");
    deletePermissionSettingById(id);
  });

  $container.on("click", ".edit-global-permission-btn", function () {
    editPermissionSetting(null,true);
    $("#is_individual").prop("checked", false).trigger("change");
  });

}

function createPropertySettingsTablePreview(dataArray) {
  let data = dataArray;
  $("#door_command_table").empty();
  let html = "";
  if(default_permissions){
    let trueCommands = createPropertyCommandsButtons(
      default_permissions?.actions_to_perform
    );
    let commandButtons = Commands_Buttons_with_checks(trueCommands);
    html += `
    <div class="card-body">
              <p class="text-center mb-2">All new users and doors will have the permissions <i class='fas fa-edit text-primary edit-global-permission-btn cursor_pointer' title='Edit Global Permissions'></i></p>
              <div class="d-flex flex-wrap justify-content-center">
                ${commandButtons}
                <p class="mx-2"> ${
                  default_permissions?.is_keep_open_to == 1
                    ? "<i class='fas fa-check-circle text-success' title='Can Keep Open'></i>"
                    : "<i class='fas fa-times-circle text-danger' title='Cannot Keep Open'></i>"
                } <label style="font-size: 14px;">Schedule</label>
              </div>
            </div>
    `;
  } else {
    // Show when no default permissions are found in table view
    html += ` 
        <div class="text-center p-4">
          <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
          <h5 class="text-muted">No Defualt permission configured</h5>
          <p class="text-muted">New users and doors will only have basic Open command available.</p>
        </div>`;
  }
  html+= `
    <div class="table-responsive">
      <table id="property_settings_data_table" class="table table-bordered table-head-fixed text-nowrap table-hover" style="width:100%;">
        <thead>
          <tr>
            <th>User</th>
            <th>Door</th>
            <th>Schedule</th>
            <th>Commands</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
  `;

  if (data.length === 0) {
    html +=
      "<tr><td colspan='5' class='text-center'>No data available</td></tr>";
  } else {
    data.forEach(function (item) {
      let trueCommands = createPropertyCommandsButtons(item.actions_to_perform);
      let commandButtons = Commands_Buttons_with_checks(trueCommands);

      let permIcon = "";
      if (item?.is_individual === 0) {
        permIcon =
          '<i class="fa-solid fa-globe" title="Global Permission" style="padding-right: 5px;"></i>';
      } else {
        permIcon =
          '<i class="fa-regular fa-user" title="Individual Permission" style="padding-right: 5px;"></i>';
      }

      html += `
        <tr>
          <td>${permIcon} ${item?.firstname || "N/A"} ${
        item?.lastname || "N/A"
      }</td>
          <td>${item.door_name || ""}</td>
          <td> 
            <div class="d-flex align-items-center"> 
              <div>${
                item?.is_keep_open_to == 1 ? "Yes" : "No"
              }</div> <div class="description ml-2">
                  ${
                    item?.is_keep_open_to == 1
                      ? "<i class='fas fa-check-circle text-success' title='Can Keep Open'></i>"
                      : "<i class='fas fa-times-circle text-danger' title='Cannot Keep Open'></i>"
                  }
                </div>
              </div>
          </td>
          <td>
            <div class="d-flex"> ${commandButtons}</div>
          </td>
          <td style="vertical-align: middle;">
              <i class='fas fa-edit text-primary edit-permission-btn cursor_pointer' data-id='${item.permission_id}'></i>
              <i class='fas fa-trash-alt text-danger delete-permission-btn cursor_pointer' data-id='${item.permission_id}'></i>
            </td>
        </tr>
      `;
    });
  }

  html += `
        </tbody>
      </table>
    </div>
  `;

  // Insert the entire table structure into the specified element
  $("#property_settings_table").html(DOMPurify.sanitize(html));
  $(".custom-bootstrap-switch").bootstrapSwitch();
  bindPropertySettingsEvents();

  if (
    !$.fn.DataTable.isDataTable("#property_settings_data_table") &&
    data?.length
  ) {
    $("#property_settings_data_table").DataTable({
      "responsive": true,
      "order": [],
      "paging": true,
      "pageLength": 10,
      "searching": false,
    });
  } else if (data?.length > 0) {
    $("#property_settings_data_table").DataTable().order([]).draw();
  }
}

function deletePermissionSettingById(id) {
  const selected = allPropertySettings.find((ele) => ele.permission_id == id);
  showConfirmModal("Are you sure you want to delete?", function () {
    send_property_settings_request({
      id: selected?.permission_id,
      delete_property_setting: true,
    });
  });
}

function settingNewPermissions() {
  document.getElementById("property_settings_id").value = "";
  document.getElementById("user_select_id").value = "";
  document.getElementById("door_id").value = "";
  document.getElementById("release_command").checked = false;
  document.getElementById("open_command").checked = false;
  document.getElementById("hold_open_command").checked = false;
  document.getElementById("keep_open_to_command").checked = false;
  document.getElementById("is_individual_command").checked = true;
  
  // Hide global message when starting new permissions
  const globalMessageContainer = document.getElementById("global_config_message");
  if (globalMessageContainer) {
    globalMessageContainer.style.display = "none";
  }
  
  handle_individual_change();
}

function editPermissionSetting(id,isGlobal=false) {
  let selected = null;
  if(isGlobal)selected = default_permissions;
  else selected = allPropertySettings.find((ele) => ele.permission_id == id);
  let action_button_checks = createPropertyCommandsButtons(
    selected.actions_to_perform
  );
  if (selected) {
    document.getElementById("property_settings_id").value = id;
    document.getElementById("user_select_id").value = selected.user_id;
    document.getElementById("door_id").value = selected.door_id;
    document.getElementById("release_command").checked =
      action_button_checks?.Release;
    document.getElementById("open_command").checked =
      action_button_checks?.Open;
    document.getElementById("hold_open_command").checked =
      action_button_checks?.Holdopen;
    document.getElementById("keep_open_to_command").checked =
      selected?.is_keep_open_to;

    // Set the "Individual" toggle if needed
    document.getElementById("is_individual_command").checked =
      selected.is_individual;

    // Trigger the change event if necessary to show/hide individual fields
    handle_individual_change();

    $("#setPermissionsModal").modal("show");
  }
}

function handle_individual_change() {
  const isIndividual = document.getElementById("is_individual_command").checked;
  const individual_fields = document.getElementById("individual_fields");
  const globalMessageContainer = document.getElementById("global_config_message");
  const individualLabel = document.querySelector('label[for="is_individual_command"]');
  
  if (isIndividual) {
    individual_fields.style.display = "block";
    if (globalMessageContainer) {
      globalMessageContainer.style.display = "none";
    }
    if (individualLabel) {
      individualLabel.textContent = "Individual";
    }
  } else {
    individual_fields.style.display = "none";
    showGlobalConfigurationMessage();
    if (individualLabel) {
      individualLabel.textContent = "Default";
    }
  }
}

function showGlobalConfigurationMessage() {
  const globalMessageContainer = document.getElementById("global_config_message");
  if (globalMessageContainer) {
    globalMessageContainer.style.display = "block";
    globalMessageContainer.innerHTML = `
      <div class="alert alert-info alert-dismissible fade show" role="alert">
        <i class="fas fa-info-circle mr-2"></i>
        <strong>Global Configuration:</strong>These settings will apply to all new users and doors by default. Individual permissions can still be set for specific users.
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
    `;
  }
  let default_actions_to_perform = createPropertyCommandsButtons(
    default_permissions.actions_to_perform
  );
  document.getElementById("release_command").checked = default_actions_to_perform?.Release;
  document.getElementById("open_command").checked = default_actions_to_perform?.Open;
  document.getElementById("hold_open_command").checked = default_actions_to_perform?.Holdopen;
  document.getElementById("keep_open_to_command").checked = default_permissions?.is_keep_open_to;
}

function getFormValues() {
  const isIndividual = document.getElementById("is_individual_command").checked;
  const userSelect = document.getElementById("user_select_id");
  const user_id = userSelect ? userSelect.value : null;
  const doorSelect = document.getElementById("door_id");
  const door_id = doorSelect ? doorSelect.value : null;
  const Release = document.getElementById("release_command").checked;
  const Open = document.getElementById("open_command").checked;
  const Holdopen = document.getElementById("hold_open_command").checked;
  const is_keep_open_to = document.getElementById(
    "keep_open_to_command"
  ).checked;
  const id_to_update = document.getElementById("property_settings_id")?.value;
  if (!sessionStorage.getItem("propertyId")) {
    show_settings_toast_message(
      "Property is missing. Please select it from left menu at the bottom"
    );
    return;
  }

  if (isIndividual) {
    if (!door_id) {
      console.log("door is required");
      show_settings_toast_message("door is required", 3000);
      return;
    }
    if (!user_id) {
      console.log("user_id is required");
      show_settings_toast_message("user is required", 3000);
      return;
    }
  }

  const user_type =
    userSelect.options[userSelect.selectedIndex]?.dataset.userSource ||
    "property_user";

  let formData = {};
  if (!isIndividual) {
    formData = {
      is_individual: 0,
      actions_to_perform: JSON.stringify({
        Release,
        Open,
        Holdopen,
      }),
      is_keep_open_to: is_keep_open_to ? 1 : 0,
      save_property_settings: true,
      property_id: sessionStorage.getItem("propertyId"),
    };
  } else {
    const user_email = all_property_users.find((ele) => ele.id == user_id)?.email;
    formData = {
      is_individual: 1,
      user_id,
      user_email,
      door_id,
      user_type,
      actions_to_perform: JSON.stringify({
        Release,
        Open,
        Holdopen,
      }),
      is_keep_open_to: is_keep_open_to ? 1 : 0,
      property_id: sessionStorage.getItem("propertyId"),
    };
  }
  if (id_to_update) {
    formData["edit_property_settings"] = true;
    formData["id"] = id_to_update;
  } else formData["save_property_settings"] = true;
  send_property_settings_request(formData);
}

function show_settings_toast_message(errorMessage, delayTime = 5000) {
  document.getElementById("settingsToastMessage").style.display = "block";
  document.getElementById("settingsErrorToast").innerHTML = errorMessage;
  var toastEl = document.getElementById("property_settings_Toast");
  var toast = new bootstrap.Toast(toastEl, {
    delay: delayTime,
    autohide: false,
  });
  toast.show();

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

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

// ===========================Camera permissions======================

function settingNewPermissionsForCamera() {
  document.getElementById("user_id_camera").value = "";
  document.getElementById("camera_id_for_permission").value = "";
  document.getElementById("property_camera_permissions_id").value = "";
  document.getElementById("multi_camera_select").value = "";
  document.getElementById("is_individual_camera").checked = true;
  document.getElementById("property_global_camera_permissions_id").value = "";
  handle_individual_camera_change();
}

function handle_individual_camera_change() {
  const isIndividual = document.getElementById("is_individual_camera").checked;
  const individual_fields = document.getElementById("individual_fields_camera");
  const global_camera_permissions = document.getElementById(
    "global_camera_permissions"
  );
  if (isIndividual) {
    global_camera_permissions.style.display = "none";
    individual_fields.style.display = "block";
  } else {
    global_camera_permissions.style.display = "flex";
    individual_fields.style.display = "none";
  }
}

function populateCameraSelectBox(allCameras) {
  const camera_id_for_permission = document.getElementById(
    "camera_id_for_permission"
  );
  camera_id_for_permission.innerHTML =
    '<option value="" selected disabled>Select a camera</option>';
  allCameras.forEach((camera) => {
    const option = document.createElement("option");
    option.value = camera.id;
    option.textContent = camera.cameraName + "(" + camera.cameraModel + ")";
    camera_id_for_permission.appendChild(option);
  });

  // ===========multi============
  const multi_camera_select = document.getElementById("multi_camera_select");
  multi_camera_select.innerHTML = "";

  allCameras.forEach((camera) => {
    const option = document.createElement("option");
    option.value = camera.id;
    option.textContent = camera.cameraName + "(" + camera.cameraModel + ")";
    multi_camera_select.appendChild(option);
  });
}

function populateUsersOptionsForCamera(users) {
  const user_id_camera = document.getElementById("user_id_camera");
  user_id_camera.innerHTML = '<option value="" disabled>Select a user</option>';
  users.forEach((user) => {
    const option = document.createElement("option");
    option.value = user.id;
    option.textContent =
      user.firstname + " " + user.lastname + " (" + user.email + ")";
    option.dataset.userSource = user.user_source;
    user_id_camera.appendChild(option);
  });
}

function setPermissionsForCamera() {
  const user_id_camera = document.getElementById("user_id_camera").value;
  const camera_id_for_permission = document.getElementById(
    "camera_id_for_permission"
  ).value;
  const property_global_camera_permissions_id = document.getElementById(
    "property_global_camera_permissions_id"
  ).value;
  const dataId = document.getElementById(
    "property_camera_permissions_id"
  ).value;
  const multi_camera_select = $("#multi_camera_select").val();

  const property_id = sessionStorage.getItem("propertyId");
  const isIndividual = document.getElementById("is_individual_camera").checked;
  const view_permission = document.getElementById("view_permission").checked;

  if (isIndividual) {
    const property_user = all_property_users.find(
      (ele) => ele.id == user_id_camera
    );

    if (!property_user) {
      show_settings_toast_message("user is required");
      return;
    }

    if (!camera_id_for_permission) {
      show_settings_toast_message("Camera is required");
      return;
    }
    const payload = {
      isIndividual,
      property_id,
      property_user_id: user_id_camera,
      camera_id: camera_id_for_permission,
      property_user_email: property_user?.email,
      property_user_name:
        property_user?.firstname + " " + property_user?.lastname,
      have_view_permission: view_permission ? 1 : 0,
    };
    if (dataId) {
      payload["edit_permissions_for_cameras"] = true;
      payload["id"] = dataId;
    } else {
      payload["add_permissions_for_cameras"] = true;
    }
    send_property_settings_request(payload);
  } else {
    if (!multi_camera_select?.length) {
      show_settings_toast_message("Please select camera for permissions");
      return;
    }
    const payload = {
      camera_ids: JSON.stringify(multi_camera_select),
      isIndividual: false,
      property_id,
    };
    if (property_global_camera_permissions_id) {
      payload["edit_global_permissions_for_cameras"] = true;
      payload["id"] = property_global_camera_permissions_id;
    } else payload["add_permissions_for_cameras"] = true;
    send_property_settings_request(payload);
  }
}

function editCameraPermissionSetting(id) {
  const selected = all_camera_permissions?.data?.find((ele) => ele.id == id);
  if (selected) {
    document.getElementById("user_id_camera").value =
      selected?.property_user_id || "";
    document.getElementById("camera_id_for_permission").value =
      selected?.camera_id || "";
    document.getElementById("property_camera_permissions_id").value =
      selected?.id;
    document.getElementById("view_permission").checked =
      selected?.have_view_permission == 1 ? true : false;
    document.getElementById("is_individual_camera").checked = true;
  }
  $("#setPermissionsForCameraModal").modal("show");
  handle_individual_camera_change();
}

function createCameraPermissionsCardsPreview(data, global_perms = null) {
  $("#property_camera_permissions_table").empty();
  $("#global_permission_container").empty();

  if (global_perms?.cameras && global_perms?.cameras?.length) {
    const cameraNames = global_perms.cameras.map((c) => c?.cameraName);
    const message = `All new users will have view permissions for: ( ${cameraNames.join(", ")} )`;
    
    $("#global_permission_container").html( DOMPurify.sanitize(`
      <div class="d-flex justify-content-center align-items-center">
        <p class="text-center text-bold mb-0">${message}</p>
        <div class="pl-2">
          <i class="fas fa-edit text-primary mx-1 cursor_pointer global_edit_permission" ></i>
        </div>
      </div>
    `));
    bindPropertySettingsCameraGlobalEvents();
  }
  // Generate cards
  let html = `<div class="mt-2" style="display: flex; flex-wrap: wrap; gap:20px">`;

  if (data.length === 0) {
    html += `
        <div class="card" style="display:flex; justify-content:center; align-items:center; width:100%;">
          <div class="text-center p-4">
            <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
            <h5 class="text-muted">No Individual Camera Permissions Found</h5>
            <p class="text-muted">There are no individual camera permissions to display.</p>
          </div>
        </div>`;
  } else {
    data.forEach((item) => {
      let permIcon = `<i class="fa-regular fa-user" title="Individual Permission" style="padding-right: 5px;"></i>`;
      html += `
        <div class="card" style="width: 31%;margin-bottom: 0px;">
          <div class="card-header">
            <div class="d-flex justify-content-between">
              <span class="text-break">${permIcon} ${
        item?.property_user_name || "N/A"
      }</span>
              <div>
                <i class='fas fa-edit text-primary camera-edit-btn cursor_pointer' data-id='${item.id}'></i>
                <i class='fas fa-trash-alt text-danger camera-delete-btn cursor_pointer' data-id='${item.id}'></i>
              </div>
            </div>
          </div>
          <div class="card-body">
            <div class="d-flex flex-wrap justify-content-between mb-2">
              <div class="info_box mr-3">
                <div class="title">Camera:</div>
                <div class="description"><span> ${
                  item?.camera_data?.cameraName || "N/A"
                }</span>${
        item?.camera_data?.cameraModel
          ? `<span  class=" text-secondary">(${item?.camera_data?.cameraModel})</span>`
          : "" || ""
      }</div>
              </div>
              <div class="info_box">
                <div class="title">can view:</div>
                <div class="description">
                  ${
                    item?.have_view_permission == 1
                      ? "<i class='fas fa-check-circle text-success' title='Can add schedule'></i>"
                      : "<i class='fas fa-times-circle text-danger' title='Cannot add schedule'></i>"
                  }
                </div>
              </div>
            </div>
          </div>
        </div>`;
    });
  }

  html += `</div>`;

  // Insert the cards into the specified element
  $("#property_camera_permissions_table").html(DOMPurify.sanitize(html));
  bindPropertySettingsCameraEvents();
  $(".custom-bootstrap-switch").bootstrapSwitch();
}

function createCameraPermissionsTablePreview(data, global_perms = null) {
  $("#property_camera_permissions_table").empty();
  $("#global_permission_container").empty();

  if (global_perms?.cameras && global_perms?.cameras?.length) {
    const cameraNames = global_perms.cameras.map((c) => c?.cameraName);
    const message = `All new users will have view permissions for: ( ${cameraNames.join(
      ", "
    )} )`;

    $("#global_permission_container").html( DOMPurify.sanitize(`
        <div class="d-flex justify-content-center align-items-center">
          <p class="text-center text-bold mb-0">${message}</p>
          <div class="pl-2">
            <i class="fas fa-edit text-primary mx-1 cursor_pointer global_edit_permission" ></i>
          </div>
        </div>
      `));
      bindPropertySettingsCameraGlobalEvents();
  }
  let html = `
    <div class="table-responsive p-0">
      <table id="property_settings_camera_table" class="table table-bordered table-head-fixed text-nowrap table-hover">
        <thead>
          <tr>
            <th>User</th>
            <th>Camera</th>
            <th>permission</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
  `;

  if (data.length === 0) {
    html +=
      "<tr><td colspan='4' class='text-center'>No data available</td></tr>";
  } else {
    data.forEach(function (item) {
      let permIcon = `<i class="fa-regular fa-user" title="Individual Permission" style="padding-right: 5px;"></i>`;
      html += `
        <tr>
          <td>${permIcon} ${item?.property_user_name || "N/A"}</td>
          <td>${item?.camera_data?.cameraName || "N/A"} ( ${
        item?.camera_data?.cameraModel || "N/A"
      } )</td>
          <td> 
            ${
              item?.have_view_permission == 1
                ? `<i class='fas fa-check-circle text-success'></i>`
                : `<i class='fas fa-times-circle text-danger' title='Cannot add'></i>`
            }
          </td>
          <td style="vertical-align: middle;">
              <i class='fas fa-edit text-primary camera-edit-btn cursor_pointer' data-id='${item.id}'></i>
              <i class='fas fa-trash-alt text-danger camera-delete-btn cursor_pointer' data-id='${item.id}'></i>
          </td>
        </tr>
      `;
    });
  }

  html += `
        </tbody>
      </table>
    </div>
  `;

  // Insert the HTML
  $("#property_camera_permissions_table").html(DOMPurify.sanitize(html));
  bindPropertySettingsCameraEvents();
  if (
    !$.fn.DataTable.isDataTable("#property_settings_camera_table") &&
    data?.length
  ) {
    // new DataTable('#command_center_complete_data_table');
    $("#property_settings_camera_table").DataTable({
      "responsive": true,
      "order": [],
      "paging": true,
      "pageLength": 10,
      // "lengthMenu": [ [10, 25, 50, 100], [10, 25, 50, 100] ],
      "searching": false,
    });
  } else if (data?.length > 0) {
    $("#property_settings_camera_table").DataTable().order([]).draw();
  }
}


function bindPropertySettingsCameraGlobalEvents() {
  const $container = $("#global_permission_container");
  $container.off("click", ".global_edit_permission");
  $container.on("click", ".global_edit_permission", function () {
    editGlobalCameraPermission()
  });
}

function bindPropertySettingsCameraEvents() {
  const $container = $("#property_camera_permissions_table");
  $container.off("click", ".camera-edit-btn");
  $container.off("click", ".camera-delete-btn");

  $container.on("click", ".camera-edit-btn", function () {
    const id = $(this).data("id");
    editCameraPermissionSetting(id);
  });

  $container.on("click", ".camera-delete-btn", function () {
    const id = $(this).data("id");
    deleteCameraPermissionById(id);
  });

}

async function editGlobalCameraPermission() {
  const selected = await property_settings_request({
    get_global_camera_properties: true,
  });
  if (selected) {
    document.getElementById("is_individual_camera").checked = false;
    document.getElementById("property_global_camera_permissions_id").value =
      selected.id;
    const multi_camera_select = document.getElementById("multi_camera_select");
    multi_camera_select.innerHTML = "";
    all_cameras_for_permissions?.forEach((item) => {
      const inputOption = document.createElement("option");
      inputOption.value = item?.id;
      inputOption.textContent = item.cameraName + "(" + item.cameraModel + ")";
      if (selected.camera_ids.includes(item?.id)) {
        inputOption.selected = true;
      }
      multi_camera_select.appendChild(inputOption);
    });
  }
  $("#setPermissionsForCameraModal").modal("show");
  handle_individual_camera_change();
}

async function deleteGlobalCameraPermission() {
  try {
    const resp = await property_settings_request({
      delete_global_camera_properties: true,
    });
    showSuccessGlobalToastMessage("Data has deleted successfully");
    send_property_settings_request({
      get_permissions_for_cameras: true,
      property_id: sessionStorage.getItem("propertyId"),
    });
  } catch (error) {
    show_settings_toast_message(error || "Got error in deleting ");
  }
}

async function property_settings_request(data) {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: "/include/property_builder/property_settings/property_settings_request.php",
      type: "POST",
      data,
      success: function (resp) {
        try {
          resolve(resp.data);
        } catch (error) {
          console.error("Error parsing response data: ", error);
          reject(error);
        }
      },
      error: function (xhr, status, error) {
        if (xhr?.responseJSON?.error) reject(xhr?.responseJSON?.error);
        else reject(error);
      },
    });
  });
}

function deleteCameraPermissionById(id) {
  showConfirmModal("Are you sure you want to delete?", function () {
    send_property_settings_request({ id, delete_camera_permission: true });
  });
}

function refreshCameraTable() {
  if ($.fn.DataTable.isDataTable("#property_settings_camera_table")) {
    const table = $("#property_settings_camera_table").DataTable();
    table.draw();
  }
}

// Call this when tab changes
$('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
  if ($(e.target).attr("href") === "#cameras") {
    refreshCameraTable();
  }
});


function getPropertySettingsCameraData(data){
  if(!data) return;
  const camera_permissions_table = document.getElementById("property_camera_permissions_table");
  camera_permissions_table.innerHTML = "";

  let valid_cameras_permissions = [];
  all_property_users.forEach(user => {
    data?.forEach(camera_permission => {
      if(user?.email == camera_permission?.property_user_email){
        valid_cameras_permissions.push(camera_permission);
      }
    });
  });
  return valid_cameras_permissions;

}