<!-- src/pages/pay/oil/authorize_preauthcharge.vue -->
<template>
  <div class="flex">

    
    <!-- Main Content -->
    <div class="flex-1 px-8 py-6">

      <!-- Breadcrumbs & Header -->
      <div class="text-sm breadcrumbs mb-6">
        <ul>
          <li><router-link :to="{ name: 'home' }">Home</router-link></li>
          <li><router-link :to="{ name: 'payOil', params: { id: deliveryId } }">Payment Confirmation</router-link></li>
          <li>Payment Authorization</li>
        </ul>
      </div>

      <!-- 2x2 Grid Layout -->
      <div class="max-w-6xl">
        <h1 class="text-3xl font-bold mb-8">Payment Authorization Authorize.net</h1>

        <!-- Top Row: Charge Breakdown and Payment Method -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
          <!-- Charge Breakdown -->
          <div class="bg-base-100 rounded-lg p-6">
            <h3 class="text-lg font-semibold mb-4">Charge Breakdown</h3>
            <div class="space-y-2">
              <div class="flex justify-between">
                <span>Gallons Ordered:</span>
                <span>{{ delivery.gallons_ordered || 0 }} gallons</span>
              </div>
              <div class="flex justify-between">
                <span>Price per Gallon:</span>
                <span>${{ delivery.customer_price || 0 }}</span>
              </div>
              <div class="flex justify-between font-semibold">
                <span>Subtotal:</span>
                <span>${{ calculateSubtotal() }}</span>
              </div>
              <div v-if="delivery.prime == 1" class="flex justify-between text-sm">
                <span>Prime Fee:</span>
                <span>+ ${{ pricing.price_prime || 0 }}</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 || 0 }}</span>
              </div>
              <div v-if="delivery.emergency == 1" class="flex justify-between text-sm">
                <span>Emergency Fee:</span>
                <span>+ ${{ pricing.price_emergency || 0 }}</span>
              </div>
              <div v-if="promo_active" class="flex justify-between text-success">
                <span>{{ promo.name_of_promotion }}:</span>
                <span>- ${{ discount }}</span>
              </div>
              <hr class="my-3">
              <div class="flex justify-between font-bold text-lg">
                <span>Total:</span>
                <span>${{ promo_active ? total_amount_after_discount : total_amount }}</span>
              </div>
            </div>
          </div>

          <!-- Credit Card Display -->
          <div class="bg-base-100 rounded-lg p-6">
            <h3 class="text-lg font-semibold mb-4">Payment Method</h3>
            <div v-if="selectedCard" class="bg-base-200 p-4 rounded-md">
              <div class="flex justify-between items-center mb-2">
                <div class="font-semibold">{{ selectedCard.type_of_card }}</div>
                <div v-if="selectedCard.main_card" class="badge badge-primary">Primary</div>
              </div>
              <div class="font-mono text-sm">
                <div> {{ selectedCard.card_number }}</div>
                <div>{{ selectedCard.name_on_card }}</div>
                <div>Expires: {{ selectedCard.expiration_month }}/{{ selectedCard.expiration_year }}</div>
              </div>
            </div>
            <div v-else class="text-gray-500 p-4">
              No payment method selected
            </div>
          </div>
        </div>

        <!-- Error/Success Messages -->
        <div class="mb-6">
          <div v-if="error" class="alert alert-error">
            <span>{{ error }}</span>
          </div>
          <div v-if="success" class="alert alert-success">
            <span>{{ success }}</span>
          </div>
        </div>

        <!-- Bottom Section: Charge Amount Input and Action Buttons -->
        <div class="bg-base-100 rounded-lg p-6">
          <div class="flex flex-col lg:flex-row lg:items-center gap-6">
            <!-- Charge Amount Input - Compact -->
            <div class="flex-1">
              <h3 class="text-lg font-semibold mb-2">Charge Amount</h3>
              <div class="flex">
                <span class="inline-flex items-center px-3 text-sm bg-base-200 rounded-l-lg border border-r-0">$</span>
                <input
                  v-model="chargeAmount"
                  type="number"
                  step="0.01"
                  class="input input-bordered flex-1 rounded-l-none"
                  placeholder="Enter amount"
                  :disabled="loading"
                />
              </div>
            </div>

            <!-- Action Buttons -->
            <div class="flex gap-3 align-bottom">
              <router-link :to="{ name: 'payOil', params: { id: deliveryId } }">
                <button class="btn btn-ghost">Cancel</button>
              </router-link>
              <button
                @click="handlePreauthorize"
                class="btn btn-warning"
                :disabled="loading || !chargeAmount"
              >
                <span v-if="loading && action === 'preauthorize'" class="loading loading-spinner loading-sm"></span>
                Preauthorize
              </button>
              <button
                @click="handleChargeNow"
                class="btn btn-primary"
                :disabled="loading || !chargeAmount"
              >
                <span v-if="loading && action === 'charge'" class="loading loading-spinner loading-sm"></span>
                Charge Now
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, watch } from 'vue'
import axios from 'axios'
import authHeader from '../../../services/auth.header'
import { notify } from "@kyvg/vue3-notification"

export default defineComponent({
  name: 'AuthorizePreauthCharge',

  data() {
    return {
      deliveryId: this.$route.params.id as string,
      loaded: false,
      chargeAmount: 0,
      loading: false,
      action: '', // 'preauthorize' or 'charge'
      error: '',
      success: '',
      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,
        service_id: null,
      },
      credit_cards: [
        {
          id: 0,
          name_on_card: '',
          main_card: false,
          card_number: '',
          expiration_month: '',
          type_of_card: '',
          last_four_digits: '',
          expiration_year: '',
          security_number: '',

        }
      ],
      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: ''
      },
      total_amount: 0,
      discount: 0,
      total_amount_after_discount: 0,
    }
  },

  computed: {
    selectedCard(): any {
      return this.credit_cards.find((card: any) => card.id === this.delivery.payment_card_id)
    }
  },

  mounted() {
    this.loadData(this.deliveryId)
  },

  created() {
    this.watchRoute()
  },

  methods: {
    watchRoute() {
      watch(
        () => this.$route.params.id,
        (newId) => {
          if (newId !== this.deliveryId) {
            this.resetState()
            this.deliveryId = newId as string
            this.loadData(newId as string)
          }
        }
      )
    },

    resetState() {
      this.loading = false
      this.action = ''
      this.error = ''
      this.success = ''
      this.chargeAmount = 0
      this.promo_active = false
      this.total_amount = 0
      this.discount = 0
      this.total_amount_after_discount = 0
      this.deliveryId = this.$route.params.id as string
    },

    loadData(deliveryId: string) {
      this.userStatus()
      this.getOilOrder(deliveryId)
      this.sumdelivery(deliveryId)
      this.getOilPricing()
      this.updatestatus()
    },

    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.total_amount = response.data.total_amount;
            this.discount = response.data.discount;
            this.total_amount_after_discount = response.data.total_amount_after_discount;

            // Auto-populate charge amount with the calculated total
            if (this.promo_active) {
              this.chargeAmount = this.total_amount_after_discount;
            } else {
              this.chargeAmount = this.total_amount;
            }
          }
        })
        .catch(() => {
          notify({
            title: "Error",
            text: "Could not get oil pricing",
            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
            this.promo_active = true

            // Update charge amount when promo is applied
            if (this.total_amount_after_discount > 0) {
              this.chargeAmount = this.total_amount_after_discount
            }
          }
        })
    },

    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",
            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) => {
          if (response.data && response.data.ok) {
            this.delivery = response.data.delivery;
            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("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
      })
    },

    calculateSubtotal() {
      const gallons = this.delivery.gallons_ordered || 0
      const pricePerGallon = this.delivery.customer_price || 0
      return (gallons * pricePerGallon).toFixed(2)
    },

    async handlePreauthorize() {
      await this.processPayment('preauthorize')
    },

    async handleChargeNow() {
      await this.processPayment('charge')
    },

    async processPayment(actionType: string) {
      if (!this.selectedCard) {
        this.error = 'No credit card found for this customer'
        return
      }

      this.loading = true
      this.action = actionType
      this.error = ''
      this.success = ''

      try {
        // Step 2: If payment method is credit, perform the pre-authorization
        if (actionType === 'preauthorize') {
          if (!this.chargeAmount || this.chargeAmount <= 0) {
            throw new Error("Pre-authorization amount must be greater than zero.");
          }

          const authPayload = {
            card_id: (this.selectedCard as any).id,
            preauthorize_amount: this.chargeAmount.toFixed(2),
            delivery_id: this.delivery.id,
          };

          const authPath = `${import.meta.env.VITE_AUTHORIZE_URL}/api/payments/authorize/saved-card/${this.customer.id}`;

          const response = await axios.post(authPath, authPayload, { withCredentials: true, headers: authHeader() });

          // On successful authorization, show success and redirect
          this.success = `Preauthorization successful! Transaction ID: ${response.data?.auth_net_transaction_id || 'N/A'}`;
          setTimeout(() => {
            this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
          }, 2000);
        } else { // Handle 'charge' action
          if (!this.chargeAmount || this.chargeAmount <= 0) {
            throw new Error("Charge amount must be greater than zero.");
          }

          // Create a payload that matches the backend's TransactionCreateByCardID schema
          const chargePayload = {
            card_id: (this.selectedCard as any).id,
            charge_amount: this.chargeAmount.toFixed(2),
            delivery_id: this.delivery.id,
            service_id: this.delivery.service_id || null,
            // You can add other fields here if your schema requires them
          };

          // Use the correct endpoint for charging a saved card
          const chargePath = `${import.meta.env.VITE_AUTHORIZE_URL}/api/charge/saved-card/${this.customer.id}`;

          console.log('=== DEBUG: Charge payload ===');
          console.log('Calling endpoint:', chargePath);
          console.log('Final payload being sent:', chargePayload);

          const response = await axios.post(chargePath, chargePayload, { withCredentials: true, headers: authHeader() });

          // Assuming your backend charge response has the same structure
          if (response.data && response.data.status === 'APPROVED') { // Adjust based on your actual response
            this.success = `Charge successful! Transaction ID: ${response.data.auth_net_transaction_id || 'N/A'}`;
            setTimeout(() => {
              this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
            }, 2000);
          } else {
            // The error message from your backend will be more specific now
            throw new Error(`Payment charge failed: ${response.data?.rejection_reason || 'Unknown error'}`);
          }
        }
      } catch (error: any) {
        this.error = error.response?.data?.detail || `Failed to ${actionType} payment`
        notify({
          title: "Error",
          text: this.error,
          type: "error",
        })
      } finally {
        this.loading = false
        this.action = ''
      }
    }
  },
})
</script>

<style scoped></style>
