<!-- src/pages/employee/edit.vue -->
<template>
  <div class="flex">
    <div class="w-full px-4 md:px-10 py-4">
      <!-- Breadcrumbs & Title -->
      <div class="text-sm breadcrumbs">
        <ul>
          <li><router-link :to="{ name: 'home' }">Home</router-link></li>
          <li>Employees</li>
          <li>Edit Employee</li>
        </ul>
      </div>

      <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between mt-4">
        <h1 class="text-3xl font-bold">
          Edit Employee
        </h1>
        <router-link v-if="employee_id" :to="{ name: 'employeeProfile', params: { id: employee_id } }" class="btn btn-secondary btn-sm mt-2 sm:mt-0">
          Back to Profile
        </router-link>
      </div>

      <!-- Main Form Card -->
      <div class="bg-neutral rounded-lg p-6 mt-6">
        <form @submit.prevent="onSubmit" class="space-y-6">

          <!-- SECTION 1: General Info -->
          <div>
            <h2 class="text-lg font-bold">General Info</h2>
            <div class="divider mt-2 mb-4"></div>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              <!-- First Name -->
              <div class="form-control">
                <label class="label"><span class="label-text">First Name</span></label>
                <input v-model="CreateEmployeeForm.employee_first_name" type="text" placeholder="First Name" class="input input-bordered input-sm w-full" />
                <span v-if="v$.CreateEmployeeForm.employee_first_name.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateEmployeeForm.employee_first_name.$errors[0].$message }}
                </span>
              </div>
              <!-- Last Name -->
              <div class="form-control">
                <label class="label"><span class="label-text">Last Name</span></label>
                <input v-model="CreateEmployeeForm.employee_last_name" type="text" placeholder="Last Name" class="input input-bordered input-sm w-full" />
                <span v-if="v$.CreateEmployeeForm.employee_last_name.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateEmployeeForm.employee_last_name.$errors[0].$message }}
                </span>
              </div>
              <!-- Phone Number -->
              <div class="form-control">
                <label class="label"><span class="label-text">Phone Number</span></label>
                <input v-model="CreateEmployeeForm.employee_phone_number" @input="acceptNumber()" type="text" placeholder="Phone Number" class="input input-bordered input-sm w-full" />
                <span v-if="v$.CreateEmployeeForm.employee_phone_number.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateEmployeeForm.employee_phone_number.$errors[0].$message }}
                </span>
              </div>
              <!-- Employee Type -->
              <div class="form-control">
                <label class="label"><span class="label-text">Employee Role</span></label>
                <select v-model="CreateEmployeeForm.employee_type" class="select select-bordered select-sm w-full">
                  <option disabled :value="0">Select a role</option>
                  <option v-for="employee in employList" :key="employee.value" :value="employee.value">
                    {{ employee.text }}
                  </option>
                </select>
                <span v-if="v$.CreateEmployeeForm.employee_type.$error" class="text-red-500 text-xs mt-1">
                  Role is required.
                </span>
              </div>
            </div>
          </div>

          <!-- SECTION 2: Address -->
          <div>
            <h2 class="text-lg font-bold">Address</h2>
            <div class="divider mt-2 mb-4"></div>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <!-- Street Address -->
              <div class="form-control">
                <label class="label"><span class="label-text">Street Address</span></label>
                <input v-model="CreateEmployeeForm.employee_address" type="text" placeholder="Street Address" class="input input-bordered input-sm w-full" />
                <span v-if="v$.CreateEmployeeForm.employee_address.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateEmployeeForm.employee_address.$errors[0].$message }}
                </span>
              </div>
              <!-- Apt, Suite, etc. -->
              <div class="form-control">
                <label class="label"><span class="label-text">Apt, Suite, etc. (Optional)</span></label>
                <input v-model="CreateEmployeeForm.employee_apt" type="text" placeholder="Apt, suite, unit..." class="input input-bordered input-sm w-full" />
              </div>
              <!-- Town -->
              <div class="form-control">
                <label class="label"><span class="label-text">Town</span></label>
                <input v-model="CreateEmployeeForm.employee_town" type="text" placeholder="Town" class="input input-bordered input-sm w-full" />
                <span v-if="v$.CreateEmployeeForm.employee_town.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateEmployeeForm.employee_town.$errors[0].$message }}
                </span>
              </div>
              <!-- State -->
              <div class="form-control">
                <label class="label"><span class="label-text">State</span></label>
                <select v-model="CreateEmployeeForm.employee_state" class="select select-bordered select-sm w-full">
                  <option disabled :value="0">Select a state</option>
                  <option v-for="state in stateList" :key="state.value" :value="state.value">
                    {{ state.text }}
                  </option>
                </select>
                <span v-if="v$.CreateEmployeeForm.employee_state.$error" class="text-red-500 text-xs mt-1">
                  State is required.
                </span>
              </div>
              <!-- Zip Code -->
              <div class="form-control">
                <label class="label"><span class="label-text">Zip Code</span></label>
                <input v-model="CreateEmployeeForm.employee_zip" type="text" placeholder="Zip Code" class="input input-bordered input-sm w-full" />
                <span v-if="v$.CreateEmployeeForm.employee_zip.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateEmployeeForm.employee_zip.$errors[0].$message }}
                </span>
              </div>
            </div>
          </div>

          <!-- SECTION 3: Employment Dates -->
          <div>
            <h2 class="text-lg font-bold">Employment Dates & Details</h2>
            <div class="divider mt-2 mb-4"></div>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div class="form-control">
                <label class="label"><span class="label-text">Birthday</span></label>
                <input v-model="CreateEmployeeForm.employee_birthday" type="date" class="input input-bordered input-sm w-full" />
                <span v-if="v$.CreateEmployeeForm.employee_birthday.$error" class="text-red-500 text-xs mt-1">Required.</span>
              </div>
              <div class="form-control">
                <label class="label"><span class="label-text">Start Date</span></label>
                <input v-model="CreateEmployeeForm.employee_start_date" type="date" class="input input-bordered input-sm w-full" />
                <span v-if="v$.CreateEmployeeForm.employee_start_date.$error" class="text-red-500 text-xs mt-1">Required.</span>
              </div>
              <div class="form-control">
                <label class="label"><span class="label-text">End Date (Optional)</span></label>
                <input v-model="CreateEmployeeForm.employee_end_date" type="date" class="input input-bordered input-sm w-full" />
              </div>
            </div>
          </div>

          <!-- SECTION 4: Fired or Current -->
          <div>
            <h2 class="text-lg font-bold">Fired or Current</h2>
            <div class="divider mt-2 mb-4"></div>
            <div class="form-control">
              <label class="label cursor-pointer">
                <span class="label-text">Active Employee</span>
                <input v-model="CreateEmployeeForm.active" type="checkbox" class="checkbox checkbox-primary" />
              </label>
            </div>
          </div>

          <!-- SUBMIT BUTTON -->
          <div class="pt-4">
            <button type="submit" class="btn btn-primary btn-sm">Save Changes</button>
          </div>
        </form>
      </div>
    </div>
  </div>
  
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import axios from 'axios'
import authHeader from '../../services/auth.header'
import useValidate from "@vuelidate/core";
import { minLength, required } from "@vuelidate/validators";

interface SelectOption {
  text: string;
  value: number;
}

export default defineComponent({
  name: 'EmployeeEdit',
  components: {
  },
  data() {
    return {
      v$: useValidate(),
      user: null,
      stateList: [] as SelectOption[],
      employList: [] as SelectOption[],
      employee_id: this.$route.params.id as string,
      CreateEmployeeForm: {
        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: 0,
        employee_state: 0,
        active: true,
      },
    }
  },
  validations() {
    return {
      CreateEmployeeForm: {
        employee_last_name: { required, minLength: minLength(1) },
        employee_first_name: { required, minLength: minLength(1) },
        employee_town: { required, minLength: minLength(1) },
        employee_type: { required },
        employee_zip: { required, minLength: minLength(5) },
        employee_state: { required },
        employee_address: { required },
        employee_birthday: { required },
        employee_phone_number: { required },
        employee_start_date: { required },
      },
    };
  },
  created() {
    this.userStatus();
    this.getEmployee(this.employee_id);
  },
  mounted() {
    this.getEmployeeTypeList();
    this.getStatesList();
  },
  methods: {
    // --- FIX APPLIED HERE ---
    acceptNumber() {
      const x = this.CreateEmployeeForm.employee_phone_number.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
      // This 'if' block ensures 'x' is not null before we use it.
      if (x) {
        this.CreateEmployeeForm.employee_phone_number = !x[2] ? x[1] : `(${x[1]}) ${x[2]}${x[3] ? `-${x[3]}` : ''}`;
      }
    },
    userStatus() {
      const path = import.meta.env.VITE_BASE_URL + '/auth/whoami';
      axios.get(path, { withCredentials: true, headers: authHeader() })
        .then((response: any) => {
          if (response.data.ok) {
            this.user = response.data.user;
          }
        })
        .catch(() => { this.user = null; });
    },
    EditEmployee(payload: any) {
      const path = `${import.meta.env.VITE_BASE_URL}/employee/edit/${this.employee_id}`;
      // Convert active from boolean to integer for API
      const apiPayload = { ...payload, active: payload.active ? 1 : 0 };
      axios.post(path, apiPayload, { withCredentials: true, headers: authHeader() })
        .then((response: any) => {
          if (response.data.ok) {
            this.$router.push({ name: "employeeProfile", params: { id: this.employee_id } });
          } else {
            console.error("Failed to edit employee:", response.data.error);
          }
        });
    },
    getEmployee(userid: any) {
      const path = `${import.meta.env.VITE_BASE_URL}/employee/${userid}`;
      axios.get(path, { withCredentials: true, headers: authHeader() })
        .then((response: any) => {
          const data = response.data;
          // Convert active from integer to boolean
          data.active = data.active === 1;
          this.CreateEmployeeForm = data;
        });
    },
    onSubmit() {
      this.v$.$validate();
      if (!this.v$.$error) {
        this.EditEmployee(this.CreateEmployeeForm);
      } else {
        console.log("Form validation failed.");
      }
    },
    getEmployeeTypeList() {
      const path = import.meta.env.VITE_BASE_URL + "/query/employeetype";
      axios.get(path, { withCredentials: true, headers: authHeader() })
        .then((response: any) => { this.employList = response.data; });
    },
    getStatesList() {
      const path = import.meta.env.VITE_BASE_URL + "/query/states";
      axios.get(path, { withCredentials: true, headers: authHeader() })
        .then((response: any) => { this.stateList = response.data; });
    },
  },
})
</script>
