<!-- src/pages/pay/pay_oil.vue -->
<template>
  <div class="flex">
 
    <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>
          <!-- Add a link to the customer's profile if the data is available -->
          <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>Confirm Payment</li>
        </ul>
      </div>
      <h1 class="text-3xl font-bold mt-4 border-b border-gray-600 pb-2">
        Confirm Delivery #{{ delivery.id }}
      </h1>

      <!-- Main Content Grid -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 my-6">
        
        <!-- LEFT COLUMN: Customer and Delivery Details -->
        <div class="space-y-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>
              <router-link v-if="customer && customer.id" :to="{ name: 'customerProfile', params: { id: customer.id } }" class="btn btn-secondary btn-sm">
                View Profile
              </router-link>
            </div>
            <div class="space-y-1">
              <div>{{ customer.customer_address }}</div>
              <div v-if="customer.customer_apt && customer.customer_apt !== 'None'">Apt: {{ customer.customer_apt }}</div>
              <div>{{ customer.customer_town }}, {{ customer.customer_state === 0 ? 'MA' : 'RI' }} {{ customer.customer_zip }}</div>
              <div class="mt-2">{{ customer.customer_phone_number }}</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="space-y-3">
              <div>
                <div class="font-bold text-sm">Current Status</div>
                <div class="badge" :class="{ 'badge-info': delivery.delivery_status === 0, 'badge-success': delivery.delivery_status === 1, 'badge-warning': delivery.delivery_status > 1 }">
                  <span v-if="delivery.delivery_status == 0">Waiting</span>
                  <span v-else-if="delivery.delivery_status == 1">Delivered</span>
                  <span v-else-if="delivery.delivery_status == 2">Out_for_Delivery</span>
                  <span v-else-if="delivery.delivery_status == 3">Tomorrow_Delivery</span>
                  <span v-else-if="delivery.delivery_status == 4">Partial Delivery</span>
                  <span v-else-if="delivery.delivery_status == 5">Issue</span>
                  <span v-else-if="delivery.delivery_status == 9">Pending</span>
                  <span v-else-if="delivery.delivery_status == 10">Finalized</span>
                  <span v-else>Pending</span>
                </div>
              </div>
              <div>
                <div class="font-bold text-sm">Scheduled Date</div>
                <div>{{ delivery.expected_delivery_date }}</div>
              </div>
              <div>
                <div class="font-bold text-sm">Gallons Ordered</div>
                <div>
                  <span v-if="delivery.customer_asked_for_fill == 1" class="badge badge-info">FILL (250 gal estimate)</span>
                  <span v-else>{{ delivery.gallons_ordered }} Gallons</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- RIGHT COLUMN: Payment and Pricing Details -->
        <div class="space-y-6">

          <!-- 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">
              <!-- Payment Method -->
              <div>
                <div class="font-bold text-sm">Payment Method</div>
                <div class="text-lg">
                  <span v-if="delivery.payment_type == 0">Cash</span>
                  <span v-else-if="delivery.payment_type == 1">Credit Card</span>
                  <span v-else-if="delivery.payment_type == 2">Credit Card / Cash</span>
                  <span v-else-if="delivery.payment_type == 3">Check</span>
                  <span v-else-if="delivery.payment_type == 4">Other</span>
                </div>
                <!-- Show the selected card if payment is by credit -->
                <div v-if="delivery.payment_type == 1 || delivery.payment_type == 3" class="mt-2">
                  <div v-for="card in credit_cards" :key="card.id">
                    <div v-if="card.id === delivery.payment_card_id" class="bg-base-100 p-3 rounded-md text-sm">
                      <div class="font-mono font-semibold">{{ card.type_of_card }} ending in {{ card.last_four_digits }}</div>
                      <div>{{ card.name_on_card }}</div>
                      <div>Expires: {{ card.expiration_month }}/{{ card.expiration_year }}</div>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- Pricing Breakdown -->
              <div class="space-y-2 pt-2">
                <div class="flex justify-between text-sm">
                  <span>Price per Gallon</span>
                  <span>${{ delivery.customer_price }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span>Gallons Ordered</span>
                  <span>
                    <span v-if="delivery.customer_asked_for_fill == 1" class="badge badge-info">FILL (250 gal estimate)</span>
                    <span v-else>{{ delivery.gallons_ordered }} Gallons</span>
                  </span>
                </div>
                <div v-if="delivery.prime == 1" class="flex justify-between text-sm">
                  <span>Prime Fee</span>
                  <span>+ ${{ pricing.price_prime }}</span>
                </div>
                <div v-if="delivery.emergency == 1" class="flex justify-between text-sm">
                  <span>Emergency Fee</span>
                  <span>+ ${{ pricing.price_emergency }}</span>
                </div>
                <div v-if="delivery.same_day == 1" class="flex justify-between text-sm">
                  <span>Same Day Fee</span>
                  <span>+ ${{ pricing.price_same_day }}</span>
                </div>
                <div v-if="promo_active" class="flex justify-between text-sm text-success">
                  <span>Promo: {{ promo.name_of_promotion }}</span>
                  <span>- ${{ discount }}</span>
                </div>

                <div class="divider my-1"></div>

                <div class="flex justify-between items-center">
                  <span class="text-lg font-bold">Total to be Charged</span>
                  <span class="text-2xl font-bold text-accent">
                    ${{ calculateTotalAmount() }}
                  </span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- Actions Card -->
          <div class="bg-neutral rounded-lg p-5">
             <div class="flex flex-wrap gap-4 justify-between items-center">
                <!-- Pay Authorize Button -->
                <button class="btn btn-warning" @click="$router.push({ name: 'authorizePreauthCharge', params: { id: $route.params.id } })">
                  Pay Authorize.net
                </button>
                <!-- A single confirm button is cleaner -->
                <button class="btn btn-primary" @click="checkoutOilUpdatePayment(1)">
                  Pay Tiger
                </button>
                <router-link v-if="delivery && delivery.id" :to="{ name: 'deliveryEdit', params: { id: delivery.id } }">
                  <button class="btn btn-sm btn-ghost">Edit Delivery</button>
                </router-link>
            </div>
          </div>

        </div>
      </div>
    </div>
  </div>

  <Footer />
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import axios from 'axios'
import authHeader from '../../../services/auth.header'
import Header from '../../../layouts/headers/headerauth.vue'
import SideBar from '../../../layouts/sidebar/sidebar.vue'
import Footer from '../../../layouts/footers/footer.vue'

import useValidate from "@vuelidate/core";
import { notify } from "@kyvg/vue3-notification"
import { minLength, required } from "@vuelidate/validators";

export default defineComponent({
  name: 'PayOil',

  components: {
    Header,
    SideBar,
    Footer,
  },

  data() {
    return {
      v$: useValidate(),
      loaded: false,
      user: {
        user_id: 0,
      },
      delivery: {
        id: 0,
        customer_id: 0,
        customer_name: '',
        customer_address: '',
        customer_town: '',
        customer_state: 0,
        customer_zip: '',
        gallons_ordered: 0,
        customer_asked_for_fill: 0,
        gallons_delivered: 0,
        customer_filled: 0,
        delivery_status: 0,
        when_ordered: '',
        when_delivered: '',
        expected_delivery_date: '',
        automatic: 0,
        oil_id: 0,
        supplier_price: 0,
        customer_price: 0,
        customer_temperature: 0,
        dispatcher_notes: '',
        prime: 0,
        promo_id: 0,
        emergency: 0,
        same_day: 0,
        payment_type: 0,
        payment_card_id: 0,
        driver_employee_id: 0,
        driver_first_name: '',
        driver_last_name: '',
        pre_charge_amount: 0,
        total_price: 0,

      },
      credit_cards: [
        {
          id: 0,
          name_on_card: '',
          main_card: false,
          card_number: '',
          expiration_month: '',
          type_of_card: '',
          last_four_digits: '',
          expiration_year: '',
          security_number: '',

        }
      ],

      stripe: null,
      customer: {
        id: 0,
        user_id: 0,
        customer_first_name: '',
        customer_last_name: '',
        customer_town: '',
        customer_address: '',
        customer_state: 0,
        customer_zip: '',
        customer_apt: '',
        customer_home_type: 0,
        customer_phone_number: '',
        account_number: '',
      },
      pricing: {
        price_from_supplier: 0,
        price_for_customer: 0,
        price_for_employee: 0,
        price_same_day: 0,
        price_prime: 0,
        price_emergency: 0,
        date: "",
      },
      promo_active: false,
      promo: {
        name_of_promotion: '',
        description: '',
        money_off_delivery: 0,
        text_on_ticket: ''
      },
      priceprime: 0,
      pricesameday: 0,
      priceemergency: 0,
      total_amount: 0,
      discount: 0,
      total_amount_after_discount: 0,
    }
  },
  validations() {
    return {
      CreateOilOrderForm: {
        basicInfo: {
          gallons_ordered: { required, minLength: minLength(1) },
          expected_delivery_date: { required },
        },
      },
    };
  },
  created() {
    this.userStatus()

  },
  watch: {
    $route() {

    },
  },
  mounted() {
    this.getOilOrder(this.$route.params.id)
    this.sumdelivery(this.$route.params.id);
    this.getOilPricing()
    this.updatestatus();

  },

  methods: {
        updatestatus() {
      let path = import.meta.env.VITE_BASE_URL + '/delivery/updatestatus';
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        if (response.data.update)
          console.log("Updated Status of Deliveries")
      })
    },
    sumdelivery(delivery_id: any) {
      let path = import.meta.env.VITE_BASE_URL + "/delivery/total/" + delivery_id;
      axios({
        method: "get",
        url: path,
        withCredentials: true,
      })
        .then((response: any) => {
          if (response.data.ok) {
 
      
            this.priceprime = response.data.priceprime;
            this.pricesameday = response.data.pricesameday;
            this.priceemergency = response.data.priceemergency;
            this.total_amount = response.data.total_amount;
            this.discount = response.data.discount;
            this.total_amount_after_discount = response.data.total_amount_after_discount;
        
          }
        })
        .catch(() => {
          notify({
            title: "Error",
            text: "Could not get oil pricing 1",
            type: "error",
          });
        });
    },
    getPromo(promo_id: any) {
      let path = import.meta.env.VITE_BASE_URL + "/promo/" + promo_id;
      axios({
        method: "get",
        url: path,
        withCredentials: true,
        headers: authHeader(),
      })
        .then((response: any) => {
          if (response.data) {
            this.promo = response.data
        
          }
        })
    },
    userStatus() {
      let path = import.meta.env.VITE_BASE_URL + '/auth/whoami';
      axios({
        method: 'get',
        url: path,
        withCredentials: true,
        headers: authHeader(),
      })
        .then((response: any) => {
          if (response.data.ok) {
            this.user = response.data.user;
          }
        })

    },
    getOilPricing() {
      let path = import.meta.env.VITE_BASE_URL + "/info/price/oil/table";
      axios({
        method: "get",
        url: path,
        withCredentials: true,
      })
        .then((response: any) => {
          this.pricing = response.data;
        })
        .catch(() => {
          notify({
            title: "Error",
            text: "Could not get oil pricing 2",
            type: "error",
          });
        });
    },
    getOilOrder(delivery_id: any) {
      let path = import.meta.env.VITE_BASE_URL + "/delivery/order/" + delivery_id;
      axios({
        method: "get",
        url: path,
        withCredentials: true,
      })
        .then((response: any) => {
          console.log("=== DEBUG: API Response:", response.data);
          if (response.data && response.data.ok) {
            console.log("=== DEBUG: Delivery data from API:", response.data.delivery);
            console.log("=== DEBUG: Delivery ID from API:", response.data.delivery?.id);
            this.delivery = response.data.delivery;
            console.log("=== DEBUG: Delivery object after assignment:", this.delivery);
            console.log("=== DEBUG: Delivery ID after assignment:", this.delivery.id);
            this.getCustomer(this.delivery.customer_id)
            this.getCreditCards(this.delivery.customer_id)
            if (this.delivery.promo_id != null) {
                this.getPromo(this.delivery.promo_id);
                this.promo_active = true;
              }
          } else {
            console.error("API Error:", response.data.error || "Failed to fetch delivery data.");
          }
        })
        .catch((error: any) => {
          console.error("=== DEBUG: API Error in getOilOrder:", error);
          notify({
            title: "Error",
            text: "Could not get delivery",
            type: "error",
          });
        });
    },
    getCreditCards(user_id: any) {
      let path = import.meta.env.VITE_BASE_URL + '/payment/cards/' + user_id;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {

        this.credit_cards = response.data
      })
    },
    getCustomer(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/customer/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.customer = response.data
      })
    },
    calculateTotalAmount() {
      if (this.total_amount_after_discount == null || this.total_amount_after_discount === undefined) {
        return '0.00';
      }

      let totalNum = Number(this.total_amount_after_discount);
      if (isNaN(totalNum)) {
        return '0.00';
      }

      if (this.delivery && this.delivery.prime == 1 && this.pricing && this.pricing.price_prime) {
        totalNum += Number(this.pricing.price_prime) || 0;
      }
      if (this.delivery && this.delivery.same_day == 1 && this.pricing && this.pricing.price_same_day) {
        totalNum += Number(this.pricing.price_same_day) || 0;
      }
      if (this.delivery && this.delivery.emergency == 1 && this.pricing && this.pricing.price_emergency) {
        totalNum += Number(this.pricing.price_emergency) || 0;
      }

      return totalNum.toFixed(2);
    },

    checkoutOilUpdatePayment(payment_type: number) {
      let path = import.meta.env.VITE_BASE_URL + "/delivery/cash/" + this.delivery.id + '/' + payment_type;
      axios({
        method: "PUT",
        url: path,
      })
        .then((response: any) => {
          if (response.data.ok) {
            if (payment_type == 0) {
              notify({
                title: "Success",
                text: "marked payment as cash (COD)",
                type: "success",
              });
            }
            if (payment_type == 1) {
              notify({
                title: "Success",
                text: "marked payment as credit card",
                type: "success",
              });
            }

            if (payment_type == 2) {
              notify({
                title: "Success",
                text: "marked payment as cash (COD) and credit card partial payment",
                type: "success",
              });
            }
            if (payment_type == 3) {
              notify({
                title: "Success",
                text: "marked payment as check with credit card hold",
                type: "success",
              });
            }
            if (payment_type == 11) {
              notify({
                title: "Success",
                text: "marked payment as CC - Authorize (API)",
                type: "success",
              });
            }
            this.$router.push({ name: "deliveryOrder", params: { id: this.delivery.id } });
          }
        })
        .catch(() => {
          notify({
            title: "Error",
            text: "Could not update wth cash",
            type: "error",
          });
        });
    },



  },
})
</script>

<style scoped></style>
