<!-- src/pages/delivery/edit.vue -->
<template>
  <div class="flex">
    <!-- Main container with reduced horizontal padding -->
    <div class="w-full px-4 md:px-6 py-4">
      <!-- Breadcrumbs Navigation -->
      <div class="text-sm breadcrumbs">
        <ul>
          <li><router-link :to="{ name: 'home' }">Home</router-link></li>
          <li>Edit Delivery </li>
        </ul>
      </div>

      <!-- Main Title -->
      <div class="mb-6">
        <h1 class="text-3xl font-bold">Edit Delivery Order #{{ deliveryOrder.id }}</h1>
      </div>


      <!--
        NEW LAYOUT: A single 2-column grid for the whole page.
        Gaps and spacing are reduced for a more compact feel.
      -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 mt-4">

        <!-- LEFT COLUMN: Primary Information & Actions -->
        <div class="space-y-4">

          <!-- 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>

          <!-- Edit Delivery Form (now in the left column) -->
          <div class="bg-neutral rounded-lg p-4">
            <form class="space-y-4" @submit.prevent="onSubmit">
              <!-- Fill Checkbox (moved above Gallons Ordered) -->
              <div class="form-control">
                <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>

              <!-- Gallons Ordered -->
              <div>
                <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="inputClasses(v$.CreateOilOrderForm.basicInfo.gallons_ordered, 'input input-bordered input-sm w-full max-w-xs')" type="number" placeholder="# gallons" />
                <div class="flex flex-wrap gap-2 mt-2">
                  <button v-for="amount in quickGallonAmounts" :key="amount" @click.prevent="setGallons(amount)" :class="['btn', 'btn-xs', selectedGallonsAmount == amount ? 'bg-blue-600 text-white border-blue-600' : 'btn-outline']">{{ amount }} gal</button>
                </div>
                <span v-if="v$.CreateOilOrderForm.basicInfo.gallons_ordered.$error" class="text-red-500 text-xs mt-1">
                  Required unless "Fill" is checked.
                </span>
              </div>

              <!-- Payment Section -->
              <div class="p-4 rounded-md space-y-2 border"
                   :class="{ 'border-red-500 bg-red-50/50': v$.isAnyPaymentMethodSelected.$error }">

                <label class="label-text font-bold">Payment Method</label>

                <div v-if="v$.isAnyPaymentMethodSelected.$error" class="text-red-600 text-sm font-medium">
                  Please select a payment method.
                </div>

                <div class="flex flex-wrap gap-x-6 gap-y-2">
                  <div v-if="userCards.length > 0" class="form-control">
                    <label class="label cursor-pointer gap-2">
                      <span class="label-text">Credit</span>
                      <input v-model="CreateOilOrderForm.basicInfo.credit" type="checkbox" class="checkbox checkbox-xs" />
                    </label>
                  </div>
                  <div class="form-control">
                    <label class="label cursor-pointer gap-2">
                      <span class="label-text">Cash</span>
                      <input v-model="CreateOilOrderForm.basicInfo.cash" type="checkbox" class="checkbox checkbox-xs" />
                    </label>
                  </div>
                  <div class="form-control">
                    <label class="label cursor-pointer gap-2">
                      <span class="label-text">Check</span>
                      <input v-model="CreateOilOrderForm.basicInfo.check" type="checkbox" class="checkbox checkbox-xs" />
                    </label>
                  </div>
                  <div class="form-control">
                    <label class="label cursor-pointer gap-2">
                      <span class="label-text">Other</span>
                      <input v-model="CreateOilOrderForm.basicInfo.other" type="checkbox" class="checkbox checkbox-xs" />
                    </label>
                  </div>
                </div>

                <div v-if="userCards.length > 0 && CreateOilOrderForm.basicInfo.credit">
                  <label class="label"><span class="label-text">Select Card</span></label>
                  <div class="flex flex-wrap gap-2 mt-2">
                    <button v-for="card in userCards" :key="card.id" @click.prevent="selectCreditCard(card.id)" :class="['btn', 'btn-xs', CreateOilOrderForm.basicInfo.credit_card_id === card.id ? 'bg-blue-600 text-white border-blue-600' : 'btn-outline']">{{ card.type_of_card }} - ****{{ card.last_four_digits }}</button>
                  </div>
                  <span v-if="v$.CreateOilOrderForm.basicInfo.credit_card_id.$error" class="text-red-500 text-xs mt-1">
                    You must select a credit card when choosing CC option.
                  </span>
                </div>
                <div v-if="userCards.length === 0" class="text-sm text-warning">No cards on file for credit payment.</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="inputClasses(v$.CreateOilOrderForm.basicInfo.expected_delivery_date)" />
                  <div class="flex flex-wrap gap-2 mt-2">
                    <button @click.prevent="setDeliveryDate(0)" :class="['btn', 'btn-xs', isDeliveryDateSelected(0) ? 'bg-blue-600 text-white border-blue-600' : 'btn-outline']">Today</button>
                    <button @click.prevent="setDeliveryDate(1)" :class="['btn', 'btn-xs', isDeliveryDateSelected(1) ? 'bg-blue-600 text-white border-blue-600' : 'btn-outline']">Tomorrow</button>
                    <button @click.prevent="setDeliveryDate(2)" :class="['btn', 'btn-xs', isDeliveryDateSelected(2) ? 'bg-blue-600 text-white border-blue-600' : 'btn-outline']">In 2 Days</button>
                    <button @click.prevent="setDeliveryDate(3)" :class="['btn', 'btn-xs', isDeliveryDateSelected(3) ? 'bg-blue-600 text-white border-blue-600' : 'btn-outline']">In 3 Days</button>
                  </div>
                  <span v-if="v$.CreateOilOrderForm.basicInfo.expected_delivery_date.$error" class="text-red-500 text-xs mt-1">Date is required.</span>
                </div>
              </div>

              <!-- Optional Section Divider -->
              <div class="flex items-center my-4">
                <div class="flex-grow h-px bg-gray-300"></div>
                <span class="px-3 text-gray-500 text-sm font-medium">Optional</span>
                <div class="flex-grow h-px bg-gray-300"></div>
              </div>

              <div>
                <label class="label"><span class="label-text font-bold">Apply Promotion</span></label>
                <select class="select select-bordered select-sm w-full max-w-xs" v-model="CreateOilOrderForm.basicInfo.promo_id">
                    <option :value="0">No Promotion</option>
                    <option v-for="promo in promos" :key="promo.id" :value="promo.id">
                        {{ promo.name_of_promotion }} (${{ promo.money_off_delivery }} off)
                    </option>
                </select>
              </div>

              <!-- Fees & Options (Tier Selection) -->
              <div class="p-4 rounded-md space-y-2">
                  <label class="label-text font-bold">Fees & Options (Select Tier)</label>
                  <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mt-3">
                      <!-- Same Day Tier -->
                      <div class="form-control">
                        <label class="label"><span class="label-text">Same Day</span></label>
                        <select v-model.number="CreateOilOrderForm.basicInfo.pricing_tier_same_day" class="select select-bordered select-sm w-full">
                          <option :value="0">None</option>
                          <option :value="1">Tier 1 ({{ formatCurrency(tierPricing.same_day_tier1) }})</option>
                          <option :value="2">Tier 2 ({{ formatCurrency(tierPricing.same_day_tier2) }})</option>
                          <option :value="3">Tier 3 ({{ formatCurrency(tierPricing.same_day_tier3) }})</option>
                          <option :value="4">Tier 4 ({{ formatCurrency(tierPricing.same_day_tier4) }})</option>
                          <option :value="5">Tier 5 ({{ formatCurrency(tierPricing.same_day_tier5) }})</option>
                        </select>
                      </div>
                      <!-- Prime Tier -->
                      <div class="form-control">
                        <label class="label"><span class="label-text">Prime</span></label>
                        <select v-model.number="CreateOilOrderForm.basicInfo.pricing_tier_prime" class="select select-bordered select-sm w-full">
                          <option :value="0">None</option>
                          <option :value="1">Tier 1 ({{ formatCurrency(tierPricing.prime_tier1) }})</option>
                          <option :value="2">Tier 2 ({{ formatCurrency(tierPricing.prime_tier2) }})</option>
                          <option :value="3">Tier 3 ({{ formatCurrency(tierPricing.prime_tier3) }})</option>
                          <option :value="4">Tier 4 ({{ formatCurrency(tierPricing.prime_tier4) }})</option>
                          <option :value="5">Tier 5 ({{ formatCurrency(tierPricing.prime_tier5) }})</option>
                        </select>
                      </div>
                      <!-- Emergency Tier -->
                      <div class="form-control">
                        <label class="label"><span class="label-text">Emergency</span></label>
                        <select v-model.number="CreateOilOrderForm.basicInfo.pricing_tier_emergency" class="select select-bordered select-sm w-full">
                          <option :value="0">None</option>
                          <option :value="1">Tier 1 ({{ formatCurrency(tierPricing.emergency_tier1) }})</option>
                          <option :value="2">Tier 2 ({{ formatCurrency(tierPricing.emergency_tier2) }})</option>
                          <option :value="3">Tier 3 ({{ formatCurrency(tierPricing.emergency_tier3) }})</option>
                          <option :value="4">Tier 4 ({{ formatCurrency(tierPricing.emergency_tier4) }})</option>
                          <option :value="5">Tier 5 ({{ formatCurrency(tierPricing.emergency_tier5) }})</option>
                        </select>
                      </div>
                  </div>
              </div>


              <!-- 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" placeholder="Notes for the driver..."></textarea>
              </div>

              <button type="submit" class="btn btn-primary btn-sm">Save Changes</button>
            </form>
          </div>

        </div>

        <!-- RIGHT COLUMN: Reference Information & Secondary Actions -->
        <div class="space-y-4">

          <!-- Pricing Chart Card -->
          <div class="bg-neutral rounded-lg p-5">
            <h3 class="text-xl font-bold mb-4">Today's Price Per Gallon</h3>
            <div class="overflow-x-auto">
              <table class="table table-sm w-full">
                <thead>
                  <tr>
                    <th>Gallons</th>
                    <th>Total Price</th>
                  </tr>
                </thead>
                <tbody>
                   <tr v-for="tier in pricingTiers" :key="tier.gallons" :class="isPricingTierSelected(tier.gallons) ? 'bg-blue-600 text-white hover:bg-blue-600' : 'hover'">
                      <td>{{ tier.gallons }}</td>
                      <td>${{ Number(tier.price).toFixed(2) }}</td>
                   </tr>
                </tbody>
              </table>
            </div>
          </div>

          <!-- Credit Cards Display -->
          <div v-if="customer && customer.id" class="bg-neutral rounded-lg p-5">
            <div class="flex justify-between items-center">
              <h2 class="text-xl font-bold">Credit Cards</h2>
              <router-link :to="{ name: 'cardadd', params: { id: customer.id } }">
                <button class="btn btn-xs btn-outline btn-success">Add New</button>
              </router-link>
            </div>
            <div class="mt-2 text-sm" v-if="userCards.length === 0">
                <p class="text-warning font-semibold">No cards on file.</p>
            </div>
            <div class="mt-4 space-y-3">
              <div v-for="card in userCards" :key="card.id" class="p-3 rounded-lg border" :class="card.main_card ? 'bg-primary/10 border-primary' : 'bg-base-200 border-base-300'">
                <div class="flex justify-between items-start">
                  <div>
                    <div class="font-bold text-sm">{{ card.name_on_card }}</div>
                    <div class="text-xs opacity-70">{{ card.type_of_card }}</div>
                  </div>
                  <div v-if="card.main_card" class="badge badge-primary badge-sm">Primary</div>
                </div>
                <div class="mt-2 text-sm font-mono tracking-wider">
                  <p>{{ card.card_number }}</p>
                  <p>Exp: <span v-if="Number(card.expiration_month) < 10">0</span>{{ card.expiration_month }} / {{ card.expiration_year }}</p>
                  <p>CVV: {{ card.security_number }}</p>
                </div>
                <div class="flex justify-end gap-2 mt-2">
                  <a @click.prevent="editCard(card.id)" class="link link-hover text-xs">Edit</a>
                  <a @click.prevent="removeCard(card.id)" class="link link-hover text-error text-xs">Remove</a>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>
    </div>
  </div>
  
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Customer, CreditCard } from '../../types/models'
import Header from '../../layouts/headers/headerauth.vue'
import SideBar from '../../layouts/sidebar/sidebar.vue'
import { useVuelidate } from "@vuelidate/core";
import { required, requiredIf } from "@vuelidate/validators";
import { notify } from "@kyvg/vue3-notification";
import { useFormValidation } from '../../composables/useFormValidation';
import deliveryService from '../../services/deliveryService';

const { inputClasses, selectClasses } = useFormValidation();
import customerService from '../../services/customerService';
import paymentService from '../../services/paymentService';
import adminService from '../../services/adminService';
import queryService from '../../services/queryService';

// Interfaces to describe the shape of your data
// Interfaces to describe the shape of your data
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; 
  pricing_tier_same_day?: number; pricing_tier_prime?: number; pricing_tier_emergency?: number;
}
interface PricingTier { gallons: number; price: string | number; }

const router = useRouter()
const route = useRoute()

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

// Reactive data
const quickGallonAmounts = ref([100, 125, 150, 175, 200, 220])
const deliveryStatus = ref([] as any[])
const truckDriversList = ref([] as any[])
const userCards = ref<CreditCard[]>([])
const promos = ref([] as any[])
const pricingTiers = ref([] as PricingTier[])
const customer = ref({} as Customer)
const deliveryOrder = ref({} as DeliveryOrder)
const userCard = ref({} as CreditCard)
// RESTORED: Add all form fields to the data model
const CreateOilOrderForm = ref({
  basicInfo: {
    gallons_ordered: '',
    customer_asked_for_fill: false,
    created_delivery_date: '',
    expected_delivery_date: '',
    prime: false,
    emergency: false,
    same_day: false,
    pricing_tier_same_day: 0,
    pricing_tier_prime: 0,
    pricing_tier_emergency: 0,
    delivery_status: 0,
    driver_employee_id: 0,
    dispatcher_notes_taken: '',
    promo_id: 0,
    payment_type: 0,
    credit_card_id: 0,
    credit: false,
    cash: false,
    check: false,
    other: false,
  },
})

// Tier pricing from API
const tierPricing = ref({
  same_day_tier1: 0, same_day_tier2: 0, same_day_tier3: 0, same_day_tier4: 0, same_day_tier5: 0,
  prime_tier1: 0, prime_tier2: 0, prime_tier3: 0, prime_tier4: 0, prime_tier5: 0,
  emergency_tier1: 0, emergency_tier2: 0, emergency_tier3: 0, emergency_tier4: 0, emergency_tier5: 0,
})

// Computed
const stateName = computed((): string => {
  if (customer.value && customer.value.customer_state !== undefined) {
    return STATE_MAP[customer.value.customer_state];
  }
  return '';
})

const isPricingTierSelected = computed(() => {
  return (tierGallons: number | string): boolean => {
    if (!CreateOilOrderForm.value.basicInfo.gallons_ordered) return false;
    const selectedGallons = Number(CreateOilOrderForm.value.basicInfo.gallons_ordered);
    if (isNaN(selectedGallons)) return false;

    const tierNum = Number(tierGallons);
    if (isNaN(tierNum)) return false;

    return selectedGallons === tierNum;
  };
})

const formatCurrency = (value: number | string | undefined) => {
  if (value === undefined || value === null) return '$0.00';
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
  }).format(Number(value));
}

const isAnyPaymentMethodSelected = computed((): boolean => {
  return !!(CreateOilOrderForm.value.basicInfo?.credit || CreateOilOrderForm.value.basicInfo?.cash || CreateOilOrderForm.value.basicInfo?.check || CreateOilOrderForm.value.basicInfo?.other);
})

const selectedGallonsAmount = computed((): number => {
  const value = CreateOilOrderForm.value.basicInfo.gallons_ordered ?? '';
  return Number(value);
})

// Validations
const validations = {
  CreateOilOrderForm: {
    basicInfo: {
      gallons_ordered: {
        required: requiredIf(() => !CreateOilOrderForm.value.basicInfo.customer_asked_for_fill),
        minValue: (value: string) => {
          if (CreateOilOrderForm.value.basicInfo.customer_asked_for_fill) return true;
          if (!value) return true; // if empty, required will catch it
          const num = parseInt(value, 10);
          return num >= 1;
        }
      },
      expected_delivery_date: { required },
      credit_card_id: {
        creditCardRequired: (value: number) => {
          if (CreateOilOrderForm.value.basicInfo.credit) {
            return value !== 0;
          }
          return true;
        }
      },
    },
  },
  isAnyPaymentMethodSelected: {
    mustBeTrue: (value: boolean) => value === true,
  },
}

const v$ = useVuelidate(validations, { CreateOilOrderForm, isAnyPaymentMethodSelected })

// Functions
const fetchInitialData = () => {
  const deliveryId = route.params.id as string;
  getPromos();
  getDriversList();
  getDeliveryStatusList();
  getPricingTiers();
  getDeliveryOrder(deliveryId);
}

const getDeliveryOrder = async (deliveryId: string) => {
  try {
    const response = await deliveryService.getOrder(Number(deliveryId));
    if (response.data && response.data.ok) {
        deliveryOrder.value = response.data.delivery as unknown as DeliveryOrder;

        // RESTORED: Populate all form fields from the API response
        const paymentType = deliveryOrder.value.payment_type;
        CreateOilOrderForm.value.basicInfo = {
          gallons_ordered: String(deliveryOrder.value.gallons_ordered),
          customer_asked_for_fill: !!deliveryOrder.value.customer_asked_for_fill,
          created_delivery_date: deliveryOrder.value.when_ordered,
          expected_delivery_date: deliveryOrder.value.expected_delivery_date,
          // Set tiers from delivery order
          pricing_tier_same_day: deliveryOrder.value.pricing_tier_same_day || (deliveryOrder.value.same_day ? 1 : 0),
          pricing_tier_prime: deliveryOrder.value.pricing_tier_prime || (deliveryOrder.value.prime ? 1 : 0),
          pricing_tier_emergency: deliveryOrder.value.pricing_tier_emergency || (deliveryOrder.value.emergency ? 1 : 0),
          
          // Set boolean flags for type compatibility and logic
          same_day: !!deliveryOrder.value.same_day,
          prime: !!deliveryOrder.value.prime,
          emergency: !!deliveryOrder.value.emergency,

          delivery_status: deliveryOrder.value.delivery_status,
          driver_employee_id: deliveryOrder.value.driver_employee_id || 0,
          dispatcher_notes_taken: deliveryOrder.value.dispatcher_notes,
          promo_id: deliveryOrder.value.promo_id || 0,
          payment_type: paymentType,
          credit_card_id: deliveryOrder.value.payment_card_id || 0,
          // Set the correct payment method checkbox based on payment_type
          credit: paymentType === 1,
          cash: paymentType === 0,
          check: paymentType === 3,
          other: paymentType === 4,
        };

        getCustomer(deliveryOrder.value.customer_id);
    } else {
        console.error("API Error: Failed to fetch delivery data.");
    }
  } catch (error) {
     console.error("Error fetching delivery order:", error);
  }
}

const getCustomer = async (customerId: number) => {
  try {
    const response = await customerService.getById(customerId);
    customer.value = response.data.customer; 
    getPaymentCards(customerId);
    if (deliveryOrder.value.payment_type === 1 && deliveryOrder.value.payment_card_id) {
      getPaymentCard(deliveryOrder.value.payment_card_id);
    }
  } catch (error) {
    console.error("Error fetching customer:", error);
  }
}

const getPaymentCards = async (customerId: number) => {
    try {
        const response = await paymentService.getCards(customerId);
        userCards.value = response.data.cards;
    } catch (error) {
        console.error("Error fetching payment cards:", error);
    }
}

const getPaymentCard = async (cardId: number) => {
    try {
        const response = await paymentService.getCard(cardId);
        userCard.value = response.data.card;
    } catch (error) {
        console.error("Error fetching specific payment card:", error);
    }
}

const getPromos = async () => {
    try {
        const response = await adminService.promos.getAll();
        promos.value = response.data.promos || (response.data as any); // Assuming wrapper or direct array
    } catch (error) {
        console.error("Error fetching promos:", error);
    }
}

const getDriversList = async () => {
    try {
        const response = await adminService.employees.getDrivers();
        truckDriversList.value = response.data.drivers || (response.data as any);
    } catch (error) {
         console.error("Error fetching drivers:", error);
    }
}

const getDeliveryStatusList = async () => {
    try {
        const response = await queryService.getDeliveryStatuses();
        deliveryStatus.value = (response.data as any).statuses || response.data;
    } catch (error) {
        console.error("Error fetching delivery statuses:", error);
    }
}

const getPricingTiers = async () => {
    try {
        const response = await queryService.getOilPriceTiers();
        const tiersObject = (response.data as any).pricing_tiers || response.data;
        pricingTiers.value = Object.entries(tiersObject).map(([gallons, price]) => ({
            gallons: parseInt(gallons, 10),
            price: price as string | number,
        }));
        
        // Fetch full pricing table for dropdowns
        const tableResponse = await queryService.getOilPriceTable();
        const data = tableResponse.data.pricing;
        if (data) {
          tierPricing.value = {
            same_day_tier1: data.price_same_day_tier1 || data.price_same_day,
            same_day_tier2: data.price_same_day_tier2,
            same_day_tier3: data.price_same_day_tier3,
            same_day_tier4: data.price_same_day_tier4,
            same_day_tier5: data.price_same_day_tier5,
            
            prime_tier1: data.price_prime_tier1 || data.price_prime,
            prime_tier2: data.price_prime_tier2,
            prime_tier3: data.price_prime_tier3,
            prime_tier4: data.price_prime_tier4,
            prime_tier5: data.price_prime_tier5,
            
            emergency_tier1: data.price_emergency_tier1 || data.price_emergency,
            emergency_tier2: data.price_emergency_tier2,
            emergency_tier3: data.price_emergency_tier3,
            emergency_tier4: data.price_emergency_tier4,
            emergency_tier5: data.price_emergency_tier5,
          };
        }
    } catch (error) {
        notify({ title: "Pricing Error", text: "Could not retrieve today's pricing.", type: "error" });
    }
}

const editCard = (card_id: number) => {
  router.push({ name: "cardedit", params: { id: card_id } });
}

const removeCard = async (card_id: number) => {
  if (window.confirm("Are you sure you want to remove this card?")) {
      try {
          await paymentService.removeCard(card_id);
          notify({ title: "Card Removed", type: "success" });
          getPaymentCards(customer.value.id);
      } catch (error) {
           notify({ title: "Error", text: "Could not remove card.", type: "error" });
      }
  }
}

const selectCreditCard = (cardId: number) => {
  CreateOilOrderForm.value.basicInfo.credit_card_id = cardId;
}

const setGallons = (amount: number) => {
  CreateOilOrderForm.value.basicInfo.gallons_ordered = String(amount);
  CreateOilOrderForm.value.basicInfo.customer_asked_for_fill = false;
}

const setDeliveryDate = (days: number) => {
  const date = new Date();
  date.setDate(date.getDate() + days);
  CreateOilOrderForm.value.basicInfo.expected_delivery_date = date.toISOString().split('T')[0];
}

const isDeliveryDateSelected = (days: number): boolean => {
  const date = new Date();
  date.setDate(date.getDate() + days);
  return CreateOilOrderForm.value.basicInfo.expected_delivery_date === date.toISOString().split('T')[0];
}

const onSubmit = async () => {
  const isFormValid = await v$.value.CreateOilOrderForm.$validate();
  const isPaymentValid = await v$.value.isAnyPaymentMethodSelected.$validate();

  if (!isFormValid || !isPaymentValid) {
    notify({ title: "Form Incomplete", text: "Please review the fields marked in red.", type: "warn" });
    return;
  }

  const formInfo = CreateOilOrderForm.value.basicInfo;
  // Convert checkboxes back to payment_type number for API
  let paymentType = 0; // Default to cash
  if (formInfo.credit) paymentType = 1;
  else if (formInfo.cash) paymentType = 0;
  else if (formInfo.other) paymentType = 4;
  else if (formInfo.check) paymentType = 3;

  // Update boolean flags based on tier selection
  formInfo.same_day = formInfo.pricing_tier_same_day > 0;
  formInfo.prime = formInfo.pricing_tier_prime > 0;
  formInfo.emergency = formInfo.pricing_tier_emergency > 0;

  // The payload now automatically includes all the restored fields
  const payload = {
      ...formInfo,
      payment_type: paymentType,
      cash: formInfo.cash,
      credit: formInfo.credit,
      check: formInfo.check,
      other: formInfo.other,
      credit_card_id: formInfo.credit ? formInfo.credit_card_id : null,
  };

  try {
      await deliveryService.update(Number(deliveryOrder.value.id), payload as any);
      notify({ type: 'success', title: 'Success!', text: 'Delivery updated.' });
      if (paymentType === 1) {
          router.push({ name: 'payOil', params: { id: deliveryOrder.value.id } });
      } else {
          router.push({ name: 'deliveryOrder', params: { id: deliveryOrder.value.id } });
      }
  } catch (error) {
      console.error("Error submitting form:", error);
      notify({ type: 'error', title: 'Update Failed', text: 'Could not save changes.' });
  }
}

// Lifecycle
onMounted(() => {
  fetchInitialData();
})
</script>
