<!-- src/pages/delivery/update_tickets/finalize_ticket_auto_nocc.vue -->
<template>
  <div class="flex">

    <!-- Main container with responsive horizontal padding -->
    <div class="w-full px-4 md:px-6 py-4">
      <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 v-if="customer && customer.id">
            <router-link :to="{ name: 'customerProfile', params: { id: customer.id } }">
              {{ customer.customer_first_name }} {{ customer.customer_last_name }}
            </router-link>
          </li>
          <li>Finalize Auto Ticket</li>
        </ul>
      </div>

      <!-- Page Header -->
      <div class="flex flex-wrap justify-between items-center gap-2 mt-4">
        <h1 class="text-3xl font-bold">
          Auto Delivery #{{ autoDelivery.id }}
        </h1>
        <router-link v-if="customer.id > 0" :to="{ name: 'customerProfile', params: { id: customer.id } }">
          <button class="btn btn-sm btn-secondary">Customer Profile</button>
        </router-link>
      </div>

      <!-- NEW LAYOUT: A single 2-column grid for the whole page -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 mt-4">

        <!-- LEFT COLUMN: All Display Information -->
        <div class="space-y-4">

          <!-- Customer Info Card -->
          <div class="bg-neutral rounded-lg p-5">
            <div class="text-xl font-bold mb-2">Customer</div>
            <!-- This section uses your original v-if logic -->
            <div>
              <div class="font-bold">{{ customer.customer_first_name }} {{ customer.customer_last_name }}</div>
              <div>{{ customer.customer_address }}</div>
              <div v-if="customer.customer_apt && customer.customer_apt !== 'None'">{{ 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">Maine</span>
                <span v-else-if="customer.customer_state == 6">New York</span>
                <span v-else>Unknown state</span>
                {{ customer.customer_zip }}
              </div>
              <div class="mt-2 text-sm">
                {{ customer.customer_phone_number }}
                (<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>
          </div>

          <!-- Payment & Pricing Card -->
          <div class="bg-neutral rounded-lg p-5">
            <h3 class="text-xl font-bold mb-4">Payment & Pricing</h3>
            <div class="space-y-4">
              <div>
                <div class="font-bold text-sm">Today's Price / Gallon</div>
                <div class="text-lg font-mono">${{ Number(today_oil_price).toFixed(2) }}</div>
              </div>

              <div>
                <div class="font-bold text-sm">Payment Method</div>
                <div v-if="!userCardfound" class="text-warning text-sm">No card on file for this customer.</div>
                <div v-if="userCardfound && userCard" class="mt-2 p-3 rounded-lg border bg-primary/10 border-primary">
                  <div class="font-bold text-sm">{{ userCard.name_on_card }}</div>
                  <div class="text-xs opacity-70">{{ userCard.type_of_card }}</div>
                  <div class="mt-1 text-sm font-mono tracking-wider">
                    <p>{{ userCard.card_number }}</p>
                    <p>{{ userCard.security_number }}</p>
                    <p>Exp: {{ userCard.expiration_month }} / {{ userCard.expiration_year }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>

        </div>

        <!-- RIGHT COLUMN: Finalize Form -->
        <div class="space-y-4">
          <div v-if="customer.id > 0" class="bg-base-100 rounded-lg p-5">
            <h2 class="text-2xl font-bold mb-4">Finalize Auto Delivery</h2>
            <form class="space-y-4" @submit.prevent="onSubmit">
              <div>
                <label class="label"><span class="label-text font-bold">Gallons Delivered</span></label>
                <input v-model="FinalizeOilOrderForm.gallons_delivered"
                  class="input input-bordered input-sm w-full max-w-xs" type="number" step="0.01" placeholder="# gallons" />
              </div>

              <div class="pt-2">
                <button type="submit" class="btn btn-success btn-sm" :disabled="submitting">
                  <span v-if="submitting" class="loading loading-spinner loading-xs"></span>
                  {{ submitting ? 'Finalizing...' : 'Finalize Delivery' }}
                </button>
              </div>
            </form>
          </div>
          <div v-else class="bg-base-100 rounded-lg p-5">
            <h2 class="text-2xl font-bold mb-4 text-error">Error</h2>
            <p>Customer information not found. Please check the automatic delivery data.</p>
          </div>
        </div>
      </div>
    </div>
  </div>
  
</template>


<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
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 useValidate from "@vuelidate/core";
import { notify } from "@kyvg/vue3-notification"
import deliveryService from '../../../services/deliveryService'
import customerService from '../../../services/customerService'
import paymentService from '../../../services/paymentService'
import queryService from '../../../services/queryService'
import authService from '../../../services/authService'

// Route and router
const route = useRoute()
const router = useRouter()

// Reactive data
const v$ = useValidate()
const loaded = ref(false)
const submitting = ref(false)
const user = ref({
  id: 0
})
const userCardfound = ref(false)
const deliveryStatus = ref([])
const userCards = ref([])
const deliveryNotesDriver = ref([])
const today_oil_price = ref(0)

const FinalizeOilOrderForm = ref({
  fill_location: 0,
  check_number: 0,
  delivery_status: 10,
  userCards: [],
  credit_card_id: 0,
  driver: 0,
  gallons_delivered: '',
  customer_filled: false,
  prime: false,
  same_day: false,
  emergency: false,
})
const CreateOilOrderForm = ref({
  basicInfo: {
    gallons_delivered: '',
    userCards: []
  },
})
const userCard = ref<{
  date_added: string;
  user_id: string;
  card_number: string;
  last_four_digits: string;
  name_on_card: string;
  expiration_month: string;
  expiration_year: string;
  type_of_card: string;
  security_number: string;
  accepted_or_declined: string;
  main_card: string;
} | null>(null)
const customer = ref({
  id: 0,
  user_id: 0,
  customer_address: '',
  customer_first_name: '',
  customer_last_name: '',
  customer_town: '',
  customer_state: 0,
  customer_zip: '',
  customer_apt: '',
  customer_home_type: 0,
  customer_phone_number: '',
})
const customerDescription = ref({
  customer_id: 0,
  account_number: '',
  company_id: 0,
  fill_location: 0,
  description: '',
})

const autoTicket = ref({
  id: 0,
  customer_id: '',
  account_number: '',

  customer_town: '',
  customer_state: '',
  customer_address: '',
  customer_zip: '',
  customer_full_name: '',

  oil_prices_id: '',
  fill_date: '',
  gallons_delivered: '',
  price_per_gallon: '',

  total_amount_customer: '',

  payment_type: '',
  payment_card_id: '',
  payment_status: '',
  open_ticket_id: 0
})

const autoDelivery = ref({
  id: 0,
  customer_id: 0,
  account_number: '',
  customer_town: '',
  customer_state: 0,
  customer_address: '',
  customer_zip: '',
  customer_full_name: '',
  last_fill: '',
  days_since_last_fill: 0,
  last_updated: '',
  estimated_gallons_left: 0,
  estimated_gallons_left_prev_day: 0,
  tank_height: '',
  tank_size: '',
  house_factor: 0,
  auto_status: 0,
  open_ticket_id: null,
})

// Watchers
watch(() => route.params, () => {
  today_price_oil()
  getAutoTicket(route.params.id)
}, { immediate: false })

// Lifecycle
onMounted(() => {
  userStatus()
  today_price_oil()
  getAutoDelivery(route.params.id)
})

// Functions
const userStatus = async () => {
    try {
        const response = await authService.whoami();
        if (response.data.ok) {
            user.value = response.data.user;
            user.value.id = response.data.user_id;
        }
    } catch (error) {}
}

const getPaymentCard = async (card_id: any) => {
    try {
        const response = await paymentService.getCard(Number(card_id));
        const card = response.data?.card || response.data as any;
        if (card?.card_number === '') {
            userCard.value = null;
            userCardfound.value = false;
        } else {
            userCard.value = card as any;
            userCardfound.value = true;
        }
        (FinalizeOilOrderForm.value.userCards as any) = card?.id
    } catch (error) {}
}

const getPaymentCards = async (user_id: any) => {
    try {
        const response = await paymentService.getCards(Number(user_id));
        userCards.value = (response.data?.cards || response.data) as any;
        if (userCards.value && userCards.value.length > 0) {
            userCardfound.value = true;
            userCard.value = userCards.value.find((card: any) => card.main_card) || userCards.value[0];
        }
    } catch (error) {}
}

const getCustomer = async (userid: any) => {
    try {
        const response = await customerService.getById(Number(userid));
        customer.value = (response.data?.customer || response.data) as any;
        if (customer.value.id > 0) {
             getPaymentCards(customer.value.user_id || customer.value.id);
        }
    } catch (error) {
         notify({
            title: "Error",
            text: "Could not find customer",
            type: "error",
        });
        customer.value = { id: 0, user_id: 0, customer_address: '', customer_first_name: '', customer_last_name: '', customer_town: '', customer_state: 0, customer_zip: '', customer_apt: '', customer_home_type: 0, customer_phone_number: '' };
    }
}

// Renamed/Merged functionality into one if possible or keeping as alias
const getCreditCards = async (userid: any) => {
    // This seems identical to getPaymentCards logic but called from getAutoDelivery
    await getPaymentCards(userid);
}

const getCustomerDescription = async (user_id: any) => {
    try {
        const response = await customerService.getDescription(Number(user_id));
        customerDescription.value = (response.data?.description || response.data) as any;
        loaded.value = true
    } catch (error) {
        notify({
            title: "Error",
            text: "Could not find customer",
            type: "error",
        });
    }
}

const getAutoTicket = async (delivery_id: any) => {
    try {
        const response = await deliveryService.auto.getTicket(Number(delivery_id));
        autoTicket.value = (response.data?.ticket || response.data as any);
        getCustomer(autoTicket.value.customer_id)

        getAutoDelivery(autoTicket.value.id)
        getCustomerDescription(autoTicket.value.customer_id)
    } catch (error) {
        notify({
            title: "Error",
            text: "Could not get automatic",
            type: "error",
        });
    }
}

const getAutoDelivery = async (delivery_id: any) => {
    try {
        const response = await deliveryService.auto.getDelivery(Number(delivery_id));
        const delivery = response.data?.delivery || response.data as any;
        if (delivery && delivery.customer_id) {
            autoDelivery.value = delivery;
            getCustomer(autoDelivery.value.customer_id)
            getCreditCards(autoDelivery.value.customer_id)
        } else {
             console.error("API Error:", response.data?.error || "Failed to fetch auto delivery data.");
        }
    } catch (error) {
         console.error("API Error in getAutoDelivery:", error);
          notify({
            title: "Error",
            text: "Could not get automatic delivery",
            type: "error",
          });
    }
}

const today_price_oil = async () => {
    try {
        const response = await queryService.getOilPrice();
         today_oil_price.value = (response.data as any).price_for_customer;
    } catch (error) {}
}

const UpdateAuto = (payload: {
  gallons: string,
  delivery_id: string,
}) => {
    // Unused in this file but migrated for consistency
  let path = import.meta.env.VITE_AUTO_URL + "/confirm/delivery"
  axios({
    method: "put",
    url: path,
    data: payload,
    withCredentials: true,
    headers: authHeader(),
  })
    .then((response: any) => {
      if (response.data.ok) {
        notify({
          text: 'Update',
          type: 'positive',
          title: 'top'
        })
        router.push({ name: "auto" });
      }
      else {
        notify({
          text: 'Auto Failure',
          type: 'negative',
          title: 'Update'
        })
      }
    })
}

const CreateTransaction = (auto_ticket_id: string) => {
    // Uses VITE_MONEY_URL
  let path = import.meta.env.VITE_MONEY_URL + "/delivery/add/auto/" + auto_ticket_id;
  axios({
    method: "post",
    url: path,
    withCredentials: true,
    headers: authHeader(),
  })
    .then((response: any) => {
      if (response.status == 201) {
        notify({
          message: 'Confirmed Transaction',
          type: 'positive',
          position: 'top'
        })
      }
      else {
        notify({
          message: 'Form Error',
          type: 'negative',
          position: 'top'
        })
      }
    })
}

const ConfirmAuto = async (payload: {
  gallons_delivered: string,
}) => {
    try {
        const response = await deliveryService.auto.createTicketNoPreauth(autoDelivery.value.id, payload);
          if (response.data) {
            notify({
              title: "Success",
              text: "Auto Delivered",
              type: "success",
            });
            // Original code accessed auto_ticket_id from ['0']
            const data = response.data as any;
            if (data['0'] && data['0']['auto_ticket_id']) {
                 CreateTransaction(data['0']['auto_ticket_id'])
            }
          } else if ((response.data as any).error) {
             notify({
              title: "Error",
              text: "Could not finalize auto",
              type: "error",
            });
            router.push("auto");
          }
    } catch (error) {
         notify({
          title: "Error",
          text: "Could not finalize auto",
          type: "error",
        });
        router.push("auto");
    }
}

const onSubmit = async () => {
  if (submitting.value) return;
  submitting.value = true;
  try {
    const payload = {
      gallons_delivered: FinalizeOilOrderForm.value.gallons_delivered,
    };
    await ConfirmAuto(payload);
    router.push({ name: "auto" });
  } finally {
    submitting.value = false;
  }
}
</script>

<style scoped></style>
