<!-- src/pages/delivery/edit.vue -->
<template>
  <div class="flex">
    <!-- Main Content -->
    <div class="w-full px-4 md:px-10 py-4">
      <!-- Breadcrumbs Navigation -->
      <div class="text-sm breadcrumbs">
        <ul>
          <li><router-link :to="{ name: 'home' }">Home</router-link></li>
          <li>Edit Oil Delivery #{{ deliveryOrder.id }}</li>
        </ul>
      </div>

      <!-- TOP SECTION: Customer and Payment Info -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 my-6">
        <!-- Customer Info Card -->
        <div v-if="customer.id" class="bg-neutral rounded-lg p-5">
          <div class="flex justify-between items-center mb-4">
            <div>
              <div class="text-xl font-bold">{{ customer.customer_first_name }} {{ customer.customer_last_name }}</div>
              <div class="text-sm text-gray-400">Account: {{ customer.account_number }}</div>
            </div>
            <router-link :to="{ name: 'customerProfile', params: { id: customer.id } }" class="btn btn-secondary btn-sm">
              View Profile
            </router-link>
          </div>
          <div>
            <div>{{ customer.customer_address }}</div>
            <div v-if="customer.customer_apt && customer.customer_apt !== 'None'">{{ customer.customer_apt }}</div>
            <div>{{ customer.customer_town }}, {{ stateName }} {{ customer.customer_zip }}</div>
            <div class="mt-2">{{ customer.customer_phone_number }}</div>
          </div>
        </div>

        <!-- Payment Card on File Card -->
        <div v-if="deliveryOrder.payment_type === 1 && userCard.id" class="bg-neutral rounded-lg p-5">
          <h3 class="text-xl font-bold mb-4">Card on File</h3>
          <div class="space-y-1">
            <p><span class="font-semibold">Card Type:</span> {{ userCard.type_of_card }}</p>
            <p><span class="font-semibold">Card Number:</span> {{ userCard.card_number }}</p>
            <p><span class="font-semibold">Name:</span> {{ userCard.name_on_card }}</p>
            <p><span class="font-semibold">Expires:</span> {{ userCard.expiration_month }}/{{ userCard.expiration_year }}</p>
            <p><span class="font-semibold">CVV:</span> {{ userCard.security_number }}</p>
          </div>
        </div>
      </div>

      <!-- BOTTOM SECTION: Edit Form -->
      <div class="bg-neutral rounded-lg p-6">
        <h2 class="text-2xl font-bold mb-4">Update Delivery Details</h2>
        <form @submit.prevent="onSubmit" class="space-y-4">
          <!-- Gallons Ordered & Fill Checkbox -->
          <div class="flex items-end gap-4">
            <div class="flex-grow">
              <label class="label"><span class="label-text font-bold">Gallons Ordered</span></label>
              <input v-model="CreateOilOrderForm.basicInfo.gallons_ordered" :disabled="CreateOilOrderForm.basicInfo.customer_asked_for_fill"
                     class="input input-bordered input-sm w-full max-w-xs" type="number" placeholder="# gallons" />
              <span v-if="v$.CreateOilOrderForm.basicInfo.gallons_ordered.$error" class="text-red-500 text-xs mt-1">
                {{ v$.CreateOilOrderForm.basicInfo.gallons_ordered.$errors[0].$message }}
              </span>
            </div>
            <div class="form-control pb-1">
              <label class="label cursor-pointer justify-start gap-4">
                <span class="label-text font-bold">Fill</span>
                <input v-model="CreateOilOrderForm.basicInfo.customer_asked_for_fill" type="checkbox" class="checkbox checkbox-sm" />
              </label>
            </div>
          </div>

          <!-- Date Fields -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label class="label"><span class="label-text font-bold">Order Created Date</span></label>
              <input v-model="CreateOilOrderForm.basicInfo.created_delivery_date" type="date" class="input input-bordered input-sm w-full" />
            </div>
            <div>
              <label class="label"><span class="label-text font-bold">Expected Delivery Date</span></label>
              <input v-model="CreateOilOrderForm.basicInfo.expected_delivery_date" type="date" class="input input-bordered input-sm w-full" />
               <span v-if="v$.CreateOilOrderForm.basicInfo.expected_delivery_date.$error" class="text-red-500 text-xs mt-1">
                {{ v$.CreateOilOrderForm.basicInfo.expected_delivery_date.$errors[0].$message }}
              </span>
            </div>
          </div>

          <!-- Fees & Options -->
          <div class="p-4 border rounded-md">
            <label class="label-text font-bold">Fees & Options</label>
            <div class="flex flex-wrap gap-x-6 gap-y-2 mt-2">
              <div class="form-control"><label class="label cursor-pointer gap-2"><span class="label-text">Prime</span><input v-model="CreateOilOrderForm.basicInfo.prime" type="checkbox" class="checkbox checkbox-xs" /></label></div>
              <div class="form-control"><label class="label cursor-pointer gap-2"><span class="label-text">Emergency</span><input v-model="CreateOilOrderForm.basicInfo.emergency" type="checkbox" class="checkbox checkbox-xs" /></label></div>
              <div class="form-control"><label class="label cursor-pointer gap-2"><span class="label-text">Same Day</span><input v-model="CreateOilOrderForm.basicInfo.same_day" type="checkbox" class="checkbox checkbox-xs" /></label></div>
            </div>
          </div>

          <!-- Payment Type Radio Group -->
          <div class="p-4 border rounded-md space-y-3">
            <label class="label-text font-bold">Payment Method</label>
            <div class="flex flex-wrap gap-x-6 gap-y-2">
              <div class="form-control"><label class="label cursor-pointer gap-2"><span class="label-text">Cash</span><input type="radio" v-model="CreateOilOrderForm.basicInfo.payment_type" :value="0" class="radio radio-xs" /></label></div>
              <div v-if="userCards.length > 0" class="form-control"><label class="label cursor-pointer gap-2"><span class="label-text">Card</span><input type="radio" v-model="CreateOilOrderForm.basicInfo.payment_type" :value="1" class="radio radio-xs" /></label></div>
              <div class="form-control"><label class="label cursor-pointer gap-2"><span class="label-text">Check</span><input type="radio" v-model="CreateOilOrderForm.basicInfo.payment_type" :value="3" class="radio radio-xs" /></label></div>
              <div class="form-control"><label class="label cursor-pointer gap-2"><span class="label-text">Other</span><input type="radio" v-model="CreateOilOrderForm.basicInfo.payment_type" :value="4" class="radio radio-xs" /></label></div>
            </div>
            <!-- Customer Card Selection -->
            <div v-if="userCards.length > 0 && CreateOilOrderForm.basicInfo.payment_type === 1">
              <label class="label"><span class="label-text">Select Card</span></label>
              <select v-model="CreateOilOrderForm.basicInfo.credit_card_id" class="select select-bordered select-sm w-full max-w-xs">
                <option disabled :value="0">Select a card</option>
                <option v-for="card in userCards" :key="card.id" :value="card.id">
                  {{ card.type_of_card }}  {{ card.card_number }}
                </option>
              </select>
            </div>
          </div>

          <!-- Delivery Status & Driver -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label class="label"><span class="label-text font-bold">Delivery Status</span></label>
              <select v-model="CreateOilOrderForm.basicInfo.delivery_status" class="select select-bordered select-sm w-full">
                <option v-for="status in deliveryStatus" :key="status.value" :value="status.value">
                  {{ status.text }}
                </option>
              </select>
            </div>
            <!-- <div>
              <label class="label"><span class="label-text font-bold">Assigned Driver</span></label>
              <select v-model="CreateOilOrderForm.basicInfo.driver_employee_id" class="select select-bordered select-sm w-full">
                <option disabled :value="0">Select a driver</option>
                <option v-for="driver in truckDriversList" :key="driver.id" :value="driver.id">
                  {{ driver.employee_first_name }} {{ driver.employee_last_name }}
                </option>
              </select>
            </div> -->
          </div>

          <!-- Dispatcher Notes -->
          <div>
            <label class="label"><span class="label-text font-bold">Dispatcher Notes</span></label>
            <textarea v-model="CreateOilOrderForm.basicInfo.dispatcher_notes_taken" rows="3" class="textarea textarea-bordered w-full"></textarea>
          </div>

          <!-- Submit Button -->
          <div class="pt-2">
            <button type="submit" class="btn btn-primary btn-sm">Save Changes</button>
          </div>
        </form>
      </div>
    </div>
  </div>
  <Footer />
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import axios from 'axios'
import authHeader from '../../services/auth.header'
import Header from '../../layouts/headers/headerauth.vue'
import SideBar from '../../layouts/sidebar/sidebar.vue'
import Footer from '../../layouts/footers/footer.vue'
import useValidate from "@vuelidate/core";
import { required, minLength } from "@vuelidate/validators";
import { notify } from "@kyvg/vue3-notification";

// Interfaces to describe the shape of your data
interface Customer { account_number: string; id: number; customer_first_name: string; customer_last_name: string; customer_address: string; customer_apt: string; customer_town: string; customer_state: number; customer_zip: string; customer_phone_number: string; }
interface DeliveryOrder { id: string; customer_id: number; payment_type: number; payment_card_id: number; gallons_ordered: number; customer_asked_for_fill: boolean | number; delivery_status: number; driver_employee_id: number; promo_id: number; expected_delivery_date: string; when_ordered: string; prime: boolean | number; emergency: boolean | number; same_day: boolean | number; dispatcher_notes: string; }
interface UserCard { id: number; type_of_card: string; card_number: string; name_on_card: string; expiration_month: string; expiration_year: string; last_four_digits: string; security_number: string; }

const STATE_MAP: { [key: number]: string } = { 0: 'Massachusetts', 1: 'Rhode Island', 2: 'New Hampshire', 3: 'Maine', 4: 'Vermont', 5: 'Connecticut', 6: 'New York' };

export default defineComponent({
  name: 'deliveryEdit',
  components: { Header, SideBar, Footer },
  data() {
    return {
      v$: useValidate(),
      deliveryStatus: [] as any[],
      truckDriversList: [] as any[],
      userCards: [] as UserCard[],
      promos: [] as any[],
      customer: {} as Customer,
      deliveryOrder: {} as DeliveryOrder,
      userCard: {} as UserCard,
      // RESTORED: Add all form fields to the data model
      CreateOilOrderForm: {
        basicInfo: {
          gallons_ordered: '',
          customer_asked_for_fill: false,
          created_delivery_date: '',
          expected_delivery_date: '',
          prime: false,
          emergency: false,
          same_day: false,
          delivery_status: 0,
          driver_employee_id: 0,
          dispatcher_notes_taken: '',
          promo_id: 0,
          payment_type: 0,
          credit_card_id: 0,
        },
      },
    }
  },

  validations() {
    return {
      CreateOilOrderForm: {
        basicInfo: {
          gallons_ordered: { required, minLength: minLength(1) },
          // RESTORED: Add validation for expected date
          expected_delivery_date: { required },
        },
      },
    };
  },
  
  computed: {
    stateName(): string {
      if (this.customer && this.customer.customer_state !== undefined) {
        return STATE_MAP[this.customer.customer_state];
      }
      return '';
    },
  },

  mounted() {
    this.fetchInitialData();
  },

  methods: {
    fetchInitialData() {
      const deliveryId = this.$route.params.id as string;
      this.getPromos();
      this.getDriversList();
      this.getDeliveryStatusList();
      this.getDeliveryOrder(deliveryId);
    },

    getDeliveryOrder(deliveryId: string) {
      axios.get(`${import.meta.env.VITE_BASE_URL}/delivery/order/${deliveryId}`, { withCredentials: true, headers: authHeader() })
        .then((response: any) => {
          // FIX: Check for the 'ok' flag and access the nested 'delivery' object
          if (response.data && response.data.ok) {
            this.deliveryOrder = response.data.delivery; // <-- THIS IS THE CRITICAL CHANGE

            // RESTORED: Populate all form fields from the API response
            this.CreateOilOrderForm.basicInfo = {
              gallons_ordered: String(this.deliveryOrder.gallons_ordered),
              customer_asked_for_fill: !!this.deliveryOrder.customer_asked_for_fill,
              created_delivery_date: this.deliveryOrder.when_ordered,
              expected_delivery_date: this.deliveryOrder.expected_delivery_date,
              prime: !!this.deliveryOrder.prime,
              emergency: !!this.deliveryOrder.emergency,
              same_day: !!this.deliveryOrder.same_day,
              delivery_status: this.deliveryOrder.delivery_status,
              driver_employee_id: this.deliveryOrder.driver_employee_id || 0,
              dispatcher_notes_taken: this.deliveryOrder.dispatcher_notes,
              promo_id: this.deliveryOrder.promo_id || 0,
              payment_type: this.deliveryOrder.payment_type,
              credit_card_id: this.deliveryOrder.payment_card_id || 0,
            };

            this.getCustomer(this.deliveryOrder.customer_id);
          } else {
            console.error("API Error:", response.data.error || "Failed to fetch delivery data.");
          }
        })
        .catch((error: any) => console.error("Error fetching delivery order:", error));
    },

    getCustomer(customerId: number) {
      axios.get(`${import.meta.env.VITE_BASE_URL}/customer/${customerId}`, { withCredentials: true })
        .then((response: any) => {
          this.customer = response.data;
          this.getPaymentCards(customerId);
          if (this.deliveryOrder.payment_type === 1 && this.deliveryOrder.payment_card_id) {
            this.getPaymentCard(this.deliveryOrder.payment_card_id);
          }
        })
        .catch((error: any) => console.error("Error fetching customer:", error));
    },

    getPaymentCards(customerId: number) {
      axios.get(`${import.meta.env.VITE_BASE_URL}/payment/cards/${customerId}`, { withCredentials: true })
        .then((response: any) => { this.userCards = response.data; })
        .catch((error: any) => console.error("Error fetching payment cards:", error));
    },

    getPaymentCard(cardId: number) {
      axios.get(`${import.meta.env.VITE_BASE_URL}/payment/card/${cardId}`, { withCredentials: true })
        .then((response: any) => { this.userCard = response.data; })
        .catch((error: any) => console.error("Error fetching specific payment card:", error));
    },

    getPromos() {
      axios.get(`${import.meta.env.VITE_BASE_URL}/promo/all`, { withCredentials: true })
        .then((response: any) => { this.promos = response.data; });
    },
    getDriversList() {
      axios.get(`${import.meta.env.VITE_BASE_URL}/employee/drivers`, { headers: authHeader(), withCredentials: true })
        .then((response: any) => { this.truckDriversList = response.data; });
    },
    getDeliveryStatusList() {
      axios.get(`${import.meta.env.VITE_BASE_URL}/query/deliverystatus`, { withCredentials: true })
        .then((response: any) => { this.deliveryStatus = response.data; });
    },

    onSubmit() {
      this.v$.$validate();
      if (this.v$.$error) {
        notify({ type: 'error', title: 'Validation Error', text: 'Please check the form fields.' });
        return;
      }
      
      const formInfo = this.CreateOilOrderForm.basicInfo;
      // The payload now automatically includes all the restored fields
      const payload = {
          ...formInfo,
          cash: formInfo.payment_type === 0,
          credit: formInfo.payment_type === 1,
          check: formInfo.payment_type === 3,
          other: formInfo.payment_type === 4,
          credit_card_id: formInfo.payment_type === 1 ? formInfo.credit_card_id : null,
      };

      axios.post(`${import.meta.env.VITE_BASE_URL}/delivery/edit/${this.deliveryOrder.id}`, payload, { withCredentials: true, headers: authHeader() })
        .then(() => {
            notify({ type: 'success', title: 'Success!', text: 'Delivery updated.' });
            this.$router.push({ name: 'deliveryOrder', params: { id: this.deliveryOrder.id } });
        })
        .catch((error: any) => {
          console.error("Error submitting form:", error);
          notify({ type: 'error', title: 'Update Failed', text: 'Could not save changes.' });
        });
    },
  },
})
</script>
