<!-- src/pages/delivery/viewstatus/finalized.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>Finalized Deliveries</li>
        </ul>
      </div>

      <!-- Main Content Card -->
      <div class="bg-neutral rounded-lg p-4 sm:p-6 mt-6">
        <!-- Header: Title and Count -->
        <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4 mb-4">
          <h2 class="text-lg font-bold">Completed and Finalized Deliveries</h2>
        </div>

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

        <!-- DESKTOP VIEW: Table -->
        <div class="overflow-x-auto hidden xl:block">
          <table class="table w-full">
            <thead>
              <tr>
                <th>Ticket #</th>
                <th>Name</th>
                <th>Status</th>
                <th>Town / Address</th>
                <th>Gallons Delivered</th>
                <th>Date</th>
                <th>Options</th>
                <th class="text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              <template v-for="oil in deliveries" :key="oil.id">
              <tr v-if="oil.id" class="hover:bg-blue-600 hover:text-white">
                <td>{{ oil.id }}</td>
                <td>
                  <router-link v-if="oil.customer_id" :to="{ name: 'customerProfile', params: { id: oil.customer_id } }" class="link link-hover">
                    {{ oil.customer_name }}
                  </router-link>
                  <span v-else>{{ oil.customer_name }}</span>
                </td>
                <td>
                  <span class="badge badge-sm badge-success">Finalized</span>
                </td>
                <td>
                  <div>{{ oil.customer_town }}</div>
                  <div class="text-xs opacity-70">{{ oil.customer_address }}</div>
                </td>
                <td>
             
                  {{ oil.gallons_delivered }}
                </td>
                <td>{{ oil.expected_delivery_date }}</td>
                <td>
                  <div class="flex flex-col gap-1">
                    <span v-if="oil.prime" class="badge badge-error badge-xs">PRIME</span>
                    <span v-if="oil.same_day" class="badge badge-error badge-xs">SAME DAY</span>
                  </div>
                </td>
                <td class="text-right">
                  <div class="flex items-center justify-end gap-2">
                    <router-link :to="{ name: 'deliveryOrder', params: { id: oil.id } }" class="btn btn-sm btn-ghost">View</router-link>
                    <router-link :to="{ name: 'deliveryEdit', params: { id: oil.id } }" class="btn btn-sm btn-secondary">Edit</router-link>
                    <router-link :to="{ name: 'Ticket', params: { id: oil.id } }" class="btn btn-sm btn-success">Print</router-link>
                  </div>
                </td>
              </tr>
              </template>
            </tbody>
          </table>
        </div>

        <!-- MOBILE VIEW: Cards -->
        <div class="xl:hidden space-y-4">
          <template v-for="oil in deliveries" :key="oil.id">
          <div v-if="oil.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">{{ oil.customer_name }}</h2>
                  <p class="text-xs text-gray-400">Ticket #{{ oil.id }}</p>
                </div>
                <div class="badge badge-success">
                  Finalized
                </div>
              </div>

              <div class="flex gap-2 mt-2">
                <div v-if="oil.prime" class="badge badge-error badge-sm">PRIME</div>
                <div v-if="oil.same_day" class="badge badge-error badge-sm">SAME DAY</div>
              </div>

              <div class="text-sm mt-2 grid grid-cols-2 gap-x-4 gap-y-1">
                <p><strong class="font-semibold">Address:</strong> {{ oil.customer_address }}</p>
                <p><strong class="font-semibold">Town:</strong> {{ oil.customer_town }}</p>
                <p><strong class="font-semibold">Gallons:</strong>
            
                  {{ oil.gallons_delivered }}
                </p>
                <p><strong class="font-semibold">Date:</strong> {{ oil.expected_delivery_date }}</p>
              </div>
              
              <div class="card-actions justify-end flex-wrap gap-2 mt-2">
                 <router-link :to="{ name: 'deliveryOrder', params: { id: oil.id } }" class="btn btn-sm btn-ghost">View</router-link>
                 <router-link :to="{ name: 'deliveryEdit', params: { id: oil.id } }" class="btn btn-sm btn-secondary">Edit</router-link>
                 <router-link :to="{ name: 'Ticket', params: { id: oil.id } }" class="btn btn-sm btn-success">Print</router-link>
              </div>
            </div>
          </div>
          </template>
        </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 setup lang="ts">
import { ref, onMounted, markRaw } from 'vue'
import axios from 'axios'
import authHeader from '../../../services/auth.header'
import { deliveryService } from '../../../services/deliveryService'
import { Delivery } from '../../../types/models'
import Header from '../../../layouts/headers/headerauth.vue'
import PaginationComp from '../../../components/pagination.vue'
import SideBar from '../../../layouts/sidebar/sidebar.vue'
import Footer from '../../../layouts/footers/footer.vue'
import {notify} from "@kyvg/vue3-notification";

// Reactive data
const token = ref(null)
const user = ref(null)
const deliveries = ref<Delivery[]>([])
const page = ref(1)
const perPage = ref(50)
const recordsLength = ref(0)
const options = ref({
  edgeNavigation: false,
  format: false,
  template: markRaw(PaginationComp)
})

// Functions
const getPage = (pageVal: any) => {
  deliveries.value = [];
  get_oil_orders(pageVal)
}

const 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) {
          user.value = response.data.user;
        }
      })
      .catch(() => {
        user.value = null
      })
}

const get_oil_orders = async (pageVal: number) => {
  try {
    const response = await deliveryService.getFinalized(pageVal)
    deliveries.value = response.data?.deliveries || []
  } catch (error) {
    console.error('Error fetching finalized deliveries:', error)
    deliveries.value = []
  }
}

const deleteCall = (delivery_id: any) => {
  let path = import.meta.env.VITE_BASE_URL + '/delivery/delete/' + delivery_id;
  axios({
    method: 'delete',
    url: path,
    headers: authHeader(),
  }).then((response: any) => {
    if (response.data.ok) {
      notify({
        title: "Success",
        text: "deleted delivery",
        type: "success",
      });
      getPage(page.value)
    } else {
      notify({
        title: "Failure",
        text: "error deleting delivery",
        type: "success",
      });
    }
  })
}

// Lifecycle
onMounted(() => {
  userStatus()
  getPage(page.value)
})
</script>
  
  <style scoped>
  
  </style>