/**
 * Admin facing js script.
 */
"use strict";
var wkwc_adyen_checkout = jQuery.noConflict();
var wk_adyen = wkwc_adyen_util;
var Prefix = 'wkwc-adyen';

var Util = {
   debugLog: function (msg) {
      console.log('%cDEBUG LOG: ' + msg, "color: orange");
   },
   isJson: function (str) {
      try {
         JSON.parse(str);
      } catch (e) {
         //Error
         //JSON is not okay
         return false;
      }

      return true;
   },
};

var WkwcAdyenCheckout = {

   /**
    * Initiates this module.
   */
   init: function () {

      //stop here if Adyen lib is not loaded
      if (typeof AdyenCheckout == 'undefined') return;

      this.init_popup();
      this.generate_web_component();
      this.regenerate_web_component();
      this.display_payment_action();
   },

   /**
   * Init Adyen checkout.
   *
   * @returns {object}
   */
   AdyenCheckout: async function () {

      return await AdyenCheckout({
         paymentMethodsResponse: wk_adyen.api.response_payment_methods,
         clientKey: wk_adyen.api.origin_key,
         locale: wk_adyen.locale,
         environment: wk_adyen.api.environment,
         onChange: function (state, component) {
            if (state.data.paymentMethod.type == 'scheme') {

               let methodType = 'bcmc' === component.props.type ? 'bcmc' : state.data.paymentMethod.type;

               WkwcAdyenCheckout.setEncryptedCardData(state, component, methodType);

            }else if(wkwc_adyen_checkout.inArray(state.data.paymentMethod.type, ['ideal'] ) != -1){

               WkwcAdyenCheckout.setBankIssuerData(state, component);

            }

         },
         onAdditionalDetails: function (state, component) {

            let elem = wkwc_adyen_checkout(component._node),
               order_id = elem.attr('data-order_id');

            wkwc_adyen_checkout('.' + Prefix + '-component__text').show();

            wkwc_adyen_checkout.ajax({
               url: wk_adyen.ajax.url,
               method: 'POST',
               data: {
                  action: Prefix + '_additional_details',
                  security: wk_adyen.ajax.nonce,
                  state_data: state.data,
                  order_id: order_id
               },
               success: function (res) {
                  if (res.data.redirect) {
                     window.location.href = res.data.redirect;
                  }
               }
            });

         },
         onError: function (err) {
            console.log(err)
         }
      });
   },

   /**
   * Generates the Web Component of the payment method.
   */
   generate_web_component: function () {

      if (wkwc_adyen_checkout('.' + Prefix + '-datepicker').length > 0) {
         wkwc_adyen_checkout('.' + Prefix + '-datepicker').datepicker({
            dateFormat: "dd-mm-yy",
            changeYear: true,
            changeMonth: true,
         })
      }

      this.generateCardForm();
      this.generateGooglePay();
      this.generateNewCardForm();
      this.generateApplePay();
      // this.generateAmazonPay();
      this.generateBankIssuer();
   },

   /**
   * Re-generates the Web Component of the payment method after WC checkout is updated.
   */
   regenerate_web_component: function () {

      wkwc_adyen_checkout(document).on('updated_checkout', this, function (e) {

         e.data.generate_web_component();

      });

   },

   /**
  * Displays the payment action based on the received action data
  * @since 1.3.0
  */
   display_payment_action: function () {

      var elem = '#' + Prefix + '-payment-action-data';

      if (wkwc_adyen_checkout(elem).length > 0) {

         // remove duplicates
         if (wkwc_adyen_checkout('.' + Prefix + '-component[data-payment_action]').length > 1) {

            var lastElem;
            wkwc_adyen_checkout(wkwc_adyen_checkout('.' + Prefix + '-component[data-payment_action]')).each(function () {
               lastElem = wkwc_adyen_checkout(this);
            });

            wkwc_adyen_checkout(wkwc_adyen_checkout('.' + Prefix + '-component[data-payment_action]')).each(function () {
               if (this !== lastElem.get(0)) {
                  wkwc_adyen_checkout(this).remove();
               }
            });
         }

         var action = JSON.parse(wkwc_adyen_checkout(elem).attr('data-payment_action'));

         WkwcAdyenCheckout.AdyenCheckout().then(function (response) {
            response.createFromAction(action).mount(elem);

            if (action.type !== "redirect") {
               jQuery('.' + Prefix + '-component__text').hide();
            }
         });
      }
   },

   /**
   * Clear card data from the hidden fields.
   *
   * @param {string} methodType
   */
   clearCardForm: function (methodType) {

      jQuery('#' + Prefix + '-' + methodType + '-card-number').val('');
      jQuery('#' + Prefix + '-' + methodType + '-card-exp-month').val('');
      jQuery('#' + Prefix + '-' + methodType + '-card-exp-year').val('');
      jQuery('#' + Prefix + '-' + methodType + '-card-cvc').val('');
      jQuery('#' + Prefix + '-' + methodType + '-card-holder').val('');
      jQuery('#' + Prefix + '-' + methodType + '-sci').val('');
      jQuery('#' + Prefix + '-' + methodType + '-store-card').val('');

      Util.debugLog('Clear the encrypted card data.');

   },

   /**
    * Fills the encrypted card data in the hidden fields.
    *
    * @param {object} state
    * @param {object} component
    * @param {string} methodType
   */
   setEncryptedCardData: function (state, component = {}, methodType = '') {

      if (state && state.isValid) {

         var store_card = state.data.storePaymentMethod ? state.data.storePaymentMethod : '0';

         if (component && component._node) {

            jQuery('#' + component._node.id).data('card_state', state);

            Util.debugLog('Saved temporarily the encrypted card data on the element.');

         }

         jQuery('#' + Prefix + '-' + methodType + '-card-number').val(state.data.paymentMethod.encryptedCardNumber);
         jQuery('#' + Prefix + '-' + methodType + '-card-exp-month').val(state.data.paymentMethod.encryptedExpiryMonth);
         jQuery('#' + Prefix + '-' + methodType + '-card-exp-year').val(state.data.paymentMethod.encryptedExpiryYear);
         jQuery('#' + Prefix + '-' + methodType + '-card-cvc').val(state.data.paymentMethod.encryptedSecurityCode);
         jQuery('#' + Prefix + '-' + methodType + '-card-holder').val(state.data.paymentMethod.holderName);
         jQuery('#' + Prefix + '-' + methodType + '-sci').val(state.data.paymentMethod.storedPaymentMethodId);
         jQuery('#' + Prefix + '-' + methodType + '-store-card').val(store_card);

         if (state.data.installments) {
            jQuery('#' + Prefix + '-' + methodType + '-card-installments').val(state.data.installments.value);
         }

         Util.debugLog('Set the encrypted card data.');

      } else {

         this.clearCardForm(methodType);
      }
   },

   /**
    * Generates credit card component.
   */
   generateCardForm: function () {

      jQuery('[data-' + Prefix + '-stored-card]').off('click').on('click', function () {
         var _this = jQuery(this),
            parent = _this.parent(),
            current = parent.find('.' + Prefix + '-stored-card__fields'),
            methodType = _this.attr('data-' + Prefix + '-stored-card-type'),
            formElemId = _this.attr('data-' + Prefix + '-stored-card'),
            card_installments = jQuery('[data-' + Prefix + '-card-installments]').val(),
            formElem = jQuery('#' + formElemId),
            formType = 'scheme' === methodType ? 'card' : methodType,
            cardState = formElem.data('card_state'),
            methodIndex = formElemId.replace(/[^0-9\.]/g, '');

         WkwcAdyenCheckout.AdyenCheckout().then(function (response) {

            let paymentMethodsConfiguration = '';
            let storedMethods = response.paymentMethodsResponse.storedPaymentMethods;

            if (formElem.length > 0) {

               //new card
               if ('' === methodIndex) {

                  if ('' == formElem.children(0).html() && formElem.children(0).children(0).length === 0) {

                     if (Util.isJson(card_installments)) {

                        card_installments = JSON.parse(card_installments);

                        if (card_installments.constructor === Array) {

                           paymentMethodsConfiguration = {
                              card: {
                                 installmentOptions: {
                                    card: {
                                       values: card_installments,
                                       // Shows regular and revolving as plans shoppers can choose.
                                       // plans: [ 'regular', 'revolving' ]
                                    },
                                 },
                                 // Shows payment amount per installment.
                                 showInstallmentAmounts: true
                              }
                           }
                        }
                     }

                     response.setOptions({
                        paymentMethodsConfiguration: paymentMethodsConfiguration,
                     }).create(formType, {
                        locale: wk_adyen.locale,
                        brands: wk_adyen.api.card_types,
                        enableStoreDetails: wk_adyen.api.store_card,
                        hasHolderName: wk_adyen.api.has_holder_name,
                        holderNameRequired: wk_adyen.api.holder_name_required,
                     }).mount('#' + formElemId);

                     Util.debugLog('Initiated the form for using a new card.');

                  } else {

                     WkwcAdyenCheckout.setEncryptedCardData(cardState, {}, methodType);
                  }

                  jQuery('#' + Prefix + '-' + methodType + '-is-stored-card').val('no');

                  //stored card
               } else {

                  if ('' == formElem.html()) {

                     response.create(formType, storedMethods[methodIndex]).mount('#' + formElemId);

                     Util.debugLog('Initiated the form for the existing card.');

                  } else {

                     WkwcAdyenCheckout.setEncryptedCardData(cardState, {}, methodType);
                  }

                  jQuery('#' + Prefix + '-' + methodType + '-is-stored-card').val('yes');
               }
            }

            jQuery('.' + Prefix + '-stored-card__fields').closest('.' + Prefix + '-stored-card').not(parent).removeClass('selected');
            jQuery('.' + Prefix + '-stored-card__fields').not(current).slideUp();

            current.slideToggle();
            parent.addClass('selected');
         });
      });
   },


   /**
    * Generates the new card form if no saved card are present
   */
   generateNewCardForm: function () {

      wkwc_adyen_checkout(document.body).on('updated_checkout', function () {

         jQuery('.wc_payment_method').each(function (index, item) {

            var method = jQuery(item),
               payment_box = method.find('.payment_box');

            //only for visible
            if (payment_box.css('display') == 'block') {

               var has_stored_cards = payment_box.find('.' + Prefix + '-stored-cards > .is-stored-card').length > 0,
                  card = payment_box.find('[data-' + Prefix + '-stored-card]');

               if (has_stored_cards) {
                  return;
               }

               var parent = card.parent(),
                  current = parent.find('.' + Prefix + '-stored-card__fields'),
                  methodType = card.attr('data-' + Prefix + '-stored-card-type'),
                  formElemId = card.attr('data-' + Prefix + '-stored-card'),
                  formElem = jQuery('#' + formElemId),
                  formType = 'scheme' === methodType ? 'card' : methodType,
                  card_installments = jQuery('[data-' + Prefix + '-card-installments]').val(),
                  paymentMethodsConfig = '';

               if (formElem.length > 0) {

                  //new card
                  if (!!formElemId && '' === formElemId.replace(/[^0-9\.]/g, '')) {

                     if ('' == formElem.children(0).html() && formElem.children(0).children(0).length === 0) {

                        if (Util.isJson(card_installments)) {

                           card_installments = JSON.parse(card_installments);

                           if (card_installments.constructor === Array) {

                              paymentMethodsConfig = {
                                 card: {
                                    installmentOptions: {
                                       card: {
                                          values: card_installments,
                                          // Shows regular and revolving as plans shoppers can choose.
                                          // plans: [ 'regular', 'revolving' ]
                                       },
                                    },
                                    // Shows payment amount per installment.
                                    showInstallmentAmounts: true
                                 }
                              }
                           }
                        }

                        WkwcAdyenCheckout.AdyenCheckout().then(function (response) {

                           response.setOptions({
                              paymentMethodsConfiguration: paymentMethodsConfig,
                           }).create(formType, {
                              locale: wk_adyen.locale,
                              brands: wk_adyen.api.card_types,
                              enableStoreDetails: wk_adyen.api.store_card,
                              hasHolderName: wk_adyen.api.has_holder_name,
                              holderNameRequired: wk_adyen.api.holder_name_required,
                           }).mount('#' + formElemId);

                           Util.debugLog('Initiated the form without saved cards.');

                           jQuery('#' + Prefix + '-' + methodType + '-is-stored-card').val('no');

                           jQuery('.' + Prefix + '-stored-card__fields').closest('.' + Prefix + '-stored-card').not(parent).removeClass('selected');
                           jQuery('.' + Prefix + '-stored-card__fields').not(current).slideUp();

                           current.slideDown();
                           parent.addClass('selected');
                        });
                     }
                  }
               }
            }

         });

      });
   },

   /**
    * Generates GooglePay component.
    */
   generateGooglePay: function () {

      if (jQuery('#wkwc_adyen_googlepay_button').length > 0) {

         const test_mode = 'yes' !== jQuery('#wkwc_adyen_googlepay_testmode').val() && 'test' !== wk_adyen.api.environment ? false : true,
            merchant_id = jQuery('#wkwc_adyen_googlepay_merchant_identifier').val();

         WkwcAdyenCheckout.AdyenCheckout().then(function (response) {
            var component = response.create(wk_adyen.google_method_type, {
               countryCode: wk_adyen.cart.country,
               environment: test_mode ? 'TEST' : 'PRODUCTION',
               amount: {
                  currency: wk_adyen.currency,
                  value: (wk_adyen.cart.total) * 100, //it's in cents
               },
               configuration: {
                  gatewayMerchantId: wk_adyen.api.adyen_merchant,
                  merchantName: wk_adyen.site_name,
                  merchantId: merchant_id
               },
               buttonColor: "default",
               onAuthorized: (data) => {
                  jQuery('#wkwc_adyen-googlepay-container .googlepay-description').html(data.paymentMethodData.description).show();
                  jQuery('#wkwc_adyen_googlepay_description').val(data.paymentMethodData.description);
                  jQuery('#wkwc_adyen_googlepay_token').val(data.paymentMethodData.tokenizationData.token);
               }
            });

            component.isAvailable().then(() => {

               component.mount("#wkwc_adyen_googlepay_button");

            }).catch(e => {
               console.log(e);
               jQuery('.wc_payment_method .payment_method_wkwc_adyen_googlepay').remove();
            });

         });
      }
   },

   /**
    * Generates ApplePay component.
    */
   generateApplePay: function(){

      if(jQuery('#wkwc-adyen-applepay-container').length > 0){

         var total =  (wk_adyen.cart.total) * 100; //in cents

         WkwcAdyenCheckout.AdyenCheckout().then(function(response){

            var component = response.create("applepay", {
               amount: {
                  currency: wk_adyen.currency,
                  value: total.toFixed(),
               },
               countryCode: wk_adyen.cart.country,
               onAuthorized: (callBackSuccess, callBackError, ApplePayPaymentAutorizedEvent) => {
                  if( ! ApplePayPaymentAutorizedEvent.payment.token.paymentData){
                     callBackError()
                  }else{

                     var token = JSON.stringify(ApplePayPaymentAutorizedEvent.payment.token.paymentData);

                     jQuery('#wkwc_adyen_applepay_token').val(token);

                     callBackSuccess();

                     document.dispatchEvent( new CustomEvent('WkwcAdyenApplePayPaymentAutorizedEvent', {'detail': {ApplePayPaymentAutorizedEvent : ApplePayPaymentAutorizedEvent} }));
                  }
               },
               onError: function (e) {
                  console.log(e);
               }
            });

            component.isAvailable().then(() => {

               component.mount("#wkwc-adyen-applepay-container");

            }).catch(e => {
               console.log(e);
               jQuery('.payment_method_wkwc_adyen_applepay').find('.payment_box p').text(wk_adyen.translation.no_apple_device);
            });
         });
      }
   },

   generateAmazonPay: function () {

      const adyenButton = document.getElementById('wkwc_adyen_amazonpay_button');

      // Check if Amazon Pay button exists
      if (!adyenButton) {
         console.error("Amazon Pay button element not found.");
         return;
      }

      if (jQuery(adyenButton).length > 0) {
         const test_mode = 'yes' !== jQuery('#wkwc_adyen_amazonpay_testmode').val() && 'test' !== wk_adyen.api.environment ? false : true;
         const merchant_id = 'A2Q9YNJENEV9XH';
         const public_key_id = 'AGF664XON7SE3N5IX23JJU7I';
         const store_id = 'amzn1.application-oa2-client.5b2571313e4043fd9744a0f5b3ea3f9d';

         WkwcAdyenCheckout.AdyenCheckout().then(function (response) {
            const amazonConfig = {
               countryCode: 'EU',
               environment: (test_mode) ? 'test' : 'live',
               ledgerCurrency: 'GBP',
               // customize the buyer experience
               checkoutLanguage: 'en_GB',
               estimatedOrderAmount: {
                  currency: wk_adyen.currency,
                  value: (wk_adyen.cart.total) * 100, //it's in cents
               },
               configuration: {
                  merchantId: merchant_id,
                  publicKeyId: public_key_id,
                  storeId: store_id
               },
               buttonColor: "Gold",
               returnUrl: "undefined" != typeof window ? window.location.href : "",
               chargePermissionType:'OneTime',
               productType: 'PayAndShip',
               currency: wk_adyen.currency,
            };

            var component = response.create('amazonpay', amazonConfig);

            // Check if the component is mountable (replace isAvailable)
            if (component) {
               component.mount("#wkwc_adyen_amazonpay_button");
            } else {
                console.error("Amazon Pay component is not available.");
                jQuery('.wc_payment_method .payment_method_wkwc_adyen_amazonpay').remove();
            }

         });
      }
   },

   /**
    * Generates bank issuer component.
    */
   generateBankIssuer: function(){

      var items = ['ideal'];

      items.map(function(item){

         var elem = '#'+Prefix+'-'+item+'-container';

         if(jQuery(elem).length > 0){

            WkwcAdyenCheckout.AdyenCheckout().then(function (response) {
               response.create(item).mount(elem);
            });

         }
      });
   },

   /**
    * Fills the selected bank issuer in the hidden field.
    */
   setBankIssuerData: function(state, component){

      var value = '';

      if(state && state.isValid){
         value = state.data.paymentMethod.issuer;
      }

      jQuery('#'+Prefix+'_'+state.data.paymentMethod.type+'_issuer').val(value);

   },

   /**
    * Init popup used for payment actions
    */
   init_popup: function () {

      wkwc_adyen_checkout('.' + Prefix + '-popup').each(function () {
         let _this = wkwc_adyen_checkout(this),
            blur = (typeof _this.attr('data-blur') == 'undefined') ? false : true,
            escape = (typeof _this.attr('data-escape') == 'undefined') ? false : true;

         _this.popup({
            autoopen: true,
            blur: blur,
            escape: escape,
            scrolllock: true,
            autozindex: true,
            onopen: function () {
               // Close all other open popups
               wkwc_adyen_checkout('.' + Prefix + '-popup').not(_this).popup('hide');
            }
         });
      });
   },

};

wkwc_adyen_checkout(document).ready(function () {
   WkwcAdyenCheckout.init();

});
