<script>
import { ref, onMounted, onUnmounted, computed } from "vue";
import ApiServiece from "@/services/ApiService";
import { useRouter } from "vue-router";
import { ChevronDownIcon } from "@zhuowenli/vue-feather-icons";
import simplebar from "simplebar-vue";
import logoWhite from "@/assets/images/logo-white.svg";
import logoDark from "@/assets/images/logo-dark.svg";
import { useStore } from "vuex";
import Swal from "sweetalert2";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
export default {
  data() {
    return {
      logoDark: logoDark,
      logoWhite: logoWhite,
    };
  },
  setup() {
    const settings = ref()
    const logo = ref()
    const router = useRouter();
    const currentLogo = ref(logoDark);
    const store = useStore();
    const user = computed(() => store.getters["user/getUser"]);
    const updateLogo = () => {
      const isDarkTheme =
        document.body.getAttribute("data-pc-theme") === "dark";
      currentLogo.value = isDarkTheme ? logoWhite : logoDark;
    };

    const logoutUser = async () => {
      try {
        const result = await Swal.fire({
          text: "شما از سیستم خارج خواهید شد.",
          icon: "warning",
          showCancelButton: true,
          confirmButtonColor: "#3085d6",
          cancelButtonColor: "#d33",
          confirmButtonText: "بله، خارج شوم",
          cancelButtonText: "خیر، باقی بمانم",
        });
        if (result.isConfirmed) {
          await store.dispatch("user/logout");

          router.push({ name: "otpLogin" });
          console.log("User logged out successfully.");
        }
      } catch (error) {
        console.error("Error logging out:", error);
        toast.error("خطا", "مشکلی در فرآیند خروج به وجود آمد.");
      }
    };

    const gotoAccount = () => {
      router.push({ name: "profile" });
      console.log("asdasd");
    };

    const getSettings = async () => {
      const localLogo = localStorage.getItem("logo")
      if(localLogo){
        logo.value = localLogo;
      }
      else {
        try {
        const response = await ApiServiece.get("settings/logo_fav");
        settings.value = response.data.data;
        logo.value = settings.value.value;
        localStorage.setItem("logo" , logo.value)
      } catch (error) {
        console.error("Error fetching settings:", error);
      }
      }
     
    };
    onMounted(() => {
      updateLogo();
      getSettings();
      const observer = new MutationObserver(() => {
        updateLogo();
      });

      observer.observe(document.body, {
        attributes: true,
        attributeFilter: ["data-pc-theme"],
      });

      onUnmounted(() => {
        observer.disconnect();
      });
    });

    return { currentLogo, user, logoutUser, gotoAccount , logo , settings };
  },
  components: {
    ChevronDownIcon,
    simplebar,
  },
  methods: {
    changeLayoutType(layoutType) {
      // Update the layout type in the store
      this.$store.commit("changeLayoutType", { layoutType });
      // Set the layout attribute based on the layout type
      document.body.setAttribute("data-pc-layout", layoutType);
    },
  },
  computed: {
    layoutType: {
      get() {
        return this.$store.state.layout.layoutType;
      },
      set(layoutType) {
        this.$store.commit("changeLayoutType", { layoutType });
      },
    },
  },
  watch: {
    layoutType: {
      immediate: true,
      deep: true,
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          switch (newVal) {
            case "horizontal":
              document.body.setAttribute("data-pc-layout", "horizontal");
              break;
            case "vertical":
              document.body.setAttribute("data-pc-layout", "vertical");
          }
        }
      },
    },
  },
  mounted() {
    const activeListItem = document.querySelector("li.active");
    if (activeListItem) {
      const parentElementOrSelf = activeListItem?.parentElement
        ? activeListItem.parentElement
        : activeListItem;
      if (
        parentElementOrSelf &&
        !parentElementOrSelf.classList.contains("pc-navbar")
      ) {
        const closestItem =
          parentElementOrSelf.parentElement.closest(".pc-item");
        if (closestItem) {
          closestItem.classList.add("active");
          closestItem.children[1].classList.add("show");
        }
      }

      /**
       * Sidebar menu collapse
       */
      if (document.querySelectorAll(".navbar-content .collapse")) {
        let collapses = document.querySelectorAll(".navbar-content .collapse");

        collapses.forEach((collapse) => {
          collapse.addEventListener("show.bs.collapse", (e) => {
            e.stopPropagation();
            let closestCollapse = collapse.parentElement.closest(".collapse");
            if (closestCollapse) {
              let siblingCollapses =
                closestCollapse.querySelectorAll(".collapse");
              siblingCollapses.forEach((siblingCollapse) => {
                if (siblingCollapse.classList.contains("show")) {
                  siblingCollapse.classList.remove("show");
                  siblingCollapse.parentElement.firstChild.setAttribute(
                    "aria-expanded",
                    "false"
                  );
                }
              });
            } else {
              let getSiblings = (elem) => {
                // Setup siblings array and get the first sibling
                let siblings = [];
                let sibling = elem.parentNode.firstChild;
                // Loop through each sibling and push to the array
                while (sibling) {
                  if (sibling.nodeType === 1 && sibling !== elem) {
                    siblings.push(sibling);
                  }
                  sibling = sibling.nextSibling;
                }
                return siblings;
              };
              let siblings = getSiblings(collapse.parentElement);
              siblings.forEach((item) => {
                if (item.childNodes.length > 2) {
                  item.firstElementChild.setAttribute("aria-expanded", "false");
                  item.firstElementChild.classList.remove("active");
                }
                let ids = item.querySelectorAll("*[id]");
                ids.forEach((item1) => {
                  item1.classList.remove("show");
                  item1.parentElement.firstChild.setAttribute(
                    "aria-expanded",
                    "false"
                  );
                  item1.parentElement.firstChild.classList.remove("active");
                  if (item1.childNodes.length > 2) {
                    let val = item1.querySelectorAll("ul li a");

                    val.forEach((subitem) => {
                      if (subitem.hasAttribute("aria-expanded"))
                        subitem.setAttribute("aria-expanded", "false");
                    });
                  }
                });
              });
            }
          });

          // Hide nested collapses on `hide.bs.collapse`
          collapse.addEventListener("hide.bs.collapse", (e) => {
            e.stopPropagation();
            let childCollapses = collapse.querySelectorAll(".collapse");
            childCollapses.forEach((childCollapse) => {
              let childCollapseInstance = childCollapse;
              childCollapseInstance.classList.remove("show");
              childCollapseInstance.parentElement.firstChild.setAttribute(
                "aria-expanded",
                "false"
              );
            });
          });
        });
      }
    } else {
      console.error("No list item with class 'active' found.");
    }
  },
};

</script>

<template>
  <div class="navbar-wrapper" id="navbar-wrapper">
    <div class="m-header">
  <!-- ========   Change your logo from here   ============ -->
  <img
    v-if="currentLogo === logoDark"
    :src="logo"
    alt="logo image"
    class="logo-img"
  />
  <img
    v-else
    :src="logo"
    alt="logo image"
    class="logo-img"
  />
</div>
    <simplebar data-simplebar class="navbar-content pc-trigger">
      <ul class="pc-navbar">
        <li class="pc-item" :class="{ active: this.$route.path === '/users' }">
          <router-link to="/users" class="pc-link">
            <span class="pc-micon">
              <i class="ph-duotone ph-user-circle"></i>
            </span>
            <span class="pc-mtext">کاربران</span></router-link
          >
        </li>
        <li
          class="pc-item"
          :class="{
            active:
              this.$route.path === '/banners' ||
              this.$route.path === '/addBanner' ||
              this.$route.name === 'editBanner',
          }"
        >
          <router-link to="/banners" class="pc-link">
            <span class="pc-micon">
              <i class="ph-duotone ph-flag"></i>
            </span>
            <span class="pc-mtext">بنر ها</span></router-link
          >
        </li>
        <li class="pc-item" :class="{ active: this.$route.path === '/brands' }">
          <router-link to="/brands" class="pc-link">
            <span class="pc-micon">
              <i class="ph-duotone ph-briefcase"></i>
            </span>
            <span class="pc-mtext">برند ها</span></router-link
          >
        </li>

        <li
          class="pc-item"
          :class="{ active: this.$route.path === '/attributes' }"
        >
          <router-link to="/attributes" class="pc-link">
            <span class="pc-micon">
              <i class="ph-duotone ph-star"></i>
            </span>
            <span class="pc-mtext">ویژگی ها</span></router-link
          >
        </li>
        <li
          class="pc-item"
          :class="{ active: this.$route.path === '/idenities' }"
        >
          <router-link to="/idenities" class="pc-link">
            <span class="pc-micon">
              <i class="ph-duotone ph-barcode"></i>
            </span>
            <span class="pc-mtext">مشخصات</span></router-link
          >
        </li>
        <li
          class="pc-item"
          :class="{
            active:
              this.$route.path === '/blogs' ||
              this.$route.path === '/addBlog' ||
              this.$route.name === 'editBlog',
          }"
        >
          <router-link to="/blogs" class="pc-link">
            <span class="pc-micon">
              <i class="ph-duotone ph-pencil"></i>
            </span>
            <span class="pc-mtext">بلاگ ها</span></router-link
          >
        </li>
        <li
          class="pc-item"
          :class="{
            active:
              this.$route.path === '/products' ||
              this.$route.path === '/addProduct' ||
              this.$route.name === 'editProduct',
          }"
        >
          <router-link to="/products" class="pc-link">
            <span class="pc-micon">
              <i class="ph-duotone ph-bag"></i>
            </span>
            <span class="pc-mtext">محصولات</span></router-link
          >
        </li>
        <li
          class="pc-item"
          :class="{
            active:
              this.$route.path === '/discounts' ||
              this.$route.path === '/addDiscount' ||
              this.$route.name === 'editDiscount',
          }"
        >
          <router-link to="/discounts" class="pc-link">
            <span class="pc-micon">
              <i class="ph-duotone ph-tag"></i>
            </span>
            <span class="pc-mtext">تخفیف ها</span></router-link
          >
        </li>

        <!-- سفاراشات -->
        <li class="pc-item pc-hasmenu">
          <BLink
            class="pc-link"
            data-bs-toggle="collapse"
            href="#collapse-orders"
            role="button"
            aria-expanded="false"
            aria-controls="collapse-orders"
          >
            <span class="pc-micon">
              <i class="ph-duotone ph-shopping-cart"></i>
            </span>
            <span class="pc-mtext">سفارشات</span>
            <span class="pc-arrow">
              <ChevronDownIcon></ChevronDownIcon>
            </span>
          </BLink>
          <div class="collapse" id="collapse-orders">
            <ul class="pc-submenu">
              <li
                class="pc-item"
                :class="{
                  active:
                    this.$route.path === '/orders' ||
                    this.$route.name === 'singleOrder',
                }"
              >
                <router-link to="/orders" class="pc-link">
                  <span class="pc-mtext">سفارشات</span></router-link
                >
              </li>
              <li
                class="pc-item"
                :class="{ active: this.$route.path === '/approvedOrders' }"
              >
                <router-link to="/approvedOrders" class="pc-link">
                  <span class="pc-mtext">آیتم های تایید شده</span></router-link
                >
              </li>
            </ul>
          </div>
        </li>

        <!-- دسته ها -->
        <!-- <li class="pc-item pc-hasmenu">
          <BLink
            class="pc-link"
            data-bs-toggle="collapse"
            href="#collapse-categories"
            role="button"
            aria-expanded="false"
            aria-controls="collapse-categories"
          >
            <span class="pc-micon">
              <i class="ph-duotone ph-folder"></i>
            </span>
            <span class="pc-mtext">دسته ها</span>
            <span class="pc-arrow">
              <ChevronDownIcon></ChevronDownIcon>
            </span>
          </BLink>
          <div class="collapse" id="collapse-categories">
            <ul class="pc-submenu">
              <li
                class="pc-item"
                :class="{ active: this.$route.path === '/cats' }"
              >
                <router-link to="/cats" class="pc-link">
                  <span class="pc-mtext">دسته محصولات</span></router-link
                >
              </li>
              <li
                class="pc-item"
                :class="{ active: this.$route.path === '/blogCat' }"
              >
                <router-link to="/blogCat" class="pc-link">
                  <span class="pc-mtext">دسته بلاگ</span></router-link
                >
              </li>
            </ul>
          </div>
        </li> -->

        <li
          class="pc-item"
          :class="{ active: this.$route.path === '/comments' }"
        >
          <router-link to="/comments" class="pc-link">
            <span class="pc-micon">
              <i class="ph-duotone ph-chat"></i>
            </span>
            <span class="pc-mtext">نظرات</span></router-link
          >
        </li>
        <li
          class="pc-item"
          :class="{
            active:
              this.$route.path === '/faqs' || this.$route.name === 'editFaqs',
          }"
        >
          <router-link to="/faqs" class="pc-link">
            <span class="pc-micon">
              <i class="ph-duotone ph-file-text"></i>
            </span>
            <span class="pc-mtext">پرسش و پاسخ</span></router-link
          >
        </li>
        <li class="pc-item pc-hasmenu">
          <BLink
            class="pc-link"
            data-bs-toggle="collapse"
            href="#collapse26"
            role="button"
            aria-expanded="false"
            aria-controls="collapse26"
          >
            <span class="pc-micon">
              <i class="ph-duotone ph-folder"></i>
            </span>
            <span class="pc-mtext">دسته ها</span
            ><span class="pc-arrow">
              <ChevronDownIcon></ChevronDownIcon>
            </span>
          </BLink>
          <div class="collapse" id="collapse26">
            <ul class="pc-submenu">
              <li
                class="pc-item"
                :class="{ active: this.$route.path === '/cats' }"
              >
                <router-link to="/cats" class="pc-link">
                  <span class="pc-mtext">دسته محصولات</span></router-link
                >
              </li>
              <li
                class="pc-item"
                :class="{ active: this.$route.path === '/blogCat' }"
              >
                <router-link to="/blogCat" class="pc-link">
                  <span class="pc-mtext">دسته بلاگ</span></router-link
                >
              </li>
            </ul>
          </div>
        </li>

        <li class="pc-item" :class="{ active: this.$route.path === '/calls' }">
          <router-link to="/calls" class="pc-link">
            <span class="pc-micon">
              <i class="ph-duotone ph-clock"></i>
            </span>
            <span class="pc-mtext">برسی فرم ها</span></router-link
          >
        </li>

        <li class="pc-item" :class="{ active: this.$route.path === '/settings' }">
          <router-link to="/settings" class="pc-link">
            <span class="pc-micon">
              <i class="ph-duotone ph-gear"></i>
            </span>
            <span class="pc-mtext">تنظیمات</span></router-link
          >
        </li>

        <!-- other -->
      </ul>
    </simplebar>
    <BCard no-body class="pc-user-card">
      <BCardBody>
        <div class="d-flex align-items-center">
          <div class="flex-shrink-0">
            <img
              src="@/assets/images/user/avatar-1.jpg"
              alt="user-image"
              class="user-avtar wid-45 rounded-circle"
            />
          </div>
          <div class="flex-grow-1 ms-3 me-2">
            <h6 class="mb-0">{{ user?.name }}</h6>
            <small v-if="user?.role === `admin`">مدیر</small>
            <small v-if="user?.role === `client`">مشتری</small>
          </div>
          <BDropdown variant="purple" dropup no-caret toggle-class="p-0">
            <template v-slot:button-content>
              <span
                class="btn btn-icon btn-link-secondary avtar arrow-none p-0 dropdown-toggle"
              >
                <i class="ph-duotone ph-windows-logo"></i>
              </span>
            </template>
            <BRow xl="6">
              <BCol @click="gotoAccount()" xl="6">
                <BDropdownItem class="pc-user-links p-0">
                  <i class="ph-duotone ph-user"></i>
                  <br />
                  <span>حساب من</span>
                </BDropdownItem>
              </BCol>
              <BCol @click="logoutUser" xl="6">
                <BDropdownItem class="pc-user-links p-0">
                  <i class="ph-duotone ph-power"></i> <br />
                  <span>خروج</span>
                </BDropdownItem>
              </BCol>
            </BRow>
          </BDropdown>
        </div>
      </BCardBody>
    </BCard>
  </div>
</template>


<style scoped>
.logo-img {
  width: auto; /* Prevent scaling */
  height: 80px; /* Set a larger fixed height */
  max-width: 100%; /* Ensure the image doesn't overflow */
  display: block; /* Center the image if necessary */
  margin: 0 auto; /* Center the logo horizontally */
  border-radius: 8px; /* Soft rounded corners */
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); /* Soft shadow for depth */
  transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out; /* Smooth transition */
}
.m-header {
  display: flex;
  justify-content: center; /* Center the logo horizontally */
  align-items: center; /* Center the logo vertically */
  padding: 20px 0; /* Add vertical padding around the header */
}

</style>
