<!-- src/pages/delivery/update_tickets/finalize_ticket.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 Ticket #{{ deliveryOrder.id }}</li>
        </ul>
      </div>

      <!-- Page Header -->
      <div class="flex flex-wrap justify-between items-center gap-2 mt-4">
        <h1 class="text-3xl font-bold">
          Finalize Delivery #{{ deliveryOrder.id }}
        </h1>
        <router-link v-if="deliveryOrder.id" :to="{ name: 'deliveryEdit', params: { id: deliveryOrder.id } }">
          <button class="btn btn-sm btn-secondary">Edit Order</button>
        </router-link>
      </div>

      <!-- NEW LAYOUT: A single 2-column grid for the whole page -->
      <div v-if="total_amount" 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>
            <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>

          <!-- Delivery Details Card -->
          <div class="bg-neutral rounded-lg p-5">
            <h3 class="text-xl font-bold mb-4">Delivery Details</h3>
            <div class="grid grid-cols-2 gap-x-4 gap-y-3 text-sm">
              <div>
                <div class="font-bold">Status</div>
                <div class="opacity-80">
                   <span v-if="deliveryOrder.delivery_status == 0">waiting</span>
                   <span v-else-if="deliveryOrder.delivery_status == 1">delivered</span>
                   <span v-else-if="deliveryOrder.delivery_status == 2">Today</span>
                   <span v-else-if="deliveryOrder.delivery_status == 3">Tomorrow</span>
                   <span v-else-if="deliveryOrder.delivery_status == 4">Partial Delivery</span>
                   <span v-else-if="deliveryOrder.delivery_status == 5">misdelivery</span>
                   <span v-else-if="deliveryOrder.delivery_status == 6">unknown</span>
                   <span v-else-if="deliveryOrder.delivery_status == 10">Finalized</span>
                </div>
              </div>
              <div>
                <div class="font-bold">Scheduled Date</div>
                <div class="opacity-80">{{ deliveryOrder.expected_delivery_date }}</div>
              </div>
              <div>
                <div class="font-bold">When Ordered</div>
                <div class="opacity-80">{{ deliveryOrder.when_ordered }}</div>
              </div>
              <div>
                <div class="font-bold">When Delivered</div>
                <div class="opacity-80">{{ deliveryOrder.when_delivered }}</div>
              </div>
              <div>
                <div class="font-bold">Driver</div>
                <div class="opacity-80">{{ deliveryOrder.driver_first_name }} {{ deliveryOrder.driver_last_name }}</div>
              </div>
            </div>
          </div>

          <!-- Financial Summary Card -->
          <div class="bg-neutral rounded-lg p-5">
            <h3 class="text-xl font-bold mb-4">Financial Summary</h3>
            <div class="space-y-3">
              <!-- Pricing & Gallons -->
              <div class="grid grid-cols-2 sm:grid-cols-3 gap-3 text-sm">
                <div>
                  <div class="font-bold">Price / Gallon</div>
                  <div class="opacity-80">${{ Number(deliveryOrder.customer_price).toFixed(2) }}</div>
                </div>
                <div>
                  <div class="font-bold">Gallons Ordered</div>
                  <div class="opacity-80" v-if="deliveryOrder.customer_asked_for_fill == 1">FILL</div>
                  <div class="opacity-80" v-else>{{ deliveryOrder.gallons_ordered }}</div>
                </div>
                <div>
                  <div class="font-bold">Gallons Delivered</div>
                  <div class="opacity-80">{{ deliveryOrder.gallons_delivered || 'N/A' }}</div>
                </div>
              </div>
              <!-- Fees -->
              <div class="text-sm space-y-1 border-t border-base-100 pt-3">
                 <div v-if="deliveryOrder.prime == 1" class="flex justify-between"><span>Prime Fee</span> <span>${{ Number(pricing.price_prime).toFixed(2) }}</span></div>
                 <div v-if="deliveryOrder.same_day === 1" class="flex justify-between"><span>Same Day Fee</span> <span>${{ Number(pricing.price_same_day).toFixed(2) }}</span></div>
              </div>
               <!-- Payment -->
              <div class="border-t border-base-100 pt-3">
                 <div class="font-bold text-sm">Payment Method</div>
                 <div class="opacity-80 text-sm">
                   <span v-if="deliveryOrder.payment_type == 0">Cash</span>
                   <span v-else-if="deliveryOrder.payment_type == 1">Credit Card</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>No Payment Type Added</span>
                 </div>
                 <div v-if="userCardfound && (deliveryOrder.payment_type == 1 || deliveryOrder.payment_type == 2 || deliveryOrder.payment_type == 3)" class="mt-2 p-3 rounded-lg border bg-accent/20 border-accent">
                    <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>Exp: {{ userCard.expiration_month }} / {{ userCard.expiration_year }}</p>
                    </div>
                 </div>
              </div>
              <!-- Total -->
              <div class="flex justify-between items-center border-t border-base-100 pt-3">
                <span class="text-lg font-bold">
                  <span v-if="deliveryOrder.payment_type == 0">Cash Total</span>
                  <span v-else-if="deliveryOrder.payment_type == 1 || deliveryOrder.payment_type == 2 || deliveryOrder.payment_type == 3">Pre-Auth Estimate</span>
                  <span v-else>Total Amount</span>
                </span>
                <span class="text-2xl font-bold text-success">
                  <span v-if="deliveryOrder.payment_type == 1 || deliveryOrder.payment_type == 2 || deliveryOrder.payment_type == 3">
                    ${{ Number(preChargeTotal).toFixed(2) }}
                  </span>
                  <span v-else>
                    ${{ Number(total_amount).toFixed(2) }}
                  </span>
                </span>
              </div>
            </div>
          </div>

        </div>

        <!-- RIGHT COLUMN: Finalize Form -->
        <div class="space-y-4">
          <div class="bg-base-100 rounded-lg p-5">
            <h2 class="text-2xl font-bold mb-4">Finalize Ticket</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>
                <label class="label"><span class="label-text font-bold">Fill Location</span></label>
                <input v-model="FinalizeOilOrderForm.fill_location" class="input input-bordered input-sm w-full max-w-xs" type="text" placeholder="Fill location (e.g., 1-12)" />
              </div>
              
              <div>
                <label class="label"><span class="label-text font-bold">Cash Received</span></label>
                <input v-model="FinalizeOilOrderForm.cash_recieved" class="input input-bordered input-sm w-full max-w-xs" type="number" step="0.01" placeholder="Amount received" />
              </div>

              <div>
                <label class="label"><span class="label-text font-bold">Check #</span></label>
                <input v-model="FinalizeOilOrderForm.check_number" class="input input-bordered input-sm w-full max-w-xs" type="text" placeholder="Check Number" />
              </div>

              <div>
                <label class="label"><span class="label-text font-bold">Delivery Status</span></label>
                <select class="select select-bordered select-sm w-full max-w-xs" v-model="FinalizeOilOrderForm.delivery_status">
                  <option class="text-white" v-for="(delivery, index) in deliveryStatus" :key="index"
                    :value="delivery['value']">
                    {{ delivery['text'] }}
                  </option>
                </select>
              </div>

              <div class="form-control">
                <label class="label cursor-pointer justify-start gap-4">
                  <span class="label-text font-bold">Customer Tank Filled</span>
                  <input v-model="FinalizeOilOrderForm.customer_filled" type="checkbox" class="checkbox checkbox-sm" />
                </label>
              </div>

              <div class="pt-2">
                <button type="submit" class="btn btn-secondary btn-sm">Finalize Delivery</button>
              </div>

            </form>
          </div>
        </div>
      </div>
      <div v-else class="text-center p-10">
        Loading ticket details...
      </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 { notify } from "@kyvg/vue3-notification"

export default defineComponent({
  name: 'finalizeTicket',

  components: {
    Header,
    SideBar,
    Footer,
  },

  data() {
    return {
      loaded: false,
      user: { id: 0 },
      userCardfound: false,
      deliveryStatus: [],
      userCards: [],
      deliveryNotesDriver: [],
      total_amount: 0,
      preChargeTotal: 0,

      FinalizeOilOrderForm: {
        cash_recieved: '',
        fill_location: 0,
        check_number: 0,
        delivery_status: 10,
        credit_card_id: 0,
        driver: 0,
        gallons_delivered: '',
        customer_filled: false,
      },
      userCard: {
        date_added: '',
        user_id: '',
        card_number: '',
        last_four_digits: '',
        name_on_card: '',
        expiration_month: '',
        expiration_year: '',
        type_of_card: '',
        security_number: '',
        accepted_or_declined: '',
        main_card: '',
      },
      customer: {
        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: '',
      },
      customerDescription: {
        customer_id: 0,
        account_number: '',
        company_id: 0,
        fill_location: 0,
        description: '',
      },
      deliveryOrder: {
        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,
        payment_type: 0,
        payment_card_id: '',
        driver_employee_id: 0,
        driver_first_name: '',
        driver_last_name: '',
        total_price: 0,
      },
      pricing: {
        price_from_supplier: 0,
        price_for_customer: 0,
        price_for_employee: 0,
        price_same_day: 0,
        price_prime: 0,
        date: "",
      },
    }
  },

  mounted() {
    const deliveryId = this.$route.params.id;
    this.sumdelivery(deliveryId);
    this.getOilOrder(deliveryId);
    this.getOilPricing();
    this.getDeliveryStatusList();
  },

  methods: {
    getOilOrder(delivery_id: any) {
      const path = `${import.meta.env.VITE_BASE_URL}/delivery/order/${delivery_id}`;
      axios.get(path, { withCredentials: true, headers: authHeader() })
        .then((response: any) => {
          if (response.data && response.data.ok) {
            this.deliveryOrder = response.data.delivery;
            this.getCustomer(this.deliveryOrder.customer_id);

            if ([1, 2, 3].includes(this.deliveryOrder.payment_type)) {
              this.getPaymentCard(this.deliveryOrder.payment_card_id);
            }

            // Properly initialize all form fields with existing delivery data
            this.FinalizeOilOrderForm.cash_recieved = response.data.delivery.cash_recieved || '';
            this.FinalizeOilOrderForm.check_number = response.data.delivery.check_number || '';
            this.FinalizeOilOrderForm.credit_card_id = response.data.delivery.payment_card_id;
            this.FinalizeOilOrderForm.customer_filled = response.data.delivery.customer_filled == 1;
            this.FinalizeOilOrderForm.gallons_delivered = response.data.delivery.gallons_delivered || '';
            this.FinalizeOilOrderForm.driver = response.data.delivery.driver_employee_id || 0;
            this.FinalizeOilOrderForm.delivery_status = 10; // Finalization status - hardcoded for finalizing action
          } else {
            console.error("API Error:", response.data.error || "Failed to fetch delivery data.");
          }
        })
        .catch((error: any) => console.error("Error fetching oil order:", error));
    },

    getPaymentCard(card_id: any) {
      const path = `${import.meta.env.VITE_BASE_URL}/payment/card/${card_id}`;
      axios.get(path, { withCredentials: true })
        .then((response: any) => {
          if (response.data.userCard && response.data.userCard.card_number !== '') {
            this.userCard = response.data;
            this.userCardfound = true;
          } else {
            this.userCardfound = false;
          }
        })
        .catch((error: any) => {
            this.userCardfound = false;
            console.error(`Error fetching payment card ${card_id}:`, error);
        });
    },

    getCustomer(user_id: any) {
      const path = `${import.meta.env.VITE_BASE_URL}/customer/${user_id}`;
      axios.get(path, { withCredentials: true })
        .then((response: any) => {
          this.customer = response.data;
          this.getCustomerDescription(this.deliveryOrder.customer_id);
        })
        .catch((error: any) => {
          notify({ title: "Error", text: "Could not find customer", type: "error" });
          console.error("Error fetching customer:", error);
        });
    },

    getCustomerDescription(user_id: any) {
      const path = `${import.meta.env.VITE_BASE_URL}/customer/description/${user_id}`;
      axios.get(path, { withCredentials: true })
        .then((response: any) => {
          this.customerDescription = response.data;
          this.FinalizeOilOrderForm.fill_location = this.customerDescription.fill_location;
        })
        .catch((error: any) => {
          notify({ title: "Error", text: "Could not find customer description", type: "error" });
          console.error("Error fetching customer description:", error);
        });
    },

    getOilPricing() {
      const path = `${import.meta.env.VITE_BASE_URL}/info/price/oil/table`;
      axios.get(path, { withCredentials: true })
        .then((response: any) => {
          this.pricing = response.data;
        })
        .catch((error: any) => {
          notify({ title: "Error", text: "Could not get oil pricing", type: "error" });
          console.error("Error fetching oil pricing:", error);
        });
    },

    sumdelivery(delivery_id: any) {
      const path = `${import.meta.env.VITE_BASE_URL}/delivery/total/${delivery_id}`;
      axios.get(path, { withCredentials: true })
        .then((response: any) => {
          if (response.data.ok) {
            this.total_amount = response.data.total_amount;
            this.preChargeTotal = response.data.total_amount;
          }
        })
        .catch((error: any) => {
          notify({ title: "Error", text: "Could not get delivery total", type: "error" });
          console.error("Error summing delivery:", error);
        });
    },

    getDeliveryStatusList() {
      const path = `${import.meta.env.VITE_BASE_URL}/query/deliverystatus`;
      axios.get(path, { withCredentials: true })
        .then((response: any) => {
          this.deliveryStatus = response.data;
        })
        .catch((error: any) => console.error("Error fetching delivery status list:", error));
    },

    CreateTransaction() {
      const path = `${import.meta.env.VITE_MONEY_URL}/delivery/add/${this.deliveryOrder.id}`;
      axios.post(path, {}, { withCredentials: true, headers: authHeader() })
        .then((response: any) => {
          if (response.status === 201) {
            notify({ title: "Success", text: "Confirmed Transaction", type: "success" });
          } else {
            notify({ title: "Error", text: "Error Confirming Transaction", type: "error" });
          }
        })
        .catch((error: any) => {
            notify({ title: "Error", text: "Failed to create transaction", type: "error" });
            console.error("CreateTransaction error:", error);
        });
    },

    FinalizeOrder(payload: any) {
      const path = `${import.meta.env.VITE_BASE_URL}/deliverydata/finalize/${this.deliveryOrder.id}`;
      axios.put(path, payload, { withCredentials: true, headers: authHeader() })
        .then((response: any) => {
          if (response.data.ok) {
            notify({ title: "Success", text: "Ticket is finalized", type: "success" });
            this.CreateTransaction();
            this.$router.push({ name: "deliveryOrder", params: { id: this.deliveryOrder.id } });
          } else {
            notify({ title: "Error", text: response.data.error || "Could not finalize ticket", type: "error" });
            this.$router.push({ name: "delivery" });
          }
        })
        .catch((error: any) => {
            notify({ title: "Error", text: "Failed to finalize order", type: "error" });
            console.error("FinalizeOrder error:", error);
        });
    },



async onSubmit() {
  // Step 1: ALWAYS build the payload with the latest form data.
  const payload = {
    cash_recieved: this.FinalizeOilOrderForm.cash_recieved,
    check_number: this.FinalizeOilOrderForm.check_number,
    delivery_status: this.FinalizeOilOrderForm.delivery_status,
    driver_employee_id: this.FinalizeOilOrderForm.driver,
    gallons_delivered: this.FinalizeOilOrderForm.gallons_delivered,
    customer_filled: this.FinalizeOilOrderForm.customer_filled,
    fill_location: this.FinalizeOilOrderForm.fill_location,
  };

  // Step 2: ALWAYS update the delivery order with the payload.
  // We make this an async call and wait for it to finish.
  try {
    const path = `${import.meta.env.VITE_BASE_URL}/deliverydata/finalize/${this.deliveryOrder.id}`;
    const finalizeResponse = await axios.put(path, payload, { withCredentials: true, headers: authHeader() });

    if (!finalizeResponse.data.ok) {
      // If the update fails, stop everything and show an error.
      notify({
        title: "Error",
        text: finalizeResponse.data.error || "Could not update delivery details.",
        type: "error"
      });
      return; // Stop execution.
    }
  } catch (error: any) {
    notify({
      title: "Error",
      text: "Failed to update delivery details.",
      type: "error"
    });
    console.error("FinalizeOrder error:", error);
    return; // Stop execution.
  }
  
  // Step 3: NOW, check if there's a pre-authorized transaction.
  try {
    const transactionUrl = `${import.meta.env.VITE_AUTHORIZE_URL}/api/transaction/delivery/${this.$route.params.id}`;
    const transactionResponse = await axios.get(transactionUrl, {
      withCredentials: true,
      headers: authHeader(),
    });

    // If a valid, approved, pre-auth transaction is found...
    if (transactionResponse.data && transactionResponse.data.transaction_type === 1 && transactionResponse.data.status === 0) {
      
      // ...redirect to the capture page. The delivery is already updated.
      const gallons = this.FinalizeOilOrderForm.gallons_delivered || '0';
      const pricePerGallon = parseFloat(this.deliveryOrder.customer_price);
      let finalAmount = parseFloat(gallons) * pricePerGallon;

      if (this.deliveryOrder.prime == 1) {
          finalAmount += parseFloat(this.pricing.price_prime.toString()) || 0;
      }
      if (this.deliveryOrder.same_day == 1) {
          finalAmount += parseFloat(this.pricing.price_same_day.toString()) || 0;
      }

      this.$router.push({
        name: 'captureAuthorize',
        params: { id: this.$route.params.id },
        query: {
          gallons: gallons,
          amount: finalAmount.toFixed(2).toString()
        }
      });

    } else {
      // Step 4a: If no pre-auth transaction, finalize the financial part and redirect.
      notify({ title: "Success", text: "Ticket details have been updated.", type: "success" });
      this.CreateTransaction();
      this.$router.push({ name: "deliveryOrder", params: { id: this.deliveryOrder.id } });
    }
  } catch (error: any) {
    // Step 4b: If checking for pre-auth fails, but the update succeeded,
    // finalize the financial part and redirect.
    console.log("No pre-authorized transaction found. Proceeding with standard finalization.");
    notify({ title: "Success", text: "Ticket details have been updated.", type: "success" });
    this.CreateTransaction();
    this.$router.push({ name: "deliveryOrder", params: { id: this.deliveryOrder.id } });
  }
},


  },

  
});
</script>
