async function maybeApplepayShowButton(){if(""===yith_ppwc_apple_pay.context)return;if(!window.ApplePaySession)throw new Error("This device does not support Apple Pay");if(!ApplePaySession.canMakePayments())throw new Error("This device, although an Apple device, is not capable of making Apple Pay payments");let e=document.getElementById("applepay-container");if(""===yith_ppwc_apple_pay.context||!e)return;const t=await paypal.Applepay().config(),{isEligible:o}=t;if(!o)throw new Error("applepay is not eligible");new ApplePayButton(t).init()}window.addEventListener("load",(()=>{(async()=>{maybeApplepayShowButton()})()}));class ApplePayButton{constructor(e){this.config=e,this.context=yith_ppwc_apple_pay.context,this.ajaxUrl=yith_ppwc_frontend.ajaxUrl,this.environment=yith_ppwc_apple_pay.environment,this.buttonColor=yith_ppwc_apple_pay.buttonColor,this.buttonType=yith_ppwc_apple_pay.buttonType,this.buttonLocale=yith_ppwc_apple_pay.buttonLocale,this.form="",this.fundingSource=yith_ppwc_apple_pay.fundingSource,this.formRequestType="",this.current_ap_session,this.transactionInfos,this.requireShipping="1"==yith_ppwc_apple_pay.needShipping,this.productInfo=null==yith_ppwc_apple_pay.product?"":yith_ppwc_apple_pay.product}initEvents(){jQuery(document.body).on("updated_cart_totals updated_checkout update_shipping_method",(function(){maybeApplepayShowButton()})),jQuery("form.variations_form").on("show_variation",(function(e,t,o){let a=jQuery(".yith-ppwc-button-container").find("#applepay-container");o?a.show():a.hide()})),jQuery("form.variations_form").on("hide_variation",(function(e,t,o){jQuery(".yith-ppwc-button-container").find("#applepay-container").hide()}))}init(){this.getTransactionInfos().then((e=>{this.transactionInfos=e,this.logger("TransactionInfos:",this.transactionInfos),this.renderButton()})),this.initEvents()}renderButton(){const e="browser"===this.buttonLocale?"":this.buttonLocale,t='<apple-pay-button id="applepay_button" buttonstyle="'+this.buttonColor+'" type="'+this.buttonType+'" locale="'+e+'">';document.getElementById("applepay-container").innerHTML=t,document.getElementById("applepay_button").addEventListener("click",(()=>{this.buttonClickHandler()}))}getPaymentRequest(){let e={merchantCapabilities:this.config.merchantCapabilities,supportedNetworks:this.config.supportedNetworks,requiredShippingContactFields:["postalAddress","email","phone"],requiredBillingContactFields:["postalAddress"]};return this.requireShipping||(e.requiredShippingContactFields=["email","phone"]),Object.assign(this.transactionInfos,e)}setApplePaySession(e){this.logger("starting new session for request:",e),this.current_ap_session=new ApplePaySession(4,e),this.requireShipping&&(this.current_ap_session.onshippingmethodselected=this.onShippingMethodSelected(this.current_ap_session)),this.current_ap_session.onshippingcontactselected=this.onShippingContactSelected(this.current_ap_session),this.current_ap_session.onvalidatemerchant=this.onValidateMerchant(this.current_ap_session),this.current_ap_session.onpaymentauthorized=this.onPaymentAuthorized(this.current_ap_session),this.current_ap_session.oncancel=this.onUIDismissed.bind(this),this.current_ap_session.begin(),this.logger("current apple pay session:",this.current_ap_session)}async onUIDismissed(){var e=[];this.logger("maybe clean session"),e.push({name:"request",value:"maybe_clean_session"}),this.blockFormRequest();await fetch(yith_ppwc_frontend.ajaxUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},credentials:"same-origin",body:this.formatRequestBody(e,"applepay")});this.unblockFormRequest()}async buttonClickHandler(e){this.logger("buttonClickHandler");const t=this.getPaymentRequest();this.logger("buttonClickHandler-paymentRequest",t),this.setApplePaySession(t)}onShippingMethodSelected(e){return t=>{this.logger("onShippingMethodSelected call",t);const o=this.getShippingMethodData(t);jQuery.ajax({url:this.ajaxUrl,method:"POST",data:o,success:(o,a,r)=>{let n=o.data;this.logger("ajax response",o),"failure"===o.result?(console.warn(o.error),e.abort()):(this.logger("Shipping Methods",n.newShippingMethods),n.newShippingMethods=n.newShippingMethods.sort(((e,o)=>e.label===t.shippingMethod.label?-1:1)),e.completeShippingMethodSelection(n))},error:(t,o,a)=>{this.log("onshippingmethodselected error",o),console.warn(o,a),e.abort()}})}}getShippingMethodData(e){return{request:"update_shipping_method_applepay",shipping_method:e.shippingMethod,simplified_contact:e.shippingContact,security:yith_ppwc_apple_pay.ajaxNonce}}onShippingContactSelected(e){return t=>{this.logger("onShippingContactSelected call");const o=this.getShippingContactData(t);this.logger("ShippingContactData ajax request",o),this.validate_cart().then((t=>{if(!1===t.validate)return this.logger("cart not validated"),void e.abort();jQuery.ajax({url:this.ajaxUrl,method:"POST",data:o,success:(t,o,a)=>{this.logger("ShippingContactUpdate",t);let r=t.data;if(!1===t.success)return console.error(t.data),void e.abort();e.completeShippingContactSelection(r)},error:(t,o,a)=>{this.logger("onshippingcontactselected error",o),console.warn(o,a),e.abort()}})}))}}getShippingContactData(e){return{request:"update_shipping_contact_applepay",simplified_contact:e.shippingContact,need_shipping:this.requireShipping,security:yith_ppwc_apple_pay.ajaxNonce}}validate_cart(){return new Promise((async(e,t)=>{try{var o=[];if("product"===this.context){if(!this.form)return e({validate:!1});{(o=this.form.serializeArray()).push({name:"request",value:"validate_product_cart"}),o.push({name:"is-yith-ppwc-action",value:"yes"});let e=this.form.find('button[name="add-to-cart"]');e.length&&o.push({name:"add-to-cart",value:e.val()})}}else o.push({name:"request",value:"validate_product_cart"});this.logger("validate_cart for "+this.context,o),this.blockFormRequest();const t=await fetch(this.ajaxUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},credentials:"same-origin",body:this.formatRequestBody(o,this.context)}),a=await t.json();return a&&"failure"===a.result?(this.handleRequestError(a,"cart"),e({validate:!1})):(this.unblockFormRequest(),e({validate:!0}))}catch(e){console.log("validate_cart error",e),t()}}))}onValidateMerchant(e){return this.logger("Validating Merchant"),t=>{paypal.Applepay().validateMerchant({validationUrl:t.validationURL}).then((t=>{this.logger("Merchant validated",t.merchantSession),e.completeMerchantValidation(t.merchantSession),jQuery.ajax({url:this.ajaxUrl,type:"POST",data:{request:"validate_merchant",validation:!0,security:yith_ppwc_frontend.ajaxNonce}})})).catch((t=>{console.error("yith_ppwc_apple_pay_blocks validate error",t),jQuery.ajax({url:this.ajaxUrl,type:"POST",data:{request:"validate_merchant",validation:!1,security:yith_ppwc_frontend.ajaxNonce}}),e.abort()}))}}onPaymentAuthorized(e){return this.logger("onPaymentAuthorized"),async t=>{if(this.logger("onPaymentAuthorized call"),!this.needShipping&&"product"===this.context){if(!1===(await this.validate_cart()).validate)return this.logger("cart not validated"),void e.abort()}let o=await this.createOrder(this,t.payment);if("failure"==o?.result)return console.error(o.error),e.completePayment(e.STATUS_FAILURE),void e.abort();let a=o.id;this.logger("onpaymentauthorized order created",a,t.payment.token,t.payment.billingContact);try{const o=await paypal.Applepay().confirmOrder({orderId:a,token:t.payment.token,billingContact:t.payment.billingContact});if(this.logger("confirmOrderResponse",o),o&&o.approveApplePayPayment)if("APPROVED"===o.approveApplePayPayment.status)try{this.blockFormRequest();let t=!1;const o=await this.approveOrder(this,{orderID:a});this.logger("approveOrder response",o),o.redirect&&(t=!0),t?(this.logger("onpaymentauthorized approveOrder OK"),e.completePayment(e.STATUS_SUCCESS),window.location.href=o.redirect):(this.logger("onpaymentauthorized approveOrder FAIL"),e.completePayment(e.STATUS_FAILURE),o.result&&"failure"===o.result&&o.message&&console.error("onpaymentauthorized",o.message),e.abort())}catch(t){e.completePayment(e.STATUS_FAILURE),e.abort(),console.log(t)}else console.error("Order Confirmation Error: status is not APPROVED"),e.completePayment(e.STATUS_FAILURE),e.abort();else console.error("Invalid confirmOrderResponse"),e.completePayment(e.STATUS_FAILURE),e.abort()}catch(t){e.completePayment(e.STATUS_FAILURE),e.abort()}this.unblockFormRequest()}}async approveOrder(e,t,o){if(this.logger("approving order"),t&&t.orderID){return(await fetch(this.ajaxUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:this.formatRequestBody([{name:"request",value:"approve_order"},{name:"orderID",value:t.orderID},{name:"checkoutRequest",value:this.context},{name:"fundingSource",value:e.fundingSource}],"applepay")})).json()}}getTransactionInfos(){return this.logger("getTransactionInfos"),new Promise((async(e,t)=>{try{var o=[];if("product"===this.context){let e=document.getElementById("applepay-container");this.form=jQuery(e).closest(".product.type-product").find("form.cart");let t=this.form.find(".qty").val();this.form.length&&(o.push({name:"request",value:"product_cart_info"}),o.push({name:"product_id",value:this.productInfo?.product_id}),o.push({name:"product_qty",value:t}))}else o.push({name:"request",value:"cart_info"});await fetch(this.ajaxUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},credentials:"same-origin",body:this.formatRequestBody(o,this.context)}).then((e=>e.json())).then((t=>t.success?e({countryCode:t.data.countryCode,currencyCode:t.data.currencyCode,total:{label:t.data.total.label,type:t.data.total.type,amount:t.data.total.amount}}):(this.logger("getTransactionInfos error",t.data),e(!1))))}catch(e){console.error("getTransactionInfos error",e),t(e)}}))}async createOrder(e,t,o){return fetch(this.ajaxUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:this.formatRequestBody([{name:"request",value:"create_order"},{name:"checkoutRequest",value:this.context},{name:"orderID",value:yith_ppwc_apple_pay.orderId},{name:"fundingSource",value:e.fundingSource},{name:"billingData",value:JSON.stringify(t.billingContact)},{name:"shippingData",value:JSON.stringify(t.shippingContact)}],"applepay")}).then((function(e){return e.json()})).then((function(e){return e}))}formatRequestBody(e,t){var o=[];return e.push({name:"security",value:yith_ppwc_frontend.ajaxNonce}),""!==t&&e.push({name:"flow",value:t}),e.push({name:"funding",value:this.fundingSource}),jQuery.each(e,(function(e,t){o.push(t.name+"="+t.value)})),o.join("&")}handleRequestError(e,t){if(e&&e.reload)window.location.reload();else if(e&&e.redirect)window.location.href=e.redirect;else{var o=e&&e.messages.length?e.messages:yith_ppwc_frontend.errorMessage;"checkout"===t?(jQuery(".woocommerce-NoticeGroup-checkout, .woocommerce-error, .woocommerce-message").remove(),jQuery("form.checkout").prepend('<div class="woocommerce-NoticeGroup woocommerce-NoticeGroup-checkout">'+o+"</div>"),jQuery(document.body).trigger("checkout_error",[o]),this.form.find(".input-text, select, input:checkbox").trigger("validate").blur()):jQuery(".woocommerce-notices-wrapper").first().html(o),void 0!==jQuery.scroll_to_notices&&jQuery.scroll_to_notices("checkout"===t?jQuery(".woocommerce-NoticeGroup-checkout"):jQuery(".woocommerce-notices-wrapper").first()),this.unblockFormRequest()}return!1}blockFormRequest(){let e=[];switch(this.context){case"cart":e.push(jQuery(".woocommerce-cart .cart_totals")),e.push(jQuery(".woocommerce-cart .woocommerce-cart-form"));break;case"checkout":e.push(jQuery("form.woocommerce-checkout"));break;case"product":e.push(jQuery("form.cart"))}e.push(jQuery(".yith-ppwc-button-container")),e.forEach((e=>{e.addClass("processing").block({message:null,overlayCSS:{background:"#fff",opacity:.6}})}))}unblockFormRequest(){let e=[];switch(this.context){case"cart":e.push(jQuery(".woocommerce-cart .cart_totals")),e.push(jQuery(".woocommerce-cart .woocommerce-cart-form"));break;case"checkout":e.push(jQuery("form.woocommerce-checkout"));break;case"product":e.push(jQuery("form.cart"))}e.push(jQuery(".yith-ppwc-button-container")),e.forEach((e=>{e.removeClass("processing").unblock()}))}logger(...e){"sandbox"===this.environment&&console.log("yith_ppwc_apple_pay",e)}}