function updateTime() {
  const now = new Date();
  let hours = now.getHours();
  const minutes = now.getMinutes().toString().padStart(2, "0");
  const seconds = now.getSeconds().toString().padStart(2, "0");  
  const timeFormat = singlePreference?.time_format

  if (timeFormat === "12h") {
    const period = hours >= 12 ? "PM" : "AM";
    hours = hours % 12 || 12; // Convert to 12-hour format
    document.getElementById(
      "current-time"
    ).textContent = `${hours}:${minutes}:${seconds} ${period}`;
  } else {
    hours = hours.toString().padStart(2, "0"); // Convert to 24-hour format
    document.getElementById(
      "current-time"
    ).textContent = `${hours}:${minutes}:${seconds}`;
  }
}

function navigateToTab(event, tab) {
  event.preventDefault(); // Prevent the default link click behavior
  const newUrl = `${window.location.origin}${window.location.pathname}?tab=${tab}`; // Construct the new URL with the tab parameter
  window.location.href = newUrl;
}

let singlePreference = null;
$(document).ready(async function () {
  try {
    const sessionPreferences = sessionStorage.getItem("preferences");
    if(sessionPreferences){
      const preferencesData = await parseJSONData(sessionPreferences);
      singlePreference = preferencesData;
    }else {
      const preferences = await asyncGetPreferencesRequest({
        get_preferences_for_property_user: true,
        property_id: sessionStorage.getItem("propertyId"),
      });
      if (preferences && preferences?.length > 0) {
        singlePreference = preferences[0];
        sessionStorage.setItem("preferences",JSON.stringify(singlePreference));
      } else singlePreference = null;
    }
    updateTime();
    setInterval(updateTime, 1000);
  } catch (error) {
    singlePreference = null;
  }
});

async function asyncGetPreferencesRequest(data) {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: "/include/preferences/set_preferences.php",
      type: "post",
      data,
      success: function (resp1) {
        resolve(resp1.data);
      },
      error: function (xhr, status, error) {
        console.log("error : ", error);
        reject(error);
      },
    });
  });
}
