<template>
  <section v-if="!addBool" :class="['information', darkMode ? 'section-darkmode' : 'section-lightmode']">
    <h2 v-if="!editable" :class="['customer-name', darkMode ? 'h2-darkmode' : 'h2-lightmode']">{{ empl.name }}
    </h2>
    <input v-if="editable" v-model="empl.name" @change="updateEmployee()"
      :class="['data', 'customer-name-input', darkMode ? 'h2-darkmode' : 'h2-lightmode', darkMode ? 'h2-input-darkmode' : 'h2-input-lightmode', 'input']">
    <div class="data-group" id="personal-data">
      <div class="data-group" id="full-name">
        <div class="data-field" id="ntitle">
          <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Title/-s:</pre>
          <pre v-if="!editable" :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ empl.title }}</pre>
          <input v-if="editable" v-model="empl.title" @change="updateEmployee()"
            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
        </div>
        <div class="data-field" id="first-name">
          <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">First Name/-s:</pre>
          <pre v-if="!editable"
            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ empl.firstName }}</pre>
          <input v-if="editable" v-model="empl.firstName" @change="updateEmployee()"
            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
        </div>
        <div class="data-field" id="last-name">
          <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Last Name/-s:</pre>
          <pre v-if="!editable"
            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ empl.lastName }}</pre>
          <input v-if="editable" v-model="empl.lastName" @change="updateEmployee()"
            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
        </div>
      </div>
      <div class="data-group" id="other">
        <div class="data-field" id="id">
          <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">ID:</pre>
          <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ empl.primaryID }}</pre>
        </div>
        <div class="data-field" id="pronouns">
          <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Pronouns:</pre>
          <pre v-if="!editable"
            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ empl.pronouns }}</pre>
          <input v-if="editable" v-model="empl.pronouns" @change="updateEmployee()"
            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
        </div>
        <div class="data-field" id="preferred-name">
          <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Preferred Name:</pre>
          <pre v-if="!editable"
            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ empl.preferredName }}</pre>
          <input v-if="editable" v-model="empl.preferredName" @change="updateEmployee()"
            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
        </div>
      </div>
    </div>
    <div class="data-group" id="employment-data">
      <div class="data-field" id="customer-id">
        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Customer ID:</pre>
        <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ empl.customerID }}</pre>
      </div>
      <div class="data-field" id="department">
        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Department:</pre>
        <pre v-if="!editable"
          :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ empl.department }}</pre>
        <select v-if="editable" id="customersDropDownChosenCI" v-model="empl.department" @change="updateDepartmentID()"
          :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
          <option v-for="depart in departments" :key="depart.primaryID">
            {{ depart.name }}
          </option>
        </select>
      </div>
      <div class="data-field" id="job-title">
        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Job Title:</pre>
        <pre v-if="!editable" :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ empl.jobTitle }}</pre>
        <input v-if="editable" v-model="empl.jobTitle" @change="updateEmployee()"
          :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
      </div>
    </div>
    <div class="data-group" id="contact-data">
      <div class="data-field" id="phone">
        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Phone No.:</pre>
        <pre v-if="!editable"
          :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ empl.phonenumber }}</pre>
        <input v-if="editable" v-model="empl.phonenumber" @change="updateEmployee()"
          :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
      </div>
      <div class="data-field" id="mail">
        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">E-Mail:</pre>
        <pre v-if="!editable" :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ empl.eMail }}</pre>
        <input v-if="editable" v-model="empl.eMail" @change="updateEmployee()"
          :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
      </div>
    </div>
    <div class="notes">
      <pre :class="['area-title', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Notes:</pre>
      <input v-model="empl.notes" :readonly="!editable" @change="updateEmployee()"
        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']" id="notes">
    </div>
  </section>
  <section v-if="addBool" :class="['information', darkMode ? 'section-darkmode' : 'section-lightmode']">
    <input v-model="newName"
      :class="['data', 'customer-name-input', darkMode ? 'h2-darkmode' : 'h2-lightmode', darkMode ? 'h2-input-darkmode' : 'h2-input-lightmode', 'input']">
    <div class="data-group" id="personal-data">
      <div class="data-group" id="full-name">
        <div class="data-field" id="ntitle">
          <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Title/-s:</pre>
          <input v-model="newTitle" :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
        </div>
        <div class="data-field" id="first-name">
          <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">First Name/-s:</pre>
          <input v-model="newFirstName" :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
        </div>
        <div class="data-field" id="last-name">
          <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Last Name/-s:</pre>
          <input v-model="newLastName" :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
        </div>
      </div>
      <div class="data-group" id="other">
        <div class="data-field" id="id">
          <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">ID:</pre>
          <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">...</pre>
        </div>
        <div class="data-field" id="pronouns">
          <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Pronouns:</pre>
          <input v-model="newPronouns" :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
        </div>
        <div class="data-field" id="preferred-name">
          <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Preferred Name:</pre>
          <input v-model="newPreferedName" :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
        </div>
      </div>
    </div>
    <div class="data-group" id="employment-data">
      <div class="data-field" id="customer-id">
        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Customer ID:</pre>
        <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ chosenCustomerId }}</pre>
      </div>
      <div class="data-field" id="department">
        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Department:</pre>
        <select id="customersDropDownChosenCI" v-model="newDepartment" @change="updateNewDepartmentID()"
          :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
          <option v-for="depart in departments" :key="depart.primaryID">
            {{ depart.name }}
          </option>
        </select>
      </div>
      <div class="data-field" id="job-title">
        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Job Title:</pre>
        <input v-model="newJobTitle" :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
      </div>
    </div>
    <div class="data-group" id="contact-data">
      <div class="data-field" id="phone">
        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Phone No.:</pre>
        <input v-model="newPhonenumber" :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
      </div>
      <div class="data-field" id="mail">
        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">E-Mail:</pre>
        <input v-model="newEMail" :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
      </div>
    </div>
    <div class="notes">
      <pre :class="['area-title', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Notes:</pre>
      <input v-model="newNotes" :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']" id="notes">
    </div>
  </section>
  <section v-if="addBool" id="saveNewItem">
    <button :class="[darkMode ? 'saveNewItem-darkmode' : 'saveNewItem-lightmode']" @click="addEmployee()">Save</button>
  </section>
</template>


<script setup>
import { ref, onMounted, watch } from 'vue';
import { useStore } from 'vuex';
import { computed } from 'vue';
import Axios from '../axios.config.js';
import clientsideConfig from '../../clientsideConfig.js';

const store = useStore();
const modeChanged = computed(() => store.state.updateDarkMode);

const editable = computed(() => store.state.editable);
const chosenCustomerId = computed(() => store.state.chosenCustomerId);
const chosenCustomerEmployeeId = computed(() => store.state.chosenCustomerEmployeeId);
const deleteBool = computed(() => store.state.deleteBool);
const addBool = computed(() => store.state.new);

const darkMode = ref('')
const empl = ref({});
const department = ref({});
const customer = ref({});
const employees = ref([]);
const departments = ref([]);

const newName = ref('');
const newPronouns = ref('');
const newTitle = ref('');
const newFirstName = ref('');
const newLastName = ref('');
const newPreferedName = ref('');
const newDepartment = ref('');
const newDepartmentID = ref('');
const newJobTitle = ref('');
const newPhonenumber = ref('');
const newEMail = ref('');
const newNotes = ref('');

// get employee from id
const getEmployeeById = async () => {
  if (!addBool.value) {
    try {
      const response = await Axios.get(
        `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getCustEmployee/${chosenCustomerEmployeeId.value}`
      );
      empl.value = response.data;
    } catch (err) {
      console.log(err.response.statusText);
    }
  }
}

// get customer from id
const getCustomerById = async () => {
  try {
    const response = await Axios.get(
      `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getCustomerById/${chosenCustomerId.value}`
    );
    customer.value = response.data;
  } catch (err) {
    console.log(err.response.statusText);
  }
}

//update data
const updateEmployee = async () => {
  if (empl.value.name.trim() === "") {
    alert("Please add an employee name!");
    return;
  } else {
    var counter = 0;
    // check if employee name already exists
    employees.value.forEach(e => {
      if (e.name === empl.value.name) {
        counter += 1;
      }
    });
    if (counter == 2) {
      alert("This employee name already exists. Please choose an unique employee name or modify respectively delete the old one!");
      empl.value.name = '';
      return;
    }
    if (empl.value.department.trim() === "") {
      alert("Please choose an department!");
      return;
    }
    if (!validateEMail(empl.value.eMail)) {
      alert("Please add a valid email!");
      return;
    }
    try {
      await Axios.put(
        `https://${clientsideConfig.url}:${clientsideConfig.port}/api/updateCustEmployee`,
        {
          primaryID: empl.value.primaryID,
          name: empl.value.name,
          pronouns: empl.value.pronouns,
          title: empl.value.title,
          firstName: empl.value.firstName,
          lastName: empl.value.lastName,
          preferredName: empl.value.preferredName,
          department: empl.value.department,
          departmentID: empl.value.departmentID,
          jobTitle: empl.value.jobTitle,
          phonenumber: empl.value.phonenumber,
          eMail: empl.value.eMail,
          notes: empl.value.notes,
        }
      )
      await getEmployeeById();
    } catch (err) {
      console.log(err.response.statusText);
    }
  }
}

// add new employee
const addEmployee = async () => {
  // check if all input data is valid
  if (newName.value.trim() === "") {
    alert("Please add an employee name!");
    return;
  } else {
    var counter = 0;
    // check if employee name already exists
    employees.value.forEach(c => {
      if (c.name === newName.value) {
        counter += 1;
      }
    });
    if (counter == 1) {
      alert("This employee name already exists. Please choose an unique employee name or modify respectively delete the old one!");
      return;
    }
  }
  if (!validateEMail(newEMail.value)) {
    alert("Please add a valid email!");
    return;
  }
  if (newDepartment.value.trim() === "") {
    alert("Please choose a department!");
    return;
  }
  try {
    const response = await Axios.post(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/addCustEmployee`,
      {
        customerID: chosenCustomerId.value,
        customername: customer.value.customername,
        name: newName.value,
        pronouns: newPronouns.value,
        title: newTitle.value,
        firstName: newFirstName.value,
        lastName: newLastName.value,
        preferredName: newPreferedName.value,
        department: newDepartment.value,
        departmentID: newDepartmentID.value,
        jobTitle: newJobTitle.value,
        phonenumber: newPhonenumber.value,
        eMail: newEMail.value,
        notes: newNotes.value,
      });
    store.commit('resetStoreNotCustomer');
    store.commit('changeToCustomerEmployeelist');
  } catch (err) {
    console.log(err.response.statusText);
  }
}

// to validate the email address
const validateEMail = (email) => {
  const emailRegex = new RegExp(/^[A-Za-z0-9_!#$%&'*+\/=?`{|}~^.-]+@[A-Za-z0-9.-]+$/, "gm");
  if (email === "") {
    return true
  }
  return emailRegex.test(email);
}

//get all employees
const getEmployees = async () => {
  try {
    const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getSelectedCustEmployeeByCustomer/${chosenCustomerEmployeeId.value}`
    );
    employees.value = response.data;
  } catch (err) {
    console.log(err.response.statusText);
  }
}

const confirmDeleteEmployee = async () => {
  if (deleteBool.value === true) {
    if (confirm("Do you really want to delete this employee? It cannot be undone!")) {
      try {
        await Axios.delete(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/deleteCustEmployee/${chosenCustomerEmployeeId.value}`);
        store.commit('undoDelete');
        store.commit('resetStoreNotCustomer');
        store.commit('changeToCustomerEmployeelist');
      } catch (err) {
        console.log(err.response.statusText);
      }
    } else {
      store.commit('undoDelete');
    }
  }
}

//get all departments
const getDepartments = async () => {
  try {
    const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getSelectedDepartmentByCustomer/${chosenCustomerId.value}`);
    departments.value = response.data;
  } catch (err) {
    console.log(err.response.statusText);
  }
}

// update departmentid if department was changed
const updateDepartmentID = async () => {
  try {
    const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getDprtmntByName/${empl.value.department}`);
    department.value = response.data;
    empl.value.departmentID = department.value.primaryID;
  } catch (err) {
    console.log(err.response.statusText);
  }
  await updateEmployee();
}

// update departmentid if department was changed
const updateNewDepartmentID = async () => {
  try {
    const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getDprtmntByName/${newDepartment.value}`);
    newDepartmentID.value = response.data.primaryID;
  } catch (err) {
    console.log(err.response.statusText);
  }
}

// include delay to avoid 503 error
const triggerBackendCallsWithDelay = async (fetchDataFunc) => {
  setTimeout(() => {
    fetchDataFunc();
  }, 2000);
}

// include delay to avoid 503 error
const triggerBackendCallsWithSmallDelay = async (fetchDataFunc) => {
  setTimeout(() => {
    fetchDataFunc();
  }, 500);
}

const getSession = async () => {
  const loggedInUserDarkModeBool = getItem('logged-in-user-darkMode');
  if (loggedInUserDarkModeBool == 1) {
    darkMode.value = true;
  } else {
    darkMode.value = false;
  }
}

function getItem(item) {
  if (process.client) {
    return localStorage.getItem(item)
  } else {
    return undefined
  }
}

watch(modeChanged, getSession)
watch(deleteBool, confirmDeleteEmployee);

onMounted(async () => {
  getSession();
  await getEmployeeById();
  triggerBackendCallsWithSmallDelay(getDepartments);
  triggerBackendCallsWithDelay(getCustomerById);
  triggerBackendCallsWithDelay(getEmployees);
});
</script>

<script>
export default {
  name: "CustomerEmployee",
};
</script>



<style scoped>
* {
  box-sizing: border-box;
  margin: 0;
}

.information {
  display: flex;
  flex-direction: column;
  width: 100%;
  align-items: flex-start;
  justify-content: center;
  padding: 1.25rem 1.875rem;
  border-radius: 0.625rem;
  box-shadow: 0.25rem 0.25rem 0.25rem 0rem rgba(0, 0, 0, 0.25);
}

.section-darkmode {
  background-color: #2c2c2c;
}

.section-lightmode {
  background-color: #ffffff;
}

.h2-input-darkmode {
  background-color: #212121;
}

.h2-input-lightmode {
  background-color: #EBEBEB;
}

.customer-name {
  align-self: stretch;
  padding: 1rem 0;
  margin: 1rem;
  letter-spacing: 5%;
  text-decoration-line: underline;
  font: italic 400 1rem/187.5% Overpass, -apple-system, Roboto, Helvetica,
    sans-serif;
}

.saveNewItem-darkmode {
  background: #2c2c2c;
  color: #fff;
  font: 400 0.875rem/1.875rem Overpass, sans-serif;
  border: none;
  padding: 1rem 1.875rem;
  width: 8%;
  border-radius: 0.625rem;
  box-shadow: 0.25rem 0.25rem 0.25rem 0rem rgba(0, 0, 0, 0.25);
}

.saveNewItem-lightmode {
  background: #EBEBEB;
  color: #212121;
  font: 400 0.875rem/1.875rem Overpass, sans-serif;
  border: none;
  padding: 1rem 1.875rem;
  width: 8%;
  border-radius: 0.625rem;
  box-shadow: 0.25rem 0.25rem 0.25rem 0rem rgba(0, 0, 0, 0.25);
}

.saveNewItem-darkmode:hover {
  background-color: #444444;
  cursor: pointer;
}

.saveNewItem-lightmode:hover {
  background-color: #ACACAC;
  cursor: pointer;
}

#saveNewItem {
  text-align: center;
}

.input {
  border: none;
}

.customer-name-input {
  padding: 1rem 0;
  margin: 1rem;
  font-size: initial;
  letter-spacing: 5%;
  text-decoration-line: underline;
  font: italic 400 1rem/187.5% Overpass, -apple-system, Roboto, Helvetica,
    sans-serif;
}

.h2-darkmode {
  color: #fff;
}

.h2-lightmode {
  color: #000;
}

.select-darkmode {
  border: none;
  color: white;
  background: #212121;
  padding: 0.4rem;
  border-radius: 0.3125rem;
}

.select-lightmode {
  border: none;
  color: black;
  background: #EBEBEB;
  padding: 0.4rem;
  border-radius: 0.3125rem;
}

.data-group {
  display: flex;
  flex: auto;
  width: 100%;
  flex-direction: row;
  padding: 1.25rem 0;
  align-items: center;
  justify-content: stretch;
}

#personal-data {
  flex-direction: column;
  align-items: stretch;
  justify-content: center;
  gap: 0.625rem;
}

#full-name,
#other {
  padding: 0;
}


.data-field {
  display: flex;
  flex: auto;
  width: 20%;
  flex-direction: row;
  padding: 0.8rem 1.875rem;
  align-items: center;
  justify-content: flex-start;
  gap: 1.25rem;
}

#first-name,
#last-name,
#department,
#job-title,
#phone {
  width: 40%;
}

#preferred-name,
#mail {
  width: 60%;
}

.label {
  letter-spacing: 0.02rem;
  font: 400 0.875rem/1.875rem Overpass, sans-serif;
}

.pre-darkmode {
  color: #ffffff;
}

.pre-lightmode {
  color: #000000;
}

.data {
  display: flex;
  flex-direction: row;
  padding: 0 0.625rem;
  border-radius: 0.3125rem;
  box-shadow: 0.0625rem 0.0625rem 0.25rem 0rem rgba(0, 0, 0, 0.25) inset;
  background-color: #212121;
  align-items: center;
  justify-content: flex-start;
  letter-spacing: 0.02rem;
  font: 400 0.75rem/1.875rem Overpass, sans-serif;
}

.data-darkmode {
  background-color: #212121;
  color: #ffffff;
}

.data-lightmode {
  background-color: #ebebeb;
  color: #000000;
}


.notes {
  display: flex;
  flex: auto;
  flex-direction: column;
  padding: 1.25rem 1.875rem 0.625rem;
  align-items: flex-start;
  justify-content: center;
  gap: 0.625rem;
  width: 100%;
}

.area-title {
  letter-spacing: 0.03rem;
  font: 400 0.875rem/1.875rem Overpass, sans-serif;
}

#notes {
  align-self: stretch;
}
</style>