<!-- src/pages/card/addcard.vue -->
<template>
  <div class="flex">
    <div class="w-full px-4 md-px-10 py-4">
      <!-- Breadcrumbs -->
      <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.id"><router-link :to="{ name: 'customerProfile', params: { id: customer.id } }">Profile</router-link></li>
          <li>Add Credit Card</li>
        </ul>
      </div>

      <!-- TOP SECTION: Customer Info -->
      <div class="my-6">
        <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>
              <span v-else>Unknown type</span>)
            </div>
          </div>
        </div>
      </div>

      <!-- BOTTOM SECTION: Add Card Form -->
      <div class="bg-neutral rounded-lg p-6">
        <h2 class="text-2xl font-bold mb-4">Add a New Credit Card</h2>
        <form @submit.prevent="onSubmit" class="space-y-4">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <!-- Name -->
            <div class="form-control">
              <label class="label"><span class="label-text font-bold">Name on Card</span></label>
              <input v-model="CardForm.name_on_card" type="text" placeholder="Name" class="input input-bordered input-sm w-full" />
              <span v-if="v$.CardForm.name_on_card.$error" class="text-red-500 text-xs mt-1">A valid name_on_card is required.</span>
            </div>

            <!-- Card Number -->
            <div class="form-control">
              <label class="label"><span class="label-text font-bold">Card Number</span></label>
              <input v-model="CardForm.card_number" type="text" placeholder="•••• •••• •••• ••••" class="input input-bordered input-sm w-full" />
              <span v-if="v$.CardForm.card_number.$error" class="text-red-500 text-xs mt-1">A valid card number is required.</span>
            </div>

            <!-- CVV (Security Code) -->
            <div class="form-control">
              <label class="label"><span class="label-text font-bold">CVV</span></label>
              <input v-model="CardForm.cvv" type="text" placeholder="123" class="input input-bordered input-sm w-full" />
              <span v-if="v$.CardForm.cvv.$error" class="text-red-500 text-xs mt-1">CVV is required.</span>
            </div>

            <!-- Expiration -->
            <div class="form-control">
              <label class="label"><span class="label-text font-bold">Expiration Date</span></label>
              <div class="flex gap-2">
                <select v-model="CardForm.expiration_month" class="select select-bordered select-sm w-full">
                  <option disabled value="">Month</option>
                  <option v-for="m in 12" :key="m" :value="String(m).padStart(2, '0')">{{ String(m).padStart(2, '0') }}</option>
                </select>
                <select v-model="CardForm.expiration_year" class="select select-bordered select-sm w-full">
                  <option disabled value="">Year</option>
                  <option v-for="y in 10" :key="y" :value="new Date().getFullYear() + y - 1">{{ new Date().getFullYear() + y - 1 }}</option>
                </select>
              </div>
              <span v-if="v$.CardForm.expiration_month.$error || v$.CardForm.expiration_year.$error" class="text-red-500 text-xs mt-1">Both month and year are required.</span>
            </div>
            
            <!-- Card Type dropdown -->
            <div class="form-control">
              <label class="label"><span class="label-text font-bold">Card Type</span></label>
              <select v-model="CardForm.type_of_card" class="select select-bordered select-sm w-full">
                <option disabled value="">Select Type</option>
                <option>Visa</option>
                <option>MasterCard</option>
                <option>Discover</option>
                <option>American Express</option>
              </select>
              <span v-if="v$.CardForm.type_of_card.$error" class="text-red-500 text-xs mt-1">Required.</span>
            </div>

            <!-- Billing Zip Code input -->
            <div class="form-control">
              <label class="label"><span class="label-text font-bold">Billing Zip Code</span></label>
              <input v-model="CardForm.zip_code" type="text" placeholder="12345" class="input input-bordered input-sm w-full" />
              <span v-if="v$.CardForm.zip_code.$error" class="text-red-500 text-xs mt-1">Required.</span>
            </div>

            <!-- --- FIX: Main Card Checkbox --- -->
            <div class="form-control md:col-span-2">
              <label class="label cursor-pointer justify-start gap-4">
                <span class="label-text font-bold">Set as Main Card for this customer</span>
                <!-- `v-model` binds the checkbox's checked state to the boolean `CardForm.main_card` -->
                <input v-model="CardForm.main_card" type="checkbox" class="checkbox checkbox-sm" />
              </label>
            </div>

          </div>
          
          <!-- SUBMIT BUTTON -->
          <div class="pt-4">
            <button type="submit" class="btn btn-primary btn-sm" :disabled="isLoading">
              <span v-if="isLoading" class="loading loading-spinner loading-xs"></span>
              {{ isLoading ? 'Saving...' : 'Save Credit Card' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
  
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import axios from 'axios'
import authHeader from '../../services/auth.header'
import useValidate from "@vuelidate/core";
import { notify } from "@kyvg/vue3-notification"
import { minLength, required } from "@vuelidate/validators";

export default defineComponent({
  name: 'AddCardCreate',
  components: {
  },
  data() {
    return {
      v$: useValidate(),
      user: null,
      customer: {} as any,
      isLoading: false,
      isLoadingAuthorize: true,
      authorizeCheck: { profile_exists: false, has_payment_methods: false, missing_components: [] as string[], valid_for_charging: false },
      CardForm: {
        main_card: false,
        card_number: '',
        expiration_month: '',
        expiration_year: '',
        cvv: '',
        type_of_card: '',
        zip_code: '',
        name_on_card: '',
      },
    }
  },
  validations() {
    return {
      CardForm: {
        card_number: { required, minLength: minLength(13) },
        expiration_month: { required },
        expiration_year: { required },
        cvv: { required, minLength: minLength(3) },
        type_of_card: { required },
        zip_code: { required, minLength: minLength(5) },
        name_on_card: { required },
      },
    };
  },
  created() {
    this.userStatus();
    this.getCustomer(this.$route.params.id);
  },
  methods: {
    userStatus() {
      const path = import.meta.env.VITE_BASE_URL + '/auth/whoami';
      axios.get(path, { withCredentials: true, headers: authHeader() })
        .then((response: any) => {
          if (response.data.ok) { this.user = response.data.user; }
        })
        .catch(() => { this.user = null; });
    },
    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;
      } 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
        };
      } finally {
        this.isLoadingAuthorize = false;
      }
    },
    getCustomer(user_id: any) {
      const path = `${import.meta.env.VITE_BASE_URL}/customer/${user_id}`;
      axios.get(path, { withCredentials: true, headers: authHeader() })
        .then((response: any) => {
          this.customer = response.data;
          this.checkAuthorizeAccount();
        })
        .catch(() => {
          notify({ title: "Error", text: "Could not find customer", type: "error" });
        });
    },
    async onSubmit() {
      this.v$.$validate();
      if (this.v$.$error) {
        notify({ title: "Validation Error", text: "Please fill out all required fields.", type: "error" });
        return;
      }

      this.isLoading = true;

      // --- STEP 1: PREPARE PAYLOADS FOR BOTH SERVICES ---
      // Payload for your Flask backend (it takes all the raw details for your DB)
      const flaskPayload = {
        card_number: this.CardForm.card_number,
        expiration_month: this.CardForm.expiration_month,
        expiration_year: this.CardForm.expiration_year,
        type_of_card: this.CardForm.type_of_card,
        security_number: this.CardForm.cvv, // Your Flask app expects 'security_number'
        main_card: this.CardForm.main_card,
        zip_code: this.CardForm.zip_code,
        name_on_card: this.CardForm.name_on_card, // Your Flask app expects 'name_on_card'
      };

      // Payload for your FastAPI backend (it only needs the essentials for Authorize.Net)
      const fastapiPayload = {
        card_number: this.CardForm.card_number.replace(/\s/g, ''),
        expiration_date: `${this.CardForm.expiration_year}-${this.CardForm.expiration_month}`,
        cvv: this.CardForm.cvv,
        main_card: this.CardForm.main_card, // Send this to FastAPI as well
      };

      // --- STEP 2: CRITICAL CALL - SAVE CARD TO LOCAL DATABASE VIA FLASK ---
      let card_id: number;
      try {
        const flaskPath = `${import.meta.env.VITE_BASE_URL}/payment/card/create/${this.customer.id}`;
        console.log("Attempting to save card to local DB via Flask:", flaskPath);
        const flaskResponse = await axios.post(flaskPath, flaskPayload, { withCredentials: true, headers: authHeader() });

        if (!flaskResponse.data.ok) {
          // If the primary save fails, stop everything and show an error.
          throw new Error(flaskResponse.data.error || "Failed to save card.");
        }
        card_id = flaskResponse.data.card_id;
        console.log("Card successfully saved to local database via Flask with ID:", card_id);

      } catch (error: any) {
        const errorMessage = error.response?.data?.error || "A critical error occurred while saving the card.";
        notify({ title: "Error", text: errorMessage, type: "error" });
        this.isLoading = false; // Stop loading spinner
        return; // End the function here
      }

      // --- CHECK IF AUTHORIZE.NET PROFILE EXISTS ---
      if (!this.authorizeCheck.profile_exists) {
        console.log("Skipping Authorize.Net tokenization as no profile exists for customer.");
        // Show success and redirect (card saved locally without tokenization)
        notify({ title: "Success", text: "Credit card has been saved.", type: "success" });
        this.isLoading = false;
        this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
        return;
      }

      // --- STEP 3: BEST-EFFORT CALL - TOKENIZE CARD VIA AUTHORIZE
      try {
        const fastapiPath = `${import.meta.env.VITE_AUTHORIZE_URL}/api/payments/customers/${this.customer.id}/cards`;
        console.log("Attempting to tokenize card with Authorize.Net via FastAPI:", fastapiPath);
        const fastapiResponse = await axios.post(fastapiPath, fastapiPayload, { withCredentials: true, headers: authHeader() });
        console.log("Card successfully tokenized with Authorize.Net via FastAPI.");

        // --- STEP 4: UPDATE LOCAL CARD WITH PAYMENT_PROFILE_ID ---
        const payment_profile_id = fastapiResponse.data.payment_profile_id;
        console.log("Updating local card with payment_profile_id:", payment_profile_id);
        const updatePath = `${import.meta.env.VITE_BASE_URL}/payment/card/update_payment_profile/${card_id}`;
        await axios.put(updatePath, { auth_net_payment_profile_id: payment_profile_id }, { withCredentials: true, headers: authHeader() });
        console.log("Card successfully updated with payment_profile_id.");

      } catch (error: any) {
        // If this fails, we just log it for the developers. We DON'T show an error to the user.
        console.warn("NON-CRITICAL-ERROR: Tokenization with Authorize.Net failed, but the card was saved locally.", error.response?.data || error.message);
        // Card is saved but without payment_profile_id, which is ok as nullable.
      }
      
      // --- STEP 4: ALWAYS SHOW SUCCESS AND REDIRECT ---
      // This code runs as long as the first (Flask) call was successful.
      notify({ title: "Success", text: "Credit card has been saved.", type: "success" });
      this.isLoading = false;
      this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
    },
  },
});
</script>
