<!-- src/pages/delivery/view.vue -->
<template>
  <div class="flex">
    <!-- Main Content -->
    <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><router-link :to="{ name: 'customer' }">Customers</router-link></li>
          <li>View Delivery</li>
        </ul>
      </div>
      <h1 class="text-3xl font-bold mt-4 border-b border-gray-600 pb-2">
        Delivery #{{ deliveryOrder.id }}
      </h1>

      <!-- TOP SECTION: Customer & Status Info -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 my-6">
        <!-- Customer Info Card -->
        <div 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>
            <!-- 
              FIX #1: Add a v-if guard. 
              This prevents the link from rendering until `customer.user_id` has a valid, non-zero value.
            -->
            <router-link v-if="customer " :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'">Apt: {{ customer.customer_apt }}</div>
            <div>
              {{ customer.customer_town }},
              <span v-if="customer.customer_state == 0">Massachusetts</span>
              <span v-else-if="customer.customer_state == 1">Rhode Island</span>
              <span v-else-if="customer.customer_state == 2">New Hampshire</span>
              <span v-else-if="customer.customer_state == 3">Maine</span>
              <span v-else-if="customer.customer_state == 4">Vermont</span>
              <span v-else-if="customer.customer_state == 5">Connecticut</span>
              <span v-else-if="customer.customer_state == 6">New York</span>
              <span v-else>Unknown state</span>
              {{ customer.customer_zip }}
            </div>
            <div class="text-sm text-gray-400 mt-1">
              <span v-if="customer.customer_home_type == 0">Residential</span>
              <span v-else-if="customer.customer_home_type == 1">Apartment</span>
              <span v-else-if="customer.customer_home_type == 2">Condo</span>
              <span v-else-if="customer.customer_home_type == 3">Commercial</span>
              <span v-else-if="customer.customer_home_type == 4">Business</span>
              <span v-else-if="customer.customer_home_type == 5">Construction</span>
              <span v-else-if="customer.customer_home_type == 6">Container</span>
            </div>
            <div class="mt-2">{{ customer.customer_phone_number }}</div>
          </div>
        </div>

        <!-- Delivery Status Card -->
        <div class="bg-neutral rounded-lg p-5">
          <div class="grid grid-cols-2 gap-4">
            <div class="col-span-2">
              <div class="font-bold text-sm">Current Status</div>
              <div class="badge badge-lg"
                   :class="{
                     'badge-success': [DELIVERY_STATUS.DELIVERED, DELIVERY_STATUS.FINALIZED].includes(deliveryOrder.delivery_status as any),
                     'badge-info': deliveryOrder.delivery_status == DELIVERY_STATUS.OUT_FOR_DELIVERY,
                     'badge-error': deliveryOrder.delivery_status == DELIVERY_STATUS.ISSUE,
                     'badge-warning': ![DELIVERY_STATUS.DELIVERED, DELIVERY_STATUS.FINALIZED, DELIVERY_STATUS.OUT_FOR_DELIVERY, DELIVERY_STATUS.ISSUE].includes(deliveryOrder.delivery_status as any)
                   }">
                <span v-if="deliveryOrder.delivery_status == DELIVERY_STATUS.WAITING">Waiting</span>
                <span v-else-if="deliveryOrder.delivery_status == DELIVERY_STATUS.DELIVERED">Delivered</span>
                <span v-else-if="deliveryOrder.delivery_status == DELIVERY_STATUS.OUT_FOR_DELIVERY">Out_for_Delivery</span>
                <span v-else-if="deliveryOrder.delivery_status == DELIVERY_STATUS.TOMORROW">Tomorrow</span>
                <span v-else-if="deliveryOrder.delivery_status == DELIVERY_STATUS.PARTIAL_DELIVERY">Partial Delivery</span>
                <span v-else-if="deliveryOrder.delivery_status == DELIVERY_STATUS.ISSUE">Misdelivery</span>
                <span v-else-if="deliveryOrder.delivery_status == DELIVERY_STATUS.UNKNOWN">Unknown</span>
                <span v-else-if="deliveryOrder.delivery_status == DELIVERY_STATUS.PENDING_PAYMENT">Pending</span>
                <span v-else-if="deliveryOrder.delivery_status == DELIVERY_STATUS.FINALIZED">Finalized</span>
              </div>
            </div>
            <div>
              <div class="font-bold text-sm">Scheduled Date</div>
              <div>{{ deliveryOrder.expected_delivery_date }}</div>
            </div>
            <div v-if="deliveryOrder.delivery_status === 10">
              <div class="font-bold text-sm">Date Delivered</div>
              <div>{{ (deliveryOrder.when_delivered) }}</div>
            </div>
            <div class="col-span-2">
              <div class="font-bold text-sm">Date Ordered</div>
              <div>{{ (deliveryOrder.when_ordered) }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- BOTTOM SECTION: Delivery & Financial Details -->
      <div class="bg-neutral rounded-lg p-6">
        <div class="grid grid-cols-1 xl:grid-cols-2 gap-8">
          <!-- Left Column: Pricing, Gallons, Promo -->
          <div class="space-y-4">
            <!-- Gallons -->
            <div class="p-4 border rounded-md">
              <div class="grid grid-cols-2 gap-4">
                <div>
                  <label class="label-text font-bold">Gallons Ordered</label>
                  <div class="text-lg mt-1">
                    <span v-if="deliveryOrder.customer_asked_for_fill == 1" class="badge badge-lg badge-info">FILL</span>
                    <span v-else>{{ deliveryOrder.gallons_ordered }} gallons</span>
                  </div>
                </div>
                <div>
                  <label class="label-text font-bold">Gallons Delivered</label>
                  <div class="text-lg mt-1">
                    <span v-if="!deliveryOrder.gallons_delivered || deliveryOrder.gallons_delivered == ''">0 gallons</span>
                    <span v-else>{{ deliveryOrder.gallons_delivered }} gallons</span>
                  </div>
                </div>
              </div>
            </div>

              <!-- Pricing & Fees -->
            <div class="p-4 border rounded-md space-y-2">
              <label class="label-text font-bold">Estimated Total</label>
              <!-- Total Breakdown -->
              <div class="space-y-2">
                <!-- Show breakdown only when promo is active -->
                <div v-if="promo && promo.name_of_promotion">
                  <!-- Oil & Fees Total (before discount) -->
                  <div class="flex justify-between items-center text-sm">
                    <span>Oil & Fees Total</span>
                    <span>${{ calculateEstimatedTotal().toFixed(2) }}</span>
                  </div>
                  <!-- Promo Discount -->
                  <div class="flex justify-between items-center text-sm text-success">
                    <span>{{ promo.name_of_promotion }}</span>
                    <span>-${{ discount.toFixed(2) }}</span>
                  </div>
                </div>
                <!-- Final Charge Amount (always show) -->
                <div class="flex justify-between items-center">
                  <span class="text-lg font-bold">
                    Estimated Charge Amount
                  </span>
                  <span class="text-2xl font-bold text-success">
                    ${{ (promo && promo.name_of_promotion ? (calculateEstimatedTotal() - discount).toFixed(2) : calculateEstimatedTotal().toFixed(2)) }}
                  </span>
                </div>
              </div>
              <!-- Fee Details (show regardless of promo) -->
              <div v-if="deliveryOrder.prime == 1" class="text-sm text-gray-400">+ ${{ pricing.price_prime }} Prime Fee</div>
              <div v-if="deliveryOrder.emergency == 1" class="text-sm text-gray-400">+ ${{ pricing.price_emergency }} Emergency Fee</div>
              <div v-if="deliveryOrder.same_day == 1" class="text-sm text-gray-400">+ ${{ pricing.price_same_day }} Same Day Fee</div>
            </div>

            <!-- Transaction Summary -->
            <div v-if="deliveryOrder.payment_type == 11" class="p-4 border rounded-md">
              <label class="label-text font-bold">Authorize.net Transaction Details</label>
              <div v-if="transaction" class="mt-2 space-y-2">
                <div class="flex justify-between">
                  <span class="font-bold">Transaction ID:</span>
                  <span class="font-mono">{{ transaction.auth_net_transaction_id || 'N/A' }}</span>
                </div>
                <div class="flex justify-between">
                  <span>Pre-Auth Amount:</span>
                  <span>${{ transaction.preauthorize_amount || '0.00' }}</span>
                </div>
                <div class="flex justify-between">
                  <span>Charge Amount:</span>
                  <span>${{ transaction.charge_amount || '0.00' }}</span>
                </div>
                <div class="flex justify-between">
                  <span>Type:</span>
                  <span :class="getTypeColor(transaction.transaction_type)">
                    {{ transaction.transaction_type === 0 ? 'Charge' : transaction.transaction_type === 1 ? 'Auth' : transaction.transaction_type === 2 ? 'Capture' : 'Other' }}
                  </span>
                </div>
                <div class="flex justify-between">
                  <span>Date:</span>
                  <span>{{ format_date(transaction.created_at) }}</span>
                </div>
                <div class="flex justify-between">
                  <span>Status:</span>
                  <span :class="transaction.status === 0 ? 'text-success' : 'text-error'">
                    {{ transaction.status === 0 ? 'Approved' : 'Declined' }}
                  </span>
                </div>
              </div>
              <div v-else class="mt-2 text-gray-500">
                No authorize.net transaction data available
              </div>
            </div>

            <!-- Simple Payment Display for Other Types -->
            <div v-else-if="deliveryOrder.payment_type == 1" class="p-4 border rounded-md">
              <label class="label-text font-bold">Payment Method</label>
              <div class="mt-2">
                <span class="text-info font-semibold">Processed via Tiger Card Machine</span>
              </div>
            </div>

            <!-- Delivery Summary -->
            <div v-if="deliveryOrder.gallons_delivered && parseFloat(deliveryOrder.gallons_delivered) > 0" class="p-4 border rounded-md">
              <label class="label-text font-bold">Delivery Summary FINAL</label>
              <div class="space-y-2 mt-2">
                <div class="flex justify-between">
                  <span>Gallons Delivered:</span>
                  <span class="font-semibold">{{ deliveryOrder.gallons_delivered }} gallons</span>
                </div>
                <div class="flex justify-between">
                  <span>Price per Gallon:</span>
                  <span class="font-semibold">${{ pricing.price_for_customer }}</span>
                </div>
                <div class="flex justify-between">
                  <span>Subtotal:</span>
                  <span class="font-semibold">${{ (parseFloat(deliveryOrder.gallons_delivered) * pricing.price_for_customer).toFixed(2) }}</span>
                </div>
                <div v-if="deliveryOrder.prime == 1" class="flex justify-between text-sm">
                  <span>Prime Fee:</span>
                  <span>+ ${{ pricing.price_prime }}</span>
                </div>
                <div v-if="deliveryOrder.same_day == 1" class="flex justify-between text-sm">
                  <span>Same Day Fee:</span>
                  <span>+ ${{ pricing.price_same_day }}</span>
                </div>
                <div v-if="deliveryOrder.emergency == 1" class="flex justify-between text-sm">
                  <span>Emergency Fee:</span>
                  <span>+ ${{ pricing.price_emergency }}</span>
                </div>
                <hr class="my-2">
                <!-- Show promo breakdown for delivered amounts -->
                <div v-if="promo && promo.name_of_promotion">
                  <div class="flex justify-between text-sm">
                    <span>Delivered Total (before discount):</span>
                    <span>${{ calculateDeliveryTotal() }}</span>
                  </div>
                  <div class="flex justify-between text-sm text-success">
                    <span>{{ promo.name_of_promotion }}</span>
                    <span>-${{ discount.toFixed(2) }}</span>
                  </div>
                </div>
                <div class="flex justify-between font-bold">
                  <span>Total:</span>
                  <span>${{ (promo && promo.name_of_promotion ? (parseFloat(calculateDeliveryTotal()) - discount).toFixed(2) : calculateDeliveryTotal()) }}</span>
                </div>
              </div>
            </div>

          

            <!-- Promotion -->
            <div v-if="deliveryOrder.promo_id !== null && deliveryOrder.delivery_status !== 10" class="p-4 border rounded-md">
              <label class="label-text font-bold">Promotion Applied</label>
              <div class="mt-1">
                <div class="font-semibold">{{ promo.name_of_promotion }} (${{ promo.money_off_delivery }} off)</div>
                <div class="text-sm text-gray-400">{{ promo.description }}</div>
              </div>
            </div>
          </div>

    <div class="space-y-4">
          <!-- 
            START: Replaced Payment Section 
          -->
          <div class="p-4 border rounded-md">
            <label class="label-text font-bold">Payment Method</label>
            <div class="mt-1">
              <div class="text-lg">
                <span v-if="deliveryOrder.payment_type == 0">Cash</span>
                <span v-else-if="deliveryOrder.payment_type == 1">Tiger Card Machine</span>
                <span v-else-if="deliveryOrder.payment_type == 11">Authorize.net PCI Card API</span>
                <span v-else-if="deliveryOrder.payment_type == 2">Credit Card & Cash</span>
                <span v-else-if="deliveryOrder.payment_type == 3">Check</span>
                <span v-else-if="deliveryOrder.payment_type == 4">Other</span>
                <span v-else>Not Specified</span>
              </div>
              
              <!--
                This is the new, styled card display.
                It uses the same logic but applies the better CSS classes.
              -->
              <div v-if="userCardfound && [1, 2, 3].includes(deliveryOrder.payment_type)"
                  class="p-4 rounded-lg border mt-2" 
                  :class="userCard.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">{{ userCard.name_on_card }}</div>
                    <div class="text-xs opacity-70">{{ userCard.type_of_card }}</div>
                  </div>
                  <div v-if="userCard.main_card" class="badge badge-primary badge-sm">Primary</div>
                </div>
                
                <div class="mt-3 text-sm font-mono tracking-wider">
                  <!-- Using last_four_digits is more secure and looks cleaner -->
                  <p>{{ userCard.card_number }}</p>
                  <p>
                    Exp:
                    <!-- Adds a leading zero for single-digit months -->
                  <span v-if="Number(userCard.expiration_month) < 10">0</span>{{ userCard.expiration_month }} / {{ userCard.expiration_year }}
                  </p>
                  <p>CVV: {{ userCard.security_number }}</p>
                </div>
              </div>
            </div>
          </div>



            <!-- Notes & Options -->
            <div class="p-4 border rounded-md">
              <label class="label-text font-bold">Notes & Options</label>
              <div class="mt-2 space-y-1 text-sm">
                <div><span class="font-semibold">Prime Required:</span> {{ deliveryOrder.prime ? 'Yes' : 'No' }}</div>
                <div><span class="font-semibold">Same Day:</span> {{ deliveryOrder.same_day ? 'Yes' : 'No' }}</div>
                <div><span class="font-semibold">Emergency:</span> {{ deliveryOrder.emergency ? 'Yes' : 'No' }}</div>
              </div>
              <div class="prose prose-sm mt-4 max-w-none">
                <blockquote class="text-gray-400">{{ deliveryOrder.dispatcher_notes || 'No dispatcher notes provided.' }}</blockquote>
              </div>
            </div>
            
            <!-- 
              FIX #2: Add a v-if guard to the container. 
              This prevents the links from rendering until `deliveryOrder.id` is available.
            -->
            <div v-if="deliveryOrder && deliveryOrder.id" class="flex flex-wrap gap-2 pt-4">
              <router-link v-if="deliveryOrder.delivery_status !== 10" :to="{ name: 'deliveryEdit', params: { id: deliveryOrder.id } }">
                <button class="btn btn-secondary btn-sm">Edit Delivery</button>
              </router-link>
              <router-link :to="{ name: 'finalizeTicket', params: { id: deliveryOrder.id } }" v-if="deliveryOrder.delivery_status != 10">
                <button class="btn btn-accent btn-sm">Finalize</button>
              </router-link>
              <router-link :to="{ name: 'Ticket', params: { id: deliveryOrder.id } }">
                <button class="btn btn-success btn-sm">Print Ticket</button>
              </router-link>
              <button
                class="btn btn-error btn-sm"
                @click="cancelDelivery"
                v-if="[0, 2, 3, 4, 5, 9].includes(deliveryOrder.delivery_status)"
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  
</template>
<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'
import authHeader from '../../services/auth.header'
import { DELIVERY_STATUS, PAYMENT_STATUS, TRANSACTION_STATUS } from '../../constants/status'
import { CreditCard, Delivery } from '../../types/models'
import Header from '../../layouts/headers/headerauth.vue'
import SideBar from '../../layouts/sidebar/sidebar.vue'
import useValidate from "@vuelidate/core";
import { notify } from "@kyvg/vue3-notification"
import dayjs from 'dayjs';
import deliveryService from '../../services/deliveryService';
import customerService from '../../services/customerService';
import authService from '../../services/authService';
import paymentService from '../../services/paymentService';
import adminService from '../../services/adminService';
import queryService from '../../services/queryService';

const route = useRoute()

// Reactive data
const v$ = useValidate()
const user = ref({
  user_id: 0
})
const priceprime = ref(0)
const pricesameday = ref(0)
const priceemergency = ref(0)
const total_amount = ref(0)
const discount = ref(0)
const total_amount_after_discount = ref(0)
const deliveryNotesDriver = ref([])
const userCardfound = ref(false)
const userCard = ref({} as CreditCard)
const customer = ref({
  account_number: '',
  id: 0,
  user_id: 0,
  customer_first_name: '',
  customer_last_name: '',
  customer_town: '',
  customer_state: 0,
  customer_address: '',
  customer_zip: '',
  customer_apt: '',
  customer_home_type: 0,
  customer_phone_number: '',
})

const deliveryMoney = ref({
  time_added: '',
  total_amount_oil: '',
  total_amount_emergency: '',
  total_amount_same_day: '',
  total_amount_prime: '',
  total_amount_fee: '',
  total_discount_amount: '',
  total_discount_total: '',
  total_amount: '',
})
const promo = ref({
  id: 0,
  name_of_promotion: '',
  description: '',
  money_off_delivery: '',
  text_on_ticket: ''
})
const pricing = ref({
  price_from_supplier: 0,
  price_for_customer: 0,
  price_for_employee: 0,
  price_same_day: 0,
  price_prime: 0,
  price_emergency: 0,
  date: "",
})
// Initialize with default values structure matches somewhat Delivery interface but loosely
const deliveryOrder = ref({
  id: '',
  customer_id: 0,
  customer_name: '',
  customer_address: '',
  customer_town: '',
  customer_state: 0,
  customer_zip: '',
  gallons_ordered: 0,
  customer_asked_for_fill: 0,
  gallons_delivered: '',
  customer_filled: 0,
  delivery_status: 0,
  when_ordered: '',
  when_delivered: '',
  expected_delivery_date: '',
  automatic: 0,
  oil_id: 0,
  supplier_price: '',
  customer_price: '',
  customer_temperature: '',
  dispatcher_notes: '',
  prime: 0,
  same_day: 0,
  emergency: 0,
  payment_type: 0,
  payment_card_id: '',
  driver_employee_id: 0,
  driver_first_name: '',
  driver_last_name: '',
  promo_id: 0,
})
const transaction = ref(null as any)

// Computed
const computedDELIVERY_STATUS = computed(() => DELIVERY_STATUS)
const computedPAYMENT_STATUS = computed(() => PAYMENT_STATUS)
const computedTRANSACTION_STATUS = computed(() => TRANSACTION_STATUS)

// Watchers
watch(route, () => {
  getOilOrder(route.params.id);
  getOilOrderMoney(route.params.id);
  sumdelivery(route.params.id);
})

// Lifecycle
onMounted(() => {
  userStatus()
  getOilOrder(route.params.id);
  getOilOrderMoney(route.params.id);
  sumdelivery(route.params.id);
  getOilPricing();
})

// Functions
const format_date = (value: string) => {
  if (value) {
    return dayjs(String(value)).format('LLLL')
  }
}

const getTypeColor = (transactionType: number) => {
  switch (transactionType) {
    case 1: return 'text-blue-600';    // Auth
    case 0: return 'text-orange-600';   // Charge
    case 2: return 'text-green-600';    // Capture
    case 3: return 'text-purple-600';   // Delivery/Other
    default: return 'text-gray-600';
  }
}

const deleteCall = async (delivery_id: any) => {
  try {
    const response = await deliveryService.delete(Number(delivery_id));
    if (response.data.ok) {
      notify({
        title: "Success",
        text: "deleted delivery",
        type: "success",
      });
      // Note: router.push would need to be imported and used
    } else {
      notify({
        title: "Failure",
        text: "error deleting delivery",
        type: "success",
      });
    }
  } catch (error) {
     console.error(error);
      notify({
        title: "Failure",
        text: "error deleting delivery",
        type: "error",
      });
  }
}

const cancelDelivery = async () => {
  try {
    const response = await deliveryService.cancel(Number(deliveryOrder.value.id));
    if (response.data.ok) {
      notify({
        title: "Success",
        text: "Delivery cancelled",
        type: "success",
      });
      // Refresh the delivery data
      getOilOrder(deliveryOrder.value.id);
    } else {
      notify({
        title: "Failure",
        text: "Failed to cancel delivery",
        type: "error",
      });
    }
  } catch (error) {
    notify({
      title: "Error",
      text: "Error cancelling delivery",
      type: "error",
    });
  }
}

const userStatus = () => {
  authService.whoami()
    .then((response: any) => {
      if (response.data.ok) {
        user.value = response.data.user;
      }
    })
    .catch(() => {
        // user not logged in or error
    })
}

const getOilPricing = async () => {
  try {
    const response = await queryService.getOilPriceTable();
    pricing.value = response.data?.pricing || response.data;
  } catch (error) {
    notify({
        title: "Error",
        text: "Could not get oil pricing",
        type: "error",
      });
  }
}

const getCustomer = async (user_id: any) => {
  try {
    const response = await customerService.getById(user_id);
    customer.value = (response.data?.customer || response.data) as any;
  } catch (error) {
    notify({
        title: "Error",
        text: "Could not find customer",
        type: "error",
      });
  }
}

const getPaymentCard = async (card_id: any) => {
  if (card_id) {
    try {
        const response = await paymentService.getCard(card_id);
        const card = response.data?.card || response.data;
        if (card && card.card_number && card.card_number !== '') {
          userCard.value = card;
          userCardfound.value = true;
        } else {
          userCard.value = {} as CreditCard;
          userCardfound.value = false;
        }
    } catch (error) {
        console.error("Error fetching payment card:", error);
        userCard.value = {} as CreditCard;
        userCardfound.value = false;
    }
  } else {
    userCardfound.value = false;
  }
}

const getOilOrder = async (delivery_id: any) => {
  if (!delivery_id) { 
    console.error("getOilOrder called with no ID.");
    return;
  }
  try {
    // Note: deliveryService.getById uses /delivery/:id, which returns { ok: boolean, delivery: ... }
    const response = await deliveryService.getById(Number(delivery_id));
    if (response.data && response.data.ok) {
      deliveryOrder.value = response.data.delivery as any; // Cast because local ref is loose

      // Now that deliveryOrder is the correct object, the rest of the logic will work.
      getCustomer(deliveryOrder.value.customer_id);

      if ([1, 2, 3].includes(deliveryOrder.value.payment_type)) {
        getPaymentCard(deliveryOrder.value.payment_card_id);
      }
      if (deliveryOrder.value.promo_id != null) {
        getPromo(deliveryOrder.value.promo_id);
      }

      // Only fetch transactions for Authorize.net payments
      if (deliveryOrder.value.payment_type == 11) {
        getTransaction(delivery_id);
      }

    } else {
      console.error("API Error: Failed to fetch delivery data.");
      notify({ title: "Error", text: "Could not load delivery details.", type: "error" });
    }
  } catch (error) {
    console.error("Error fetching delivery order:", error);
  }
}

const getOilOrderMoney = (delivery_id: any) => {
  // Keeping axios for this specific endpoint as it uses VITE_MONEY_URL and is not yet in services
  let path = import.meta.env.VITE_MONEY_URL + "/delivery/order/money/" + delivery_id;
  axios({
    method: "get",
    url: path,
    withCredentials: true,
    headers: authHeader(),
  })
    .then((response: any) => {
      if (response.data) {
        deliveryMoney.value = response.data?.money || response.data
      }
    })
}

const sumdelivery = async (delivery_id: any) => {
  try {
    const response = await deliveryService.getTotal(Number(delivery_id));
    // deliveryService.getTotal returns AxiosResponse<DeliveryTotalResponse>
    if (response.data && response.data.ok) {
        priceprime.value = response.data.priceprime || 0;
        pricesameday.value = response.data.pricesameday || 0;
        priceemergency.value = response.data.priceemergency || 0;
        total_amount.value = Number(response.data.total_amount) || 0;
        discount.value = Number(response.data.discount) || 0;
        total_amount_after_discount.value = Number(response.data.total_amount_after_discount) || 0;
    } else {
        calculateFallbackTotal();
    }
  } catch (error) {
      console.error("Error fetching delivery totals:", error);
      calculateFallbackTotal();
      notify({
        title: "Warning",
        text: "Could not get delivery totals, using estimated calculation",
        type: "warn",
      });
  }
}

const calculateFallbackTotal = () => {
  // Fallback calculation using available data
  if (deliveryOrder.value.gallons_ordered && pricing.value.price_for_customer) {
    const gallons = Number(deliveryOrder.value.gallons_ordered);
    const pricePerGallon = Number(pricing.value.price_for_customer);
    let total = gallons * pricePerGallon;

    if (deliveryOrder.value.prime == 1) {
      total += Number(pricing.value.price_prime) || 0;
    }
    if (deliveryOrder.value.same_day == 1) {
      total += Number(pricing.value.price_same_day) || 0;
    }
    if (deliveryOrder.value.emergency == 1) {
      total += Number(pricing.value.price_emergency) || 0;
    }

    total_amount.value = total;
    total_amount_after_discount.value = total; // No discount info available
    discount.value = 0;
  }
}

const getPromo = async (promo_id: any) => {
    try {
        const response = await adminService.promos.getById(Number(promo_id));
        if (response.data) {
            promo.value = response.data?.promo || (response.data as any);
        }
    } catch (error) {
        console.error('Error fetching promo:', error);
    }
}

const calculateDeliveryTotal = () => {
  if (!deliveryOrder.value.gallons_delivered || !pricing.value.price_for_customer) {
    return '0.00';
  }

  const gallons = Number(deliveryOrder.value.gallons_delivered);
  const pricePerGallon = Number(pricing.value.price_for_customer);
  let total = gallons * pricePerGallon;

  if (deliveryOrder.value.prime == 1) {
    total += Number(pricing.value.price_prime) || 0;
  }
  if (deliveryOrder.value.same_day == 1) {
    total += Number(pricing.value.price_same_day) || 0;
  }
  if (deliveryOrder.value.emergency == 1) {
    total += Number(pricing.value.price_emergency) || 0;
  }

  return total.toFixed(2);
}

const calculateEstimatedTotal = () => {
  if (!deliveryOrder.value.gallons_ordered || !pricing.value.price_for_customer) {
    return 0;
  }

  const gallons = Number(deliveryOrder.value.gallons_ordered);
  const pricePerGallon = Number(pricing.value.price_for_customer);
  let total = gallons * pricePerGallon;

  if (deliveryOrder.value.prime == 1) {
    total += Number(pricing.value.price_prime) || 0;
  }
  if (deliveryOrder.value.same_day == 1) {
    total += Number(pricing.value.price_same_day) || 0;
  }
  if (deliveryOrder.value.emergency == 1) {
    total += Number(pricing.value.price_emergency) || 0;
  }

  return total;
}

const getTransaction = async (delivery_id: any) => {
  try {
      const response = await paymentService.getDeliveryTransaction(Number(delivery_id));
      if (response.data.ok) {
          // Cast needed if TS definition of PaymentTransaction doesn't perfectly overlap or if response wrapping is tricky
          transaction.value = (response.data as any).transaction || response.data;
          console.log("Transaction loaded:", transaction.value);
      } else {
          console.log("No transaction found for delivery:", delivery_id);
          transaction.value = null;
      }
  } catch (error) {
    console.error("Error fetching transaction:", error);
    transaction.value = null;
  }
}
</script>

<style scoped></style>
