<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>
        </ul>
      </div>
      <h1 class="text-3xl font-bold mt-4">Employees</h1>

      <!-- Main Content Card -->
      <div class="bg-neutral rounded-lg p-4 sm:p-6 mt-6">
        <!-- Header: Count and Add Button -->
        <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4 mb-4">
          <div class="badge badge-ghost">{{ recordsLength }} employees found</div>
          <router-link :to="{ name: 'employeeCreate' }" class="btn btn-primary btn-sm">
            Create New Employee
          </router-link>
        </div>

        <div class="divider"></div>

        <!-- DESKTOP VIEW: Table -->
        <div class="overflow-x-auto hidden xl:block">
          <table class="table w-full">
            <thead>
              <tr>
                <th>Employee ID</th>
                <th>Name</th>
                <th>Role</th>
                <th>Town</th>
                <th>Phone Number</th>
                <th class="text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="person in employees" :key="person.id" class="hover:bg-blue-600 hover:text-white">
                <td>{{ person.id }}</td>
                <td>{{ person.employee_first_name }} {{ person.employee_last_name }}</td>
                <td><span class="badge badge-ghost badge-sm">{{ getEmployeeTypeName(person.employee_type) }}</span></td>
                <td>{{ person.employee_town }}</td>
                <td>{{ person.employee_phone_number }}</td>
                <td class="text-right">
                  <div class="flex items-center justify-end gap-2">
                    <router-link :to="{ name: 'employeeEdit', params: { id: person.id } }" class="btn btn-sm btn-secondary">Edit</router-link>
                    <router-link :to="{ name: 'employeeProfile', params: { id: person.id } }" class="btn btn-sm btn-ghost">View</router-link>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- MOBILE VIEW: Cards -->
        <div class="xl:hidden space-y-4">
          <div v-for="person in employees" :key="person.id" class="card bg-base-100 shadow-md">
            <div class="card-body p-4">
              <div class="flex justify-between items-start">
                <div>
                  <h2 class="card-title text-base">{{ person.employee_first_name }} {{ person.employee_last_name }}</h2>
                  <p class="text-xs text-gray-400">ID: #{{ person.id }}</p>
                </div>
                <div class="badge badge-ghost">
                  {{ getEmployeeTypeName(person.employee_type) }}
                </div>
              </div>
              <div class="text-sm mt-2">
                <p>{{ person.employee_town }}</p>
                <p>{{ person.employee_phone_number }}</p>
              </div>
              <div class="card-actions justify-end flex-wrap gap-2 mt-2">
                <router-link :to="{ name: 'employeeEdit', params: { id: person.id } }" class="btn btn-sm btn-secondary">Edit</router-link>
                <router-link :to="{ name: 'employeeProfile', params: { id: person.id } }" class="btn btn-sm btn-ghost">View</router-link>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- Pagination -->
      <div class="mt-6 flex justify-center">
        <pagination @paginate="getPage" :records="recordsLength" v-model="page" :per-page="50" :options="options">
        </pagination>
      </div>

    </div>
  </div>
  <Footer />
</template><script lang="ts">
import { defineComponent } from 'vue'
import axios from 'axios'
import authHeader from '../../services/auth.header'
import PaginationComp from '../../components/pagination.vue'
import Footer from '../../layouts/footers/footer.vue'

export default defineComponent({
  name: 'EmployeeHome',
  components: {
    Footer,
  },
  data() {
    return {
      user: null,
      employees: [] as any[],
      page: 1,
      perPage: 50,
      recordsLength: 0,
      options: {
        edgeNavigation: false,
        format: false,
        template: PaginationComp
      }
    }
  },
  created() {
    this.userStatus();
  },
  mounted() {
    this.getPage(this.page);
  },
  methods: {
    getPage: function (page: number) {
      this.get_employees(page);
    },
    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;
        });
    },
    // --- METHOD CORRECTED TO MATCH YOUR SIMPLE ARRAY API RESPONSE ---
    get_employees(page: number) {
      // Using your original, working URL
      const path = `${import.meta.env.VITE_BASE_URL}/employee/all/${page}`;
      
      axios.get(path, { headers: authHeader() })
        .then((response: any) => {
          // --- FIX 1: Assign the response data directly, as it's an array ---
          this.employees = response.data;

          // --- FIX 2: Set the recordsLength from the array length ---
          // NOTE: For full pagination, your API will eventually need to send the *total* count.
          // For now, this will show the count of items on the current page.
          // If you update your API to send { data: [], total_records: X }, this is the only line you'd change.
          this.recordsLength = response.data.length; 
        })
        .catch((error: any) => {
            console.error("Failed to fetch employees:", error);
        });
    },
    getEmployeeTypeName(typeId: number | string): string {
      const typeMap: { [key: string]: string } = {
        '0': 'Owner', '1': 'Manager', '2': 'Secretary', '3': 'Office',
        '4': 'Driver', '5': 'Service Tech', '6': 'Contractor', '7': 'Cash Driver', '8': 'Driver/Tech'
      };
      return typeMap[String(typeId)] || 'Unknown Role';
    }
  },
})
</script>