<template>

  <div class="navbar bg-primary border-b border-bottom-500 border-gray-500">
    <div class="basis-1/4 md:basis-1/4">
      <router-link :to="{ name: 'home' }">
      <div class="text-3xl"> 
        <img src="../../assets/images/1.png" alt="" width="250" height="250" />

      </div>
      </router-link>
    </div>
    <div class="basis-1/4 md:basis-1/2 justify-center text-center">
      <input type="text" placeholder="Search " class="input input-bordered w-24 md:w-auto grow" v-model="searchTerm" />
    </div>

    <div class="basis-1/2 md:basis-1/4 justify-end gap-5">
      <router-link :to="{ name: 'customerCreate' }">
        <button class="btn btn-accent btn-sm">Create Customer</button>
      </router-link>

      <div v-if="employee.id">
        <router-link :to="{ name: 'employeeProfile', params: { id: employee.id } }">
          <div class="">{{ user.user_name }}</div>
        </router-link>
      </div>
    </div>


  </div>
  <div class="grid grid-cols-12 ">
    <div class="grow col-start-4 col-span-6 ">
      <SearchResults v-if="customers.length" :customers="customers" />
    </div>
  </div>
</template>


<script lang="ts">
import { debounce } from "vue-debounce";
import { defineComponent } from "vue";
import axios from "axios";
import authHeader from "../../services/auth.header";
import SearchResults from "./SearchResults.vue";

export default defineComponent({
  name: "HeaderAuth",
  components: {
    SearchResults,

  },

  created() {
    this.userStatus();
  },
  data() {
    return {
      user: {
        user_id: 0,
        user_name: '',
      },
      company_id: 0,
      company: {
        creation_date: "",
        account_prefix: "",
        company_name: "",
        company_address: "",
        company_town: "",
        company_zip: "",
        company_state: "",
        company_phone_number: "",
      },
      employee: {
        id: '',
        user_id: '',
        employee_last_name: "",
        employee_first_name: "",
        employee_town: "",
        employee_address: "",
        employee_apt: "",
        employee_zip: "",
        employee_birthday: "",
        employee_phone_number: "",
        employee_start_date: "",
        employee_end_date: "",
        employee_type: '',
        employee_state: '',
      },
      loaded: false,
      searchTerm: "",
      customers: [],
      type_of_search: 0,
    };
  },
  watch: {
    searchTerm(this: any) {
      this.performSearch();
    },
  },
  mounted() {
    this.getCompany();

  },
  methods: {
    performSearch: debounce(async function (this: any) {
      if (this.searchTerm === "") {
        this.customers = [];
        return;
      }
      if (this.searchTerm.length < 2) {
        return;
      }

      if (this.searchTerm.startsWith("@")) {
        this.type_of_search = 0
      } else if (this.searchTerm.startsWith("!")) {
        this.type_of_search = 1
      } else if (this.searchTerm.startsWith("#")) {
        this.type_of_search = 2
      } else {
        this.type_of_search = 2
      }

      const searchUrl = this.getSearchUrl();
      const response = await (await fetch(searchUrl)).json();

      this.customers = response;
    }, 600),
    getSearchUrl() {
      if (this.type_of_search == 0) {
        const url = import.meta.env.VITE_BASE_URL + "/search/customer";
        const params = {
          q: this.searchTerm,
        };
        const searchParams = new URLSearchParams(params);
        return `${url}?${searchParams}`;
      }
      else if (this.type_of_search == 1) {
        const url = import.meta.env.VITE_BASE_URL +"/search/customer";
        const params = {
          q: this.searchTerm,
        };
        const searchParams = new URLSearchParams(params);
        return `${url}?${searchParams}`;
      }
      else if (this.type_of_search == 2) {
        const url = import.meta.env.VITE_BASE_URL +"/search/customer";
        const params = {
          q: this.searchTerm,
        };
        const searchParams = new URLSearchParams(params);
        return `${url}?${searchParams}`;
      }
      else {
        const url = import.meta.env.VITE_BASE_URL +"/search/customer";
        const params = {
          q: this.searchTerm,
        };
        const searchParams = new URLSearchParams(params);
        return `${url}?${searchParams}`;
      }
    },

    userStatus() {
      let path = import.meta.env.VITE_BASE_URL + '/auth/whoami';
      axios({
        method: "get",
        url: path,
        withCredentials: true,
        headers: authHeader(),
      })
        .then((response: any) => {
          if (response.data.ok) {
            this.user = response.data.user;
            this.employeeStatus()
            this.loaded = true;
          } else {
            localStorage.removeItem('user');
            this.$router.push('/login');
          }
        })
        .catch(() => {
          this.loaded = true;
          this.$router.push('/login');
        });
    },
    employeeStatus() {
      let path = import.meta.env.VITE_BASE_URL + '/employee/userid/' + this.user.user_id;

      axios({
        method: "get",
        url: path,
        withCredentials: true,
        headers: authHeader(),
      })
        .then((response: any) => {
          this.employee = response.data;
          this.loaded = true;

        })
    },
    getCompany() {
      let path = import.meta.env.VITE_BASE_URL + '/admin/company/' + import.meta.env.VITE_COMPANY_ID;
      axios({
        method: "get",
        url: path,
        withCredentials: true,
        headers: authHeader(),
      })
        .then((response: any) => {
          this.company = response.data;
          this.company_id = import.meta.env.VITE_COMPANY_ID
   

        })
    },
  },
});
</script>

<style scoped></style>