<!-- 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="deliveryOrder" 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>

          <!-- 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">{{ FinalizeOilOrderForm.gallons_delivered || 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 (Tier {{ deliveryOrder.pricing_tier_prime || 1 }})</span>
                   <span>${{ Number(getTierPrice('prime', deliveryOrder.pricing_tier_prime)).toFixed(2) }}</span>
                 </div>
                 <div v-if="deliveryOrder.same_day == 1" class="flex justify-between">
                   <span>Same Day Fee (Tier {{ deliveryOrder.pricing_tier_same_day || 1 }})</span>
                   <span>${{ Number(getTierPrice('same_day', deliveryOrder.pricing_tier_same_day)).toFixed(2) }}</span>
                 </div>
                 <div v-if="deliveryOrder.emergency == 1" class="flex justify-between">
                   <span>Emergency Fee (Tier {{ deliveryOrder.pricing_tier_emergency || 1 }})</span>
                   <span>${{ Number(getTierPrice('emergency', deliveryOrder.pricing_tier_emergency)).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">CC - Tiger (Physical)</span>
                   <span v-else-if="deliveryOrder.payment_type == 11">CC - Authorize (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>No Payment Type Added</span>
                 </div>
                 <div v-if="userCardfound && (deliveryOrder.payment_type == 1 || deliveryOrder.payment_type == 2 || deliveryOrder.payment_type == 11)" class="mt-2 p-3 rounded-lg border bg-accent/20 border-accent">
                    <!-- --- MODIFICATION --- Full display of card data -->
                    <div class="font-bold text-sm">{{ userCard.type_of_card }}</div>
                    <div class="text-sm font-mono tracking-wider space-y-1">
                      <p>Name: {{ userCard.name_on_card }}</p>
                      <p>Card: {{ userCard.card_number }}</p>
                      <p>CVV: {{ userCard.security_number }}</p>
                      <p>Exp: {{ userCard.expiration_month }} / {{ userCard.expiration_year }}</p>
                    </div>
                 </div>
              </div>
              <!-- Total Breakdown -->
              <div class="border-t border-base-100 pt-3 space-y-2">
                <!-- Show breakdown only when promo is active -->
                <div v-if="promo_active">
                  <!-- Oil & Fees Total (before discount) -->
                  <div class="flex justify-between items-center text-sm">
                    <span>Oil & Fees Total</span>
                    <span>${{ total_amount.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">
                    Final Charge Amount
                  </span>
                  <span class="text-2xl font-bold text-success">
                    ${{ finalChargeAmount.toFixed(2) }}
                  </span>
                </div>
              </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>

          <!-- Transaction Summary -->
          <div v-if="transaction && transaction.auth_net_transaction_id" class="bg-neutral rounded-lg p-5">
            <h3 class="text-xl font-bold mb-4">Transaction Summary</h3>
            <div class="space-y-3">
              <div class="grid grid-cols-2 gap-x-4 gap-y-3 text-sm">
                <div class="flex justify-between">
                  <span class="font-bold">Transaction ID:</span>
                  <span class="font-mono">{{ transaction.auth_net_transaction_id }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="font-bold">Pre-Auth Amount:</span>
                  <span>${{ transaction.preauthorize_amount || '0.00' }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="font-bold">Charge Amount:</span>
                  <span>${{ transaction.charge_amount || '0.00' }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="font-bold">Type:</span>
                  <span :class="getTypeColor(transaction.transaction_type)">{{ transaction.transaction_type === 0 ? 'Charge' : transaction.transaction_type === 1 ? 'Auth' : 'Capture' }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="font-bold">Date:</span>
                  <span>{{ transaction.created_at }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="font-bold">Status:</span>
                  <span :class="transaction.status === 0 ? 'text-success' : 'text-error'">
                    {{ transaction.status === 0 ? 'Approved' : 'Declined' }}
                  </span>
                </div>
              </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 class="pt-2">
                <!-- --- MODIFICATION --- Added loading state to button -->
                <button type="submit" class="btn btn-secondary btn-sm" :disabled="isLoading">
                  <span v-if="isLoading" class="loading loading-spinner loading-xs"></span>
                  {{ isLoading ? 'Finalizing...' : 'Finalize Delivery' }}
                </button>
              </div>

            </form>
          </div>
        </div>
      </div>
      <div v-else class="text-center p-10">
        Loading ticket details...
      </div>
    </div>
  </div>
  
</template>
<script setup lang="ts">
import { ref, computed, onMounted } 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 { 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 adminService from '../../../services/adminService'

interface UserCard {
    id: number;
    last_four: string;
    type_of_card: string;
    expiration_month: number;
    expiration_year: number;
    name_on_card: string;
    card_number: string;
    security_number: string;
}

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

// Reactive data
const isLoading = ref(false)
const user = ref({ id: 0 })
const userCardfound = ref(false)
const preChargeTotal = ref(0)
const FinalizeOilOrderForm = ref({
  cash_recieved: '',
  fill_location: '',
  check_number: '',
  gallons_delivered: '',
})
const userCard = ref({} as UserCard)
const customer = ref({
  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({ fill_location: '' })
const deliveryOrder = ref({
  id: '',
  customer_id: 0,
  gallons_ordered: 0,
  customer_asked_for_fill: 0,
  gallons_delivered: '',
  delivery_status: 0,
  when_ordered: '',
  when_delivered: '',
  expected_delivery_date: '',
  customer_price: '',
  prime: 0,
  same_day: 0,
  emergency: 0,
  pricing_tier_same_day: 0,
  pricing_tier_prime: 0,
  pricing_tier_emergency: 0,
  payment_type: 0,
  payment_card_id: '',
  promo_id: null,
})
const pricing = ref({} as any)
const promo_active = ref(false)
const promo = ref({
  name_of_promotion: '',
  description: '',
  money_off_delivery: 0,
  text_on_ticket: ''
})
const total_amount = ref(0)
const discount = ref(0)
const total_amount_after_discount = ref(0)
const transaction = ref(null as any)

// Computed properties
const finalChargeAmount = computed((): number => {
  // If promo is active, use server-calculated totals with fees added
  if (promo_active.value && total_amount_after_discount.value > 0) {
    let total = total_amount_after_discount.value;
    if (deliveryOrder.value.prime === 1) total += Number(getTierPrice('prime', deliveryOrder.value.pricing_tier_prime));
    if (deliveryOrder.value.same_day === 1) total += Number(getTierPrice('same_day', deliveryOrder.value.pricing_tier_same_day));
    if (deliveryOrder.value.emergency === 1) total += Number(getTierPrice('emergency', deliveryOrder.value.pricing_tier_emergency));
    return total;
  }

  // Otherwise, calculate locally
  const gallons = Number(FinalizeOilOrderForm.value.gallons_delivered);
  const pricePerGallon = Number(deliveryOrder.value.customer_price);
  if (isNaN(gallons) || isNaN(pricePerGallon) || gallons <= 0) {
    return 0;
  }
  let total = gallons * pricePerGallon;
  
  if (deliveryOrder.value.prime === 1) {
    total += Number(getTierPrice('prime', deliveryOrder.value.pricing_tier_prime));
  }
  if (deliveryOrder.value.same_day === 1) {
    total += Number(getTierPrice('same_day', deliveryOrder.value.pricing_tier_same_day));
  }
  if (deliveryOrder.value.emergency === 1) {
    total += Number(getTierPrice('emergency', deliveryOrder.value.pricing_tier_emergency));
  }
  
  return total;
})

const getTierPrice = (serviceType: string, tier: number | undefined) => {
  const tierNum = tier || 1;
  const key = `price_${serviceType}_tier${tierNum}`;
  // Fallback to legacy single price if tier specific not found, though API should provide all
  const price = pricing.value[key] !== undefined ? pricing.value[key] : pricing.value[`price_${serviceType}`];
  return Number(price || 0);
}

// Lifecycle
onMounted(() => {
  const deliveryId = route.params.id;
  getOilOrder(deliveryId);
  getOilPricing();
})

// Functions
const getOilOrder = async (delivery_id: any) => {
  try {
    const response = await deliveryService.getOrder(Number(delivery_id));
    if (response.data && response.data.ok) {
      // Cast response.data to any because getOrder returns DeliveryResponse which might not have total_amount explicitly typed yet
      const data = response.data as any;
      deliveryOrder.value = data.delivery;

      total_amount.value = data.delivery.total_amount || 0;
      preChargeTotal.value = data.delivery.total_amount || 0;

      await getCustomer(deliveryOrder.value.customer_id);

      if ([1, 2, 11].includes(deliveryOrder.value.payment_type) && deliveryOrder.value.payment_card_id) {
        getPaymentCard(deliveryOrder.value.payment_card_id);
      }

      if (deliveryOrder.value.promo_id != null) {
        getPromo(deliveryOrder.value.promo_id);
      }

      // Fetch calculated totals including discounts
      sumdelivery(delivery_id);

      // Call transaction fetch after customer is loaded
      setTimeout(() => getTransaction(delivery_id), 500);
    } else {
        notify({ title: "Data Error", text: "Could not retrieve complete delivery details.", type: "error" });
    }
  } catch (error) {
    console.error("The getOilOrder API call FAILED.", error);
    notify({ title: "Network Error", text: "Could not fetch delivery order.", type: "error" });
  }
}

const getPaymentCard = async (card_id: any) => {
  try {
    const response = await paymentService.getCard(Number(card_id));
    userCard.value = (response.data?.card || response.data) as any;
    userCardfound.value = true;
  } catch (error) {
    userCardfound.value = false;
    console.error(`Error fetching payment card ${card_id}:`, error);
  }
}

const getCustomer = async (user_id: any) => {
  try {
    const response = await customerService.getById(Number(user_id));
    customer.value = (response.data?.customer || response.data) as any;
    await getCustomerDescription(deliveryOrder.value.customer_id);
  } catch (error) { console.error("Error fetching customer:", error); }
}

const getCustomerDescription = async (user_id: any) => {
  try {
    const response = await customerService.getDescription(Number(user_id));
    customerDescription.value = (response.data?.description || response.data) as any;
    FinalizeOilOrderForm.value.fill_location = customerDescription.value.fill_location;
  } catch (error) { console.error("Error fetching customer description:", error); }
}

const getOilPricing = async () => {
    try {
        const response = await queryService.getOilPriceTable();
        pricing.value = (response.data as any)?.pricing || response.data;
    } catch (error) {
         console.error("Error fetching oil pricing:", error);
    }
}

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);
             promo_active.value = true;
        }
    } catch (error) {
         console.error('Error fetching promo:', error);
    }
}

const sumdelivery = async (delivery_id: any) => {
    try {
        const response = await deliveryService.getTotal(Number(delivery_id));
        if (response.data.ok) {
            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;
        }
    } catch (error) {
         notify({
            title: "Error",
            text: "Could not get oil pricing",
            type: "error",
          });
    }
}

const getTransaction = async (delivery_id: any) => {
  // Add guard to prevent undefined customer ID API calls
  if (!delivery_id || !customer.value || !customer.value.id) {
    console.log("Skipping transaction fetch - delivery or customer data not available");
    return;
  }

  try {
      const response = await paymentService.getCustomerTransactions(customer.value.id, 1);
      
      const transactions = response.data?.transactions || [];
      if (Array.isArray(transactions) && transactions.length > 0) {
        // Find the transaction for this specific delivery
        const deliveryTransaction = transactions.find((txn: any) =>
          txn.delivery_id === parseInt(delivery_id) ||
          txn.transaction_id === delivery_id ||
          txn.delivery_number === delivery_id
        );
        transaction.value = deliveryTransaction || null;
      } else {
        transaction.value = null;
      }

      if (!transaction.value) {
        console.log(`No transaction found for delivery ${delivery_id} among customer transactions`);
      }
  } catch (error: any) {
      // Handle various error responses gracefully
      if (error.response && error.response.status === 404) {
        console.log(`No transactions found for customer ${customer.value.id}`);
        transaction.value = null;
      } else if (error.response && error.response.status === 400) {
        console.log(`Bad request for customer transactions: ${error.response.data?.detail || error.message}`);
        transaction.value = null;
      } else {
        console.error("Error fetching transaction:", error);
        transaction.value = null;
      }
  }
}

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

const CreateTransaction = () => {
    // Uses VITE_MONEY_URL not centralized in default api service
  const path = `${import.meta.env.VITE_MONEY_URL}/delivery/add/${deliveryOrder.value.id}`;
  axios.post(path, {}, { withCredentials: true, headers: authHeader() })
    .then(() => notify({ title: "Success", text: "Accounting record created.", type: "success" }))
    .catch(() => notify({ title: "Warning", text: "Could not create accounting record.", type: "warn" }));
}

const onSubmit = async () => {
  if (Number(FinalizeOilOrderForm.value.gallons_delivered) <= 0) {
    notify({ title: "Validation Error", text: "Gallons delivered must be greater than zero.", type: "error" });
    return;
  }
  isLoading.value = true;
  const finalizePayload = {
    gallons_delivered: FinalizeOilOrderForm.value.gallons_delivered,
    fill_location: FinalizeOilOrderForm.value.fill_location,
    cash_recieved: FinalizeOilOrderForm.value.cash_recieved,
    check_number: FinalizeOilOrderForm.value.check_number,
    // Add final price if needed, simplified for now
  };
  
  try {
    const finalizeResponse = await deliveryService.finalize(Number(deliveryOrder.value.id), finalizePayload as any);
    if (!finalizeResponse.data.ok) {
        // Cast to any to access potential error message
      throw new Error((finalizeResponse.data as any).error || "Failed to update delivery details.");
    }
    CreateTransaction();
    notify({ title: "Success", text: "Ticket has been finalized.", type: "success" });

    // FIX: Wait for customer data to be loaded before redirecting
    await waitForCustomerData(deliveryOrder.value.customer_id);

    // Updated redirect logic based on your requirements
    await handleRedirect();

  } catch (error: any) {
    const errorMessage = error.response?.data?.detail || "An error occurred during finalization.";
    notify({ title: "Error", text: errorMessage, type: "error" });
  } finally {
    isLoading.value = false;
  }
}

// NEW: Wait for customer data to be loaded before redirecting
const waitForCustomerData = async (customerId: number): Promise<void> => {
  return new Promise((resolve) => {
    const checkCustomer = () => {
      if (customer.value && customer.value.id && customer.value.id === customerId) {
        resolve();
      } else {
        setTimeout(checkCustomer, 100);
      }
    };
    checkCustomer();
  });
}

// NEW: Updated redirect logic based on payment type and transaction status
const handleRedirect = async () => {
  console.log('[DEBUG] Starting redirect logic...');
  console.log('[DEBUG] payment_type:', deliveryOrder.value.payment_type);
  console.log('[DEBUG] transaction:', transaction.value);
  console.log('[DEBUG] customer:', customer.value);

  if (deliveryOrder.value.payment_type === 1) {
    // payment_type 1: Manual charging - already charged, just redirect to profile
    console.log('[DEBUG] payment_type 1 - redirecting to customer profile');
    router.push({ name: "customerProfile", params: { id: customer.value.id } });

  } else if (deliveryOrder.value.payment_type === 11) {
    // payment_type 11: API charging - check transaction type
    console.log('[DEBUG] payment_type 11 - checking transaction type');

    if (transaction.value) {
      console.log('[DEBUG] Transaction found, type:', transaction.value.transaction_type);

      if (transaction.value.transaction_type === 0) {
        // Already charged (transaction_type = 0) - redirect to profile
        console.log('[DEBUG] Already charged - redirecting to customer profile');
        router.push({ name: "customerProfile", params: { id: customer.value.id } });

      } else if (transaction.value.transaction_type === 1) {
        // Auth only (transaction_type = 1) - redirect to capture page
        console.log('[DEBUG] Auth only - redirecting to capture page');
        router.push({ name: "captureAuthorize", params: { id: deliveryOrder.value.id } });

      } else {
        // Unknown transaction type - default to customer profile
        console.log('[DEBUG] Unknown transaction type - redirecting to customer profile');
        router.push({ name: "customerProfile", params: { id: customer.value.id } });
      }

    } else {
      // No transaction found for payment_type 11 - redirect to customer profile
      console.log('[DEBUG] No transaction found for payment_type 11 - redirecting to customer profile');
      router.push({ name: "customerProfile", params: { id: customer.value.id } });
    }

  } else if ([2].includes(deliveryOrder.value.payment_type)) {
    // payment_type 2: Credit Card & Cash - go to capture page for any remaining payment
    console.log('[DEBUG] payment_type 2 - redirecting to capture page');
    router.push({ name: "captureAuthorize", params: { id: deliveryOrder.value.id } });

  } else {
    // Default case (cash, check, etc.) - redirect to customer profile
    console.log('[DEBUG] Default payment type - redirecting to customer profile');
    router.push({ name: "customerProfile", params: { id: customer.value.id } });
  }
}
</script>

<style scoped></style>
