<!-- src/pages/customer/profile/profile.vue -->
<template>
  <div class="w-full min-h-screen bg-base-200 px-4 md:px-10">
    <!-- ... breadcrumbs ... -->

    <div v-if="customer && customer.id" class="bg-neutral rounded-lg p-4 sm:p-6 mt-6">

      <!-- Current Plan Status Banner - Same as ServicePlanEdit.vue -->
      <div v-if="servicePlan && servicePlan.contract_plan > 0" class="alert alert-info mb-6"
        :class="servicePlan.contract_plan === 2 ? 'border-4 border-yellow-400 bg-yellow-50' : ''">
        <div class="flex items-center">
          <div class="flex-1">
            <div class="flex items-center gap-3">
              <h3 class="font-bold">Current Plan: {{ getPlanName(servicePlan.contract_plan) }}</h3>
              <!-- Premium Star Icon -->
              <svg v-if="servicePlan.contract_plan === 2" class="w-8 h-8 text-yellow-500 fill-current" fill="none"
                stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" />
              </svg>
            </div>
            <p>{{ servicePlan.contract_years }} Year{{ servicePlan.contract_years > 1 ? 's' : '' }} Contract</p>
            <p class="text-sm">Expires: {{ formatEndDate(servicePlan.contract_start_date, servicePlan.contract_years) }}
            </p>
          </div>
          <div class="badge" :class="getStatusBadge(servicePlan.contract_start_date, servicePlan.contract_years)">
            {{ getStatusText(servicePlan.contract_start_date, servicePlan.contract_years) }}
          </div>
        </div>
      </div>

      <!-- FIX: Changed `lg:` to `xl:` for a later breakpoint -->
      <div class="grid grid-cols-1 xl:grid-cols-12 gap-6">

        <!-- FIX: Changed `lg:` to `xl:` -->
        <div class="xl:col-span-8 space-y-6">

          <div class="grid grid-cols-1 xl:grid-cols-12 gap-6">
            <ProfileMap v-if="customer && customer.customer_latitude != null && customer.customer_longitude != null"
              class="xl:col-span-7" :customer="customer" />

            <!-- You can add a placeholder for when the map isn't ready -->
            <div v-else class="xl:col-span-7 bg-base-100 rounded-lg flex justify-center items-center">
              <p class="text-gray-400">Location not available...</p>
            </div>

            <ProfileSummary class="xl:col-span-5" :customer="customer" :automatic_status="automatic_status"
              :customer_description="customer_description.description" @toggle-automatic="userAutomatic" />
          </div>

          <HistoryTabs :deliveries="deliveries" :autodeliveries="autodeliveries" :service-calls="serviceCalls"
            :transactions="transactions" @open-service-modal="openEditModal" />
        </div>



        <!-- FIX: Changed `lg:` to `xl:` -->
        <div class="xl:col-span-4 space-y-6">
          <!-- Authorize.net Account Status Box -->
          <div v-if="customer.id" class="bg-base-100 rounded-lg p-4 border">
            <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between">
              <div class="flex items-center gap-3 mb-3 md:mb-0">
                <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v4a3 3 0 003 3z" />
                </svg>
                <span v-if="isLoadingAuthorize" class="text-sm font-medium">
                  <span class="loading loading-dots loading-xs mr-2"></span>
                  Loading...
                </span>
                <span v-else-if="authorizeCheck.valid_for_charging" class="text-sm font-medium">
                  Authorize Account ID: {{ customer.auth_net_profile_id }}
                </span>
                <span v-else class="text-sm font-medium text-red-600">
                  {{ getAccountStatusMessage() }}
                </span>
              </div>
              <div class="flex gap-2" v-if="!isLoadingAuthorize && !authorizeCheck.valid_for_charging">
                <!-- CREATE ACCOUNT SECTION - Only show when account doesn't exist -->
                <div class="flex gap-2">

                  <button @click="createAuthorizeAccount"
                    :class="['btn btn-sm', credit_cards_count === 0 ? 'btn-disabled' : 'btn-primary']"
                    :disabled="credit_cards_count === 0" v-if="credit_cards_count > 0">
                    Create Account
                  </button>
                  <button v-else @click="addCreditCard" class="btn btn-secondary btn-sm">
                    Add Card First
                  </button>
                </div>
              </div>
              <!-- DELETE ACCOUNT SECTION - Only show when account exists -->
              <div v-if="authorizeCheck.valid_for_charging" class="mt-3 lg:mt-0 lg:flex lg:gap-2">
                <button @click="showDeleteAccountModal" class="btn btn-error btn-sm lg:self-start">
                  Delete Account
                </button>
              </div>
            </div>
          </div>

          <CustomerComments :comments="comments" @add-comment="onSubmitSocial" @delete-comment="deleteCustomerSocial" />
          <CustomerStats :stats="customer_stats" :last_delivery="customer_last_delivery" />
          <TankInfo :customer_id="customer.id" :tank="customer_tank" :description="customer_description" />
          <EquipmentParts :parts="currentParts" @open-parts-modal="openPartsModal" />
          <CreditCards :cards="credit_cards" :count="credit_cards_count" :user_id="customer.id"
            :auth_net_profile_id="customer.auth_net_profile_id" @edit-card="editCard" @remove-card="removeCard" />

          <!-- Automatic Delivery Actions Box -->
          <div v-if="automatic_status === 1 && autodeliveries.length > 0" class="bg-base-100 rounded-lg p-4 border">
            <h3 class="font-semibold mb-4">Automatic Delivery Actions</h3>
            <div class="flex flex-wrap gap-2">
              <router-link v-if="autodeliveries[0].auto_status != 3"
                :to="{ name: 'payAutoAuthorize', params: { id: autodeliveries[0].id } }">
                <button class="btn btn-primary btn-sm">Preauthorize</button>
              </router-link>
              <router-link :to="{ name: 'finalizeTicketAutoNocc', params: { id: autodeliveries[0].id } }">
                <button class="btn btn-secondary btn-sm">Finalize</button>
              </router-link>
              <router-link v-if="autodeliveries[0].auto_status == 3"
                :to="{ name: 'finalizeTicketAuto', params: { id: autodeliveries[0].open_ticket_id || autodeliveries[0].id } }">
                <button class="btn btn-secondary btn-sm">Finalize</button>
              </router-link>
              <router-link :to="{ name: 'TicketAuto', params: { id: autodeliveries[0].id } }">
                <button class="btn btn-success btn-sm">Print Ticket</button>
              </router-link>
            </div>
          </div>

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

    <!-- A loading indicator is shown while the API call is in progress -->
    <div v-else class="flex justify-center items-center mt-20">
      <span class="loading loading-spinner loading-lg"></span>
    </div>

    <!-- The Footer can be placed here if it's specific to this page -->
    <Footer />
  </div>


  <!-- Modals remain at the root of the template for proper display -->
  <ServiceEditModal v-if="selectedServiceForEdit" :service="selectedServiceForEdit" @close-modal="closeEditModal"
    @save-changes="handleSaveChanges" @delete-service="handleDeleteService" />
  <PartsEditModal v-if="isPartsModalOpen && currentParts" :customer-id="customer.id" :existing-parts="currentParts"
    @close-modal="closePartsModal" @save-parts="handleSaveParts" />

  <!-- Delete Account Confirmation Modal -->
  <div class="modal" :class="{ 'modal-open': isDeleteAccountModalVisible }">
    <div class="modal-box">
      <h3 class="font-bold text-lg">Confirm Account Deletion</h3>
      <p class="py-4">This will permanently delete the Authorize.net account and remove all payment profiles. This
        action cannot be undone.</p>
      <div class="modal-action">
        <button @click="deleteAccount" class="btn btn-error">Delete Account</button>
        <button @click="isDeleteAccountModalVisible = false" class="btn">Cancel</button>
      </div>
    </div>
  </div>

  <!-- Create Account Progress Modal -->
  <div class="modal" :class="{ 'modal-open': isCreateAccountModalVisible }">
    <div class="modal-box">
      <h3 class="font-bold text-lg">Creating Authorize.net Account</h3>
      <div class="py-4 flex flex-col items-center">
        <div v-if="isCreatingAccount" class="text-center">
          <span class="text-lg mb-3">Setting up your payment account...</span>
          <div class="loading loading-spinner loading-lg text-primary mb-3"></div>
          <p class="text-sm text-gray-600">Please wait while we create your Authorize.net customer profile.</p>
        </div>
        <div v-else class="text-center">
          <div class="text-success mb-3">
            <svg class="w-12 h-12 mx-auto mb-2" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd"
                d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                clip-rule="evenodd" />
            </svg>
          </div>
          <p class="text-lg font-semibold mb-2">Account Created Successfully!</p>
          <div class="bg-base-200 p-3 rounded-lg mb-4">
            <p class="text-sm mb-1">Authorize.net Profile ID:</p>
            <p class="font-mono font-bold text-success">{{ createdProfileId }}</p>
          </div>
          <p class="text-sm text-gray-600">Your payment account is now ready for transactions.</p>
        </div>
      </div>
    </div>
  </div>

  <!-- Duplicate Account Error Modal -->
  <div class="modal" :class="{ 'modal-open': isDuplicateErrorModalVisible }">
    <div class="modal-box">
      <h3 class="font-bold text-lg text-error">⚠️ Duplicate Account Detected</h3>
      <div class="py-4 space-y-4">
        <div class="text-center">
          <svg class="w-16 h-16 mx-auto mb-4 text-warning" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
          </svg>
          <p class="text-lg font-semibold">Duplicate Account in Authorize.net</p>
          <p class="text-sm text-gray-600 mt-2">
            A duplicate account was found in your Authorize.net merchant account.
          </p>
          <p class="text-sm text-gray-600 mt-2">
            Customer ID: <strong>{{ customer.id }}</strong>
          </p>
        </div>

        <div class="bg-base-200 p-4 rounded-lg">
          <h4 class="font-semibold mb-2 text-warning">Action Required:</h4>
          <ul class="list-disc list-inside text-sm space-y-1">
            <li>Manually check your Authorize.net merchant dashboard</li>
            <li>Review existing customer profiles</li>
            <li>Contact support for linkage if needed</li>
          </ul>
          <p class="text-xs text-gray-500 mt-2">
            Inconsistency between your system and Authorize.net detected.
          </p>
        </div>

        <div class="text-center pt-2">
          <p class="text-xs text-gray-500">
            This profile may have been created previously and needs manual linking.
          </p>
        </div>
      </div>
      <div class="modal-action">
        <button class="btn btn-primary" @click="hideDuplicateErrorModal()">
          Acknowledge
        </button>
      </div>
    </div>
  </div>

</template>

<script lang="ts">
// --- SCRIPT REMAINS EXACTLY THE SAME AS YOUR ORIGINAL FILE ---
// All data properties, computed, methods, and imports are kept here.
// No changes are needed in the script block.
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";
import "leaflet/dist/leaflet.css";
import L from 'leaflet';
import iconUrl from 'leaflet/dist/images/marker-icon.png';
import shadowUrl from 'leaflet/dist/images/marker-shadow.png';
import { LMap, LTileLayer } from "@vue-leaflet/vue-leaflet";
import dayjs from 'dayjs';
import ServiceEditModal from '../../service/ServiceEditModal.vue';
import PartsEditModal from '../service/PartsEditModal.vue';

// Import new child components
import ProfileMap from './profile/ProfileMap.vue';
import ProfileSummary from './profile/ProfileSummary.vue';
import CustomerStats from './profile/CustomerStats.vue';
import TankInfo from './profile/TankInfo.vue';
import EquipmentParts from './profile/EquipmentParts.vue';
import CreditCards from './profile/CreditCards.vue';
import CustomerComments from './profile/CustomerComments.vue';
import HistoryTabs from './profile/HistoryTabs.vue';


L.Icon.Default.mergeOptions({
  iconUrl: iconUrl,
  shadowUrl: shadowUrl,
});

interface Delivery {
  id: number;
  delivery_status: number;
  customer_name: string;
  customer_asked_for_fill: number | boolean;
  gallons_ordered: number | string;
  gallons_delivered: number | string | null;
  expected_delivery_date: string;
}

interface AutomaticDelivery {
  id: number;
  customer_full_name: string;
  gallons_delivered: number | string;
  fill_date: string;
  auto_status: number | string;
  open_ticket_id: number | string;
}

interface CreditCard {
  id: number;
  main_card: boolean;
  type_of_card: string;
  name_on_card: string;
  card_number: string;
  expiration_month: number;
  expiration_year: string | number;
  zip_code: string;
  security_number: string;
}

// You already have these, just make sure they exist
interface ServiceCall {
  id: number;
  scheduled_date: string;
  customer_name: string;
  customer_address: string;
  customer_town: string;
  type_service_call: number;
  description: string;
}

interface ServiceParts {
  id?: number;
  customer_id: number;
  oil_filter: string;
  oil_filter_2: string;
  oil_nozzle: string;
  oil_nozzle_2: string;
  hot_water_tank: number;
}

interface ServicePlan {
  id: number;
  customer_id: number;
  contract_plan: number;
  contract_years: number;
  contract_start_date: string;
}



export default defineComponent({
  name: 'CustomerProfile',
  components: {
    Header,
    SideBar,
    Footer,
    LMap,
    LTileLayer,
    ServiceEditModal,
    PartsEditModal,
    // Register new components
    ProfileMap,
    ProfileSummary,
    CustomerStats,
    TankInfo,
    EquipmentParts,
    CreditCards,
    CustomerComments,
    HistoryTabs,
  },
  data() {
    return {
      zoom: 14,
      user: null as { user_id: number; user_name: string; confirmed: string; } | null,
      automatic_status: 0,
      customer_last_delivery: '',
      comments: [{ id: 0, created: '', customer_id: 0, poster_employee_id: 0, comment: '' }],
      CreateSocialForm: { basicInfo: { comment: '' } },

      // --- UPDATE THESE LINES ---
      credit_cards: [] as CreditCard[],
      deliveries: [] as Delivery[],
      autodeliveries: [] as AutomaticDelivery[],
      serviceCalls: [] as ServiceCall[],
      transactions: [] as any[],
      // --- END OF UPDATES ---
      automatic_response: 0,
      credit_cards_count: 0,
      customer: { id: 0, user_id: null as number | null, customer_first_name: '', customer_last_name: '', customer_town: '', customer_address: '', customer_state: 0, customer_zip: '', customer_apt: '', customer_home_type: 0, customer_phone_number: '', customer_latitude: 0, customer_longitude: 0, correct_address: true, account_number: '', auth_net_profile_id: null },
      customer_description: { id: 0, customer_id: 0, account_number: '', company_id: '', fill_location: 0, description: '' },
      customer_tank: { id: 0, last_tank_inspection: null, tank_status: false, outside_or_inside: false, tank_size: 0 },
      customer_stats: { id: 0, customer_id: 0, total_calls: 0, service_calls_total: 0, service_calls_total_spent: 0, service_calls_total_profit: 0, oil_deliveries: 0, oil_total_gallons: 0, oil_total_spent: 0, oil_total_profit: 0 },
      delivery_page: 1,
      selectedServiceForEdit: null as ServiceCall | null,
      isPartsModalOpen: false,
      currentParts: null as ServiceParts | null,
      servicePlan: null as ServicePlan | null,
      isLoadingAuthorize: true,
      authorizeCheck: { profile_exists: false, has_payment_methods: false, missing_components: [] as string[], valid_for_charging: false },
      isDeleteAccountModalVisible: false,
      isCreateAccountModalVisible: false,
      isCreatingAccount: false,
      createdProfileId: '',
      isDuplicateErrorModalVisible: false, // Add for duplicate detection popup
    }
  },
  computed: {
    hasPartsData() {
      if (!this.currentParts) return false;
      return !!(this.currentParts.oil_filter || this.currentParts.oil_filter_2 || this.currentParts.oil_nozzle || this.currentParts.oil_nozzle_2);
    }
  },
  created() {
    this.getCustomer(this.$route.params.id);
  },
  mounted() {
    // Check for success query parameter and show notification
    if (this.$route.query.success === 'true') {
      this.$notify({ title: "Success", text: "Customer edited successfully!", type: "success" });
      // Clean up the URL by removing the query parameter
      this.$router.replace({ name: this.$route.name, params: this.$route.params, query: {} });
    }
  },
  watch: {
    '$route.params.id'(newId) {
      if (newId) {
        this.getCustomer(newId);
      }
    },
  },
  methods: {
    // ALL YOUR METHODS from the original file go here without any changes.
    // getCustomer, userStatus, userAutomatic, etc...
    getPage: function (page: any) {
      if (this.customer && this.customer.id) {
        this.getCustomerDelivery(this.customer.id, page);
      }
    },
    getCustomer(userid: any) {
      if (!userid) return;
      let path = import.meta.env.VITE_BASE_URL + '/customer/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.customer = response.data;

        // --- DEPENDENT API CALLS ---
        this.userStatus();

        // FIX: Pass the correct ID for payment-related calls
        this.getCreditCards(this.customer.id);
        this.getCreditCardsCount(this.customer.id);

        // These other calls are likely correct as they are customer-specific
        this.getCustomerSocial(this.customer.id, 1);
        this.getPage(this.delivery_page);
        this.checktotalOil(this.customer.id);
        this.getCustomerTank(this.customer.id);
        this.userAutomaticStatus(this.customer.id);
        this.getCustomerDescription(this.customer.id);
        this.getCustomerStats(this.customer.id);
        this.getCustomerLastDelivery(this.customer.id);
        this.getServiceCalls(this.customer.id);
        this.fetchCustomerParts(this.customer.id);
        this.loadServicePlan(this.customer.id);
        this.getCustomerTransactions(this.customer.id);
        this.checkAuthorizeAccount();

      }).catch((error: any) => {
        console.error("CRITICAL: Failed to fetch main customer data. Aborting other calls.", error);
      });
    },
    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;
        }
      }).catch(() => { this.user = null });
    },
    userAutomaticStatus(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/customer/automatic/status/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.automatic_status = response.data.status
        if (this.automatic_status === 1) {
          this.getCustomerAutoDelivery(this.customer.id)
        }
        this.checktotalOil(this.customer.id)
      })
    },
    userAutomatic(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/customer/automatic/assign/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.automatic_response = response.data.status
        if (this.automatic_response == 1) {
          this.$notify({ title: "Automatic Status", text: 'Customer is now Automatic Customer', type: 'Success' });
        } else if (this.automatic_response == 2) {
          this.$notify({ title: "Automatic Status", text: 'Customer does not have a main credit card.  Can not make automatic.', type: 'Error' });
        } else if (this.automatic_response == 3) {
          this.$notify({ title: "Automatic Status", text: 'Customer is now a Call in ', type: 'Info' });
        } else {
          this.$notify({ title: "Automatic Status", text: 'Customer is now Manual Customer', type: 'Warning' });
        }
        this.getCustomer(this.$route.params.id);
      })
    },
    getNozzleColor(nozzleString: string): string {
      if (!nozzleString || typeof nozzleString !== 'string') return '';
      const firstChar = nozzleString.trim().toLowerCase().charAt(0);
      switch (firstChar) {
        case 'a': return '#EF4444';
        case 'b': return '#3B82F6';
        case 'w': return '#16a34a';
        default: return 'inherit';
      }
    },
    getCustomerLastDelivery(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/stats/user/lastdelivery/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.customer_last_delivery = response.data.date
      })
    },
    getCustomerStats(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/stats/user/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.customer_stats = response.data
      })
    },
    checktotalOil(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/stats/gallons/check/total/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      })
    },
    getCustomerDescription(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/customer/description/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.customer_description = response.data
      })
    },
    getCustomerTank(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/customer/tank/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.customer_tank = response.data
      })
    },
    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
      })
    },
    getCreditCardsCount(user_id: any) {
      let path = import.meta.env.VITE_BASE_URL + '/payment/cards/onfile/' + user_id;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.credit_cards_count = response.data.cards
      })
    },
    getCustomerAutoDelivery(userid: any) {
      let path = import.meta.env.VITE_AUTO_URL + '/delivery/all/profile/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        // Handle the case where response.data might be null (no auto delivery found)
        this.autodeliveries = response.data || []
        console.log(this.autodeliveries)
      })
    },
    getCustomerDelivery(userid: any, delivery_page: any) {
      let path = import.meta.env.VITE_BASE_URL + '/delivery/customer/' + userid + '/' + delivery_page;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.deliveries = response.data
      })
    },
    editCard(card_id: any) {
      this.$router.push({ name: "cardedit", params: { id: card_id } });
    },
    removeCard(card_id: any) {
      let path = import.meta.env.VITE_BASE_URL + '/payment/card/remove/' + card_id;
      axios({
        method: 'delete',
        url: path,
        headers: authHeader(),
      }).then(() => {
        // --- EFFICIENT FIX: Manipulate the local array directly ---

        // 1. Filter the 'credit_cards' array to remove the card with the matching id.
        this.credit_cards = this.credit_cards.filter(card => card.id !== card_id);

        // 2. Decrement the count.
        this.credit_cards_count--;

        // --- END EFFICIENT FIX ---

        notify({ title: "Card Status", text: "Card Removed", type: "Success" });
      })
        .catch(() => {

          notify({ title: "Error", text: "Could not remove card.", type: "error" });
        });
    },
    deleteCall(delivery_id: any) {
      let path = import.meta.env.VITE_BASE_URL + '/delivery/delete/' + delivery_id;
      axios({
        method: 'delete',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        if (response.data.ok) {
          notify({ title: "Success", text: "deleted delivery", type: "success" });
          this.getPage(1)
        } else {
          notify({ title: "Failure", text: "error deleting delivery", type: "success" });
        }
      })
    },
    deleteCustomerSocial(comment_id: number) {
      let path = import.meta.env.VITE_BASE_URL + '/social/delete/' + comment_id;
      axios({
        method: 'delete',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        console.log(response)
        this.getCustomerSocial(this.customer.id, 1)
      })
    },
    getCustomerSocial(userid: any, delivery_page: any) {
      let path = import.meta.env.VITE_BASE_URL + '/social/posts/' + userid + '/' + delivery_page;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.comments = response.data
      })
    },
    CreateSocialComment(payload: { comment: string; poster_employee_id: number }) {
      let path = import.meta.env.VITE_BASE_URL + "/social/create/" + this.customer.id;
      axios({
        method: "post",
        url: path,
        data: payload,
        withCredentials: true,
        headers: authHeader(),
      })
        .then((response: any) => {
          if (response.data.ok) {
            this.getCustomerSocial(this.customer.id, 1)
          }
          if (response.data.error) {
            this.$router.push("/");
          }
        })
    },
    onSubmitSocial(commentText: string) {
      if (!this.user) {
        console.error("Cannot submit comment: user is not logged in.");
        return;
      }

      let payload = { comment: commentText, poster_employee_id: this.user.user_id };
      this.CreateSocialComment(payload);
    },
    getServiceCalls(customerId: number) {
      let path = `${import.meta.env.VITE_BASE_URL}/service/for-customer/${customerId}`;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
        withCredentials: true,
      }).then((response: any) => {
        this.serviceCalls = response.data;
      }).catch((error: any) => {
        console.error("Failed to get customer service calls:", error);
      });
    },
    getCustomerTransactions(customerId: number) {
      let path = `${import.meta.env.VITE_BASE_URL}/payment/transactions/customer/${customerId}/1`;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.transactions = response.data;
      }).catch((error: any) => {
        console.error("Failed to get customer transactions:", error);
        this.transactions = [];
      });
    },
    openEditModal(service: ServiceCall) {
      this.selectedServiceForEdit = service;
    },
    closeEditModal() {
      this.selectedServiceForEdit = null;
    },
    async handleSaveChanges(updatedService: ServiceCall) {
      try {
        const path = `${import.meta.env.VITE_BASE_URL}/service/update/${updatedService.id}`;
        await axios.put(path, updatedService, { headers: authHeader(), withCredentials: true });
        this.getServiceCalls(this.customer.id);
        this.closeEditModal();
      } catch (error) {
        console.error("Failed to save service call changes:", error);
      }
    },
    async handleDeleteService(serviceId: number) {
      if (!window.confirm("Are you sure you want to delete this service call?")) return;
      try {
        const path = `${import.meta.env.VITE_BASE_URL}/service/delete/${serviceId}`;
        const response = await axios.delete(path, { headers: authHeader(), withCredentials: true });
        if (response.data.ok) {
          this.getServiceCalls(this.customer.id);
          this.closeEditModal();
          notify({ title: "Success", text: "Service call deleted!", type: "success" });
        }
      } catch (error) {
        console.error("Failed to delete service call:", error);
      }
    },
    async fetchCustomerParts(customerId: number) {
      try {
        const path = `${import.meta.env.VITE_BASE_URL}/service/parts/customer/${customerId}`;
        const response = await axios.get(path, { headers: authHeader() });
        this.currentParts = response.data;
      } catch (error) {
        console.error("Failed to fetch customer parts:", error);
      }
    },
    openPartsModal() {
      if (this.currentParts) {
        this.isPartsModalOpen = true;
      } else {
        notify({ title: "Info", text: "Parts data still loading, please wait.", type: "info" });
      }
    },
    closePartsModal() {
      this.isPartsModalOpen = false;
    },
    async handleSaveParts(partsToSave: ServiceParts) {
      try {
        const path = `${import.meta.env.VITE_BASE_URL}/service/parts/update/${partsToSave.customer_id}`;
        const response = await axios.post(path, partsToSave, { headers: authHeader() });

        if (response.data.ok) {
          this.currentParts = partsToSave;
          notify({ title: "Success", text: "Equipment parts saved successfully!", type: "success" });
        }
        this.closePartsModal();
      } catch (error) {
        console.error("Failed to save parts:", error);
        notify({ title: "Error", text: "Failed to save equipment parts.", type: "error" });
      }
    },
    formatDate(dateString: string): string {
      if (!dateString) return 'N/A';
      return dayjs(dateString).format('MMMM D, YYYY');
    },
    formatTime(dateString: string): string {
      if (!dateString) return 'N/A';
      return dayjs(dateString).format('h:mm A');
    },
    getServiceTypeName(typeId: number): string {
      const typeMap: { [key: number]: string } = { 0: 'Tune-up', 1: 'No Heat', 2: 'Fix', 3: 'Tank Install', 4: 'Other' };
      return typeMap[typeId] || 'Unknown Service';
    },
    getServiceTypeColor(typeId: number): string {
      const colorMap: { [key: number]: string } = { 0: 'blue', 1: 'red', 2: 'green', 3: '#B58900', 4: 'black' };
      return colorMap[typeId] || 'gray';
    },
    formatEndDate(startDate: string, years: number): string {
      if (!startDate) return 'N/A';
      return dayjs(startDate).add(years, 'year').format('MMM D, YYYY');
    },
    getPlanStatusText(startDate: string, years: number): string {
      if (!startDate) return 'Unknown';
      const endDate = dayjs(startDate).add(years, 'year');
      const now = dayjs();
      if (now.isAfter(endDate)) {
        return 'Expired';
      } else if (now.isAfter(endDate.subtract(30, 'day'))) {
        return 'Expiring Soon';
      } else {
        return 'Active';
      }
    },
    getPlanStatusBadge(startDate: string, years: number): string {
      if (!startDate) return 'badge-ghost';
      const endDate = dayjs(startDate).add(years, 'year');
      const now = dayjs();
      if (now.isAfter(endDate)) {
        return 'badge-error';
      } else if (now.isAfter(endDate.subtract(30, 'day'))) {
        return 'badge-warning';
      } else {
        return 'badge-success';
      }
    },
    getPlanName(planType: number): string {
      const planNames: { [key: number]: string } = {
        1: 'Standard Plan',
        2: 'Premium Plan'
      };
      return planNames[planType] || 'No Plan';
    },
    getStatusText(startDate: string, years: number): string {
      if (!startDate) return 'Unknown';
      const endDate = dayjs(startDate).add(years, 'year');
      const now = dayjs();
      if (now.isAfter(endDate)) {
        return 'Expired';
      } else if (now.isAfter(endDate.subtract(30, 'day'))) {
        return 'Expiring Soon';
      } else {
        return 'Active';
      }
    },
    getStatusBadge(startDate: string, years: number): string {
      if (!startDate) return 'badge-ghost';
      const endDate = dayjs(startDate).add(years, 'year');
      const now = dayjs();
      if (now.isAfter(endDate)) {
        return 'badge-error';
      } else if (now.isAfter(endDate.subtract(30, 'day'))) {
        return 'badge-warning';
      } else {
        return 'badge-success';
      }
    },
    async loadServicePlan(customerId: number) {
      try {
        const path = `${import.meta.env.VITE_BASE_URL}/service/plans/customer/${customerId}`;
        const response = await axios.get(path, { headers: authHeader() });

        if (response.data && response.data.contract_plan !== undefined) {
          this.servicePlan = response.data;
        }
      } catch (error) {
        // Plan doesn't exist yet, that's okay
        console.log('No existing service plan found');
      }
    },
    async checkAuthorizeAccount() {
      if (!this.customer.id) return;

      this.isLoadingAuthorize = true;

      try {
        const path = `${import.meta.env.VITE_AUTHORIZE_URL}/user/check-authorize-account/${this.customer.id}`;
        const response = await axios.get(path, { headers: authHeader() });
        this.authorizeCheck = response.data;

        // Check if the API returned an error in the response body
        if (this.authorizeCheck.missing_components && this.authorizeCheck.missing_components.includes('api_error')) {
          console.log("API error detected in response, calling cleanup for customer:", this.customer.id);
          this.cleanupAuthorizeData();
          return; // Don't set loading to false yet, let cleanup handle it
        }
      } catch (error) {
        console.error("Failed to check authorize account:", error);
        notify({ title: "Error", text: "Could not check payment account status.", type: "error" });
        // Set default error state
        this.authorizeCheck = {
          profile_exists: false,
          has_payment_methods: false,
          missing_components: ['api_error'],
          valid_for_charging: false
        };
        // Automatically cleanup the local Authorize.Net data on API error
        console.log("Calling cleanupAuthorurizedData for customer:", this.customer.id);
        this.cleanupAuthorizeData();
      } finally {
        this.isLoadingAuthorize = false;
      }
    },
    async createAuthorizeAccount() {
      // Show the creating account modal
      this.isCreatingAccount = true;
      this.isCreateAccountModalVisible = true;

      try {
        const path = `${import.meta.env.VITE_AUTHORIZE_URL}/user/create-account/${this.customer.id}`;
        const response = await axios.post(path, {}, { headers: authHeader() });

        if (response.data.success) {
          // Update local state
          this.customer.auth_net_profile_id = response.data.profile_id;
          this.authorizeCheck.valid_for_charging = true;
          this.authorizeCheck.profile_exists = true;
          this.authorizeCheck.has_payment_methods = true;
          this.authorizeCheck.missing_components = [];
          this.createdProfileId = response.data.profile_id;

          // Refresh credit cards to get updated payment profile IDs
          await this.getCreditCards(this.customer.id);

          // Switch modal to success view and close after delay
          setTimeout(() => {
            this.isCreatingAccount = false;
            setTimeout(() => {
              this.isCreateAccountModalVisible = false;
              this.createdProfileId = '';

              notify({
                title: "Success",
                text: "Authorize.net account created successfully!",
                type: "success"
              });
            }, 3000); // Show success message for 3 seconds
          }, 1000); // Brief delay to show success animation

        } else {
          // Hide modal on error
          this.isCreateAccountModalVisible = false;

          // Check for E00039 duplicate error
          const errorMessage = response.data.message || response.data.error_detail || "Failed to create Authorize.net account";

          if (response.data.is_duplicate || errorMessage.includes("E00039")) {
            // Show duplicate account popup
            setTimeout(() => {
              this.showDuplicateErrorModal();
            }, 300);
            return;
          } else {
            // Normal error notification
            notify({
              title: "Error",
              text: errorMessage,
              type: "error"
            });
          }
        }
      } catch (error: any) {
        console.error("Failed to create account:", error);
        this.isCreateAccountModalVisible = false;
        this.isCreatingAccount = false;

        // Check for E00039 duplicate error
        const errorMessage = error.response?.data?.error_detail ||
          error.response?.data?.detail ||
          error.response?.data?.message ||
          error.message || "Failed to create Authorize.net account";

        if (error.response?.data?.is_duplicate || errorMessage.includes("E00039")) {
          // Show duplicate account popup
          setTimeout(() => {
            this.showDuplicateErrorModal();
          }, 300);
          return;
        }

        // Normal error notification
        notify({
          title: "Error",
          text: errorMessage,
          type: "error"
        });
      }
    },

    // Duplicate Account Error Modal Methods
    showDuplicateErrorModal() {
      this.isDuplicateErrorModalVisible = true;
    },
    hideDuplicateErrorModal() {
      this.isDuplicateErrorModalVisible = false;
    },
    addCreditCard() {
      // Redirect to add card page
      this.$router.push({ name: 'cardadd', params: { id: this.customer.id } });
    },
    showDeleteAccountModal() {
      this.isDeleteAccountModalVisible = true;
    },
    async deleteAccount() {
      this.isDeleteAccountModalVisible = false;

      try {
        const path = `${import.meta.env.VITE_AUTHORIZE_URL}/user/delete-account/${this.customer.id}`;
        const response = await axios.delete(path, { headers: authHeader() });

        if (response.data.success) {
          // Update local state
          this.customer.auth_net_profile_id = null;
          this.authorizeCheck.valid_for_charging = false;
          this.authorizeCheck.profile_exists = false;
          this.authorizeCheck.has_payment_methods = false;

          // Refresh credit cards list (IDs should now be null)
          this.getCreditCards(this.customer.id);

          notify({
            title: "Success",
            text: "Authorize.net account deleted successfully",
            type: "success"
          });
        } else {
          notify({
            title: "Warning",
            text: response.data.message || "Account deletion completed with warnings",
            type: "warning"
          });
        }
      } catch (error: any) {
        console.error("Failed to delete account:", error);
        notify({
          title: "Error",
          text: "Failed to delete Authorize.net account",
          type: "error"
        });
      }
    },
    async cleanupAuthorizeData() {
      try {
        const path = `${import.meta.env.VITE_BASE_URL}/payment/authorize/cleanup/${this.customer.id}`;
        const response = await axios.post(path, {}, { headers: authHeader() });

        if (response.data.ok) {
          // Update local state to reflect cleanup
          this.customer.auth_net_profile_id = null;
          this.authorizeCheck.valid_for_charging = false;
          this.authorizeCheck.profile_exists = false;
          this.authorizeCheck.has_payment_methods = false;

          // Refresh credit cards to reflect null payment profile IDs
          this.getCreditCards(this.customer.id);

          console.log("Successfully cleaned up Authorize.Net data:", response.data.message);
        } else {
          console.error("Failed to cleanup Authorize.Net data:", response.data.error);
        }
      } catch (error) {
        console.error("Error during cleanup:", error);
      }
    },
    getAccountStatusMessage(): string {
      if (!this.authorizeCheck || !this.authorizeCheck.missing_components) {
        return 'Account setup incomplete';
      }

      const missing = this.authorizeCheck.missing_components;
      if (missing.includes('customer_not_found')) {
        return 'Customer not found in Authorize.net';
      } else if (missing.includes('authorize_net_profile')) {
        return 'No Authorize.net profile configured';
      } else if (missing.includes('authorize_net_profile_invalid')) {
        return 'Authorize.net profile is invalid';
      } else if (missing.includes('payment_method')) {
        return 'No payment methods configured';
      } else if (missing.includes('api_error')) {
        return 'Error checking account status';
      } else {
        return 'Account requires setup';
      }
    }
  },
})
</script>
