(()=>{"use strict";var t={n:e=>{var i=e&&e.__esModule?()=>e.default:()=>e;return t.d(i,{a:i}),i},d:(e,i)=>{for(var s in i)t.o(i,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:i[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)};const e=window.jQuery;var i=t.n(e);const s=window.wp.apiFetch;var n=t.n(s);const a=window.wp.hooks,r=window.wcPPCP.utils,o=window.lodash,l=class{constructor({id:t,context:e,actions:i,container:s=null}){this.id=t,this.actions=i,this.buttons={},this.buttonActions={},this.context=e,this.settings=(0,r.getSetting)(`${t}_data`),this.container=s||`li.payment_method_${t}`,this.order_field_key=`${this.id}_paypal_order_id`,this.billing_token_key=`${this.id}_billing_token`}initialize(){this.loadPayPalScript().then(()=>{this.initializeEvents(),this.createButton()})}initializeEvents(){}isActive(){return null!==this.getData()}loadPayPalScript(){return new Promise((t,e)=>{(0,r.loadPayPalSdk)(this.getPayPalSDKArgs()).then(e=>{this.paypal=e,t()}).catch(t=>{console.log(t),t?.code&&this.submitError((0,r.getErrorMessage)(t)),e()})})}getPayPalSDKArgs(){return(0,r.getPayPalQueryParams)()}getClientId(){let{clientId:t=null,environment:e}=(0,r.getSetting)("generalData");return t||"sandbox"!=e||(t="sb"),t}getData(){return i()(`${this.container}`).find(".wc-ppcp-payment-method-data").data("payment-method-data")||null}setData(t){i()(`${this.container}`).find(".wc-ppcp-payment-method-data").data("payment-method-data",t)}setOption(t,e){const i=this.getData();i&&(i[t]=e,this.setData(i))}setVariable(t,e){(0,r.getSetting)(`${this.id}_data`)[t]=e}getVariable(t,e=null){const i=(0,r.getSetting)(`${this.id}_data`);return i.hasOwnProperty(t)?i[t]:(e&&this.setVariable(t,e),e)}getOption(t,e=null){const i=this.getData();return i.hasOwnProperty(t)?i[t]:(e&&this.setOption(t,e),e)}createButton(){const t=this.getButtonContainer();t&&!i()(t).find(".paypal-buttons").length&&(this.getSortedFunding(this.getFunding()).forEach(e=>{const i=this.paypal.Buttons(this.getButtonOptions(e));if(this.buttons[e]=i,i.isEligible())if(t instanceof NodeList)for(const e of t)i.render(e);else i.render(t)}),this.$button=i()(t),a.defaultHooks.doAction("wcPPCPButtonCreated",this))}getButton(){return this.$button}destroyButtons(){Object.keys(this.buttons).forEach(t=>{this.buttons[t].close&&this.buttons[t].close()})}disableButtons(){Object.keys(this.buttonActions).forEach(t=>{this.buttonActions[t].disable()})}enableButtons(){Object.keys(this.buttonActions).forEach(t=>{this.buttonActions[t].enable()})}getFunding(){const t=[],e=this.settings?.funding||[];return this.settings?.paypal_sections?.includes(this.getPage())&&t.push(paypal.FUNDING.PAYPAL),e.includes("paylater")&&this.settings?.paylater_sections?.includes(this.getPage())&&this.isCheckoutFlow()&&t.push(paypal.FUNDING.PAYLATER),e.includes("card")&&this.settings?.credit_card_sections?.includes(this.getPage())&&t.push(paypal.FUNDING.CARD),t}isFundingActive(t){return this.settings?.funding?.includes(t)}isSectionEnabled(t,e){const i=`${t}_sections`;return this.settings?.[i]?.includes(e)}getSortedFunding(t){const e=this.settings.buttons_order||[];return t.sort((t,i)=>e.indexOf(t)<e.indexOf(i)?-1:1),t}getButtonContainer(){return null}getButtonOptions(t){const e={fundingSource:t,style:this.getButtonStyle(t),onInit:(...e)=>{this.onInit(t,...e),i()(document.body).triggerHandler("wc_ppcp_on_init",[this,t])},onClick:(...e)=>{this.onClick(...e),i()(document.body).triggerHandler("wc_ppcp_on_click",[this,t])},onApprove:(e,s)=>{this.onApprove(e,s),i()(document.body).triggerHandler("wc_ppcp_on_approve",[this,t])},onCancel:e=>{this.orderId=e.orderID,i()(document.body).triggerHandler("wc_ppcp_on_cancel",[this,t,e])},onError:e=>{this.currentError?(this.submitError(this.currentError),this.currentError=null):this.submitError(e),i()(document.body).triggerHandler("wc_ppcp_on_error",[this,t,e])},onDestroy:()=>{i()(document.body).triggerHandler("wc_ppcp_on_destroy",[this,t])}};return this.isCheckoutFlow()?(e.createOrder=(t,e)=>this.createOrder(t,e),this.needsShipping()&&t!==paypal.FUNDING.VENMO&&(e.onShippingChange=(...t)=>this.onShippingChange(...t))):e.createBillingAgreement=(...t)=>this.createBillingAgreement(...t),e}needsShipping(){return this.getOption("needsShipping",!1)}isCheckoutFlow(){return"true"!==(0,r.getPayPalQueryParams)()?.vault}getTotal(){return this.getOption("total",0)}getButtonStyle(t){let e=null;switch(t){case paypal.FUNDING.PAYPAL:e=this.settings?.buttons?.paypal;break;case paypal.FUNDING.PAYLATER:e=this.settings?.buttons?.paylater;break;case paypal.FUNDING.CARD:e={...this.settings?.buttons?.card},e.tagline?(delete e.tagline,e.layout="vertical"):e.layout="horizontal";break;case paypal.FUNDING.VENMO:const{color:t="",label:i="",...s}=this.settings?.buttons?.paypal;e=s}return e?.height&&(e.height=parseInt(e.height)),e}onApprove(t,e){if((0,r.setFieldValue)(this.order_field_key,t.orderID,""),t.billingToken)return(0,r.setFieldValue)(this.billing_token_key,t.billingToken,""),this.fetchBillingToken(t.billingToken).then(e=>{this.handleBillingToken(e,t)}).catch(t=>this.submitError(t?.message));e.order.get().then(e=>{this.handleOnApproveResponse(t,e)}).catch(t=>this.submitError(t))}handleOnApproveResponse(t,e){this.populateCheckoutFields(e),this.processCartCheckout()}fetchBillingToken(t){return n()({method:"GET",path:`/wc-ppcp/v1/billing-agreement/token/${t}`})}handleBillingToken(t,e){if((0,o.isEmpty)(t.payer_info.billing_address)||this.populateBillingAddressFields((0,r.convertPayPalAddressToCart)(t.payer_info.billing_address)),t?.payer_info?.first_name&&((0,r.isValid)("billing_first_name")||(0,r.setFieldValue)("first_name",t.payer_info.first_name,"billing")),t?.payer_info?.last_name&&((0,r.isValid)("billing_last_name")||(0,r.setFieldValue)("last_name",t.payer_info.last_name,"billing")),t?.payer_info?.email&&((0,r.isValid)("billing_email")||(0,r.setFieldValue)("billing_email",t.payer_info.email)),t?.payer_info?.phone&&((0,r.isValid)("billing_phone")||(0,r.setFieldValue)("billing_phone",t.payer_info.phone)),this.needsShipping()&&t.shipping_address&&!(0,o.isEmpty)(t.shipping_address)){var i;let e=(0,r.convertPayPalAddressToCart)(t.shipping_address);var s;if(this.populateNameFields((0,r.extractFullName)(null!==(i=t.shipping_address.recipient_name)&&void 0!==i?i:""),"shipping"),this.populateShippingAddressFields(e),!(0,r.isValidAddress)(this.getCartFullAddress("billing"),["phone","email"]))(0,r.isValidFieldValue)((0,r.getFieldValue)("billing_first_name"))||(0,r.isValidFieldValue)((0,r.getFieldValue)("billing_last_name"))||this.populateNameFields(null!==(s=t.shipping_address.recipient_name)&&void 0!==s?s:"","billing"),this.populateBillingAddressFields(e)}}createOrder(t,e){return e.order.create(args)}createBillingAgreement(t,e,i=null){return n()({method:"POST",url:(0,r.getRestPath)("/wc-ppcp/v1/billing-agreement/token"),data:{payment_method:this.id,context:this.getPage(),...i}}).then(t=>t).catch(t=>{this.currentError=t})}onShippingChange(t,e,i={}){const s=(0,r.convertPayPalAddressToCart)(t?.shipping_address||{},!0),a=t?.selected_shipping_option?.id||"";return n()({method:"POST",url:(0,r.getRestRoute)("cart/shipping"),data:{order_id:t.orderID,address:s,shipping_method:a,payment_method:this.id,...i}}).then(t=>t.code?e.reject():e.resolve()).catch(t=>e.reject())}submitError(t){}getShippingPrefix(){return"shipping"}getCartAddress(t){return{address_1:(0,r.getFieldValue)("address_1",t),address_2:(0,r.getFieldValue)("address_2",t),state:(0,r.getFieldValue)("state",t),city:(0,r.getFieldValue)("city",t),postcode:(0,r.getFieldValue)("postcode",t),country:(0,r.getFieldValue)("country",t)}}getCartFullAddress(t){return{first_name:(0,r.getFieldValue)("first_name",t),last_name:(0,r.getFieldValue)("last_name",t),address_1:(0,r.getFieldValue)("address_1",t),address_2:(0,r.getFieldValue)("address_2",t),state:(0,r.getFieldValue)("state",t),city:(0,r.getFieldValue)("city",t),postcode:(0,r.getFieldValue)("postcode",t),country:(0,r.getFieldValue)("country",t)}}onInit(t,e,i){this.buttonActions[t]=i}onClick(t,e){}isPage(t){return this.getPage()===t}getPage(){let t=(0,r.getSetting)("generalData")?.page;return"cart"==t&&i()(document.body).is(".woocommerce-checkout")&&(t="checkout"),t}populateShippingAddressFields(t){for(let e in t)(0,r.setFieldValue)(e,t[e],"shipping")}populateBillingAddressFields(t){for(let e in t)(0,r.setFieldValue)(e,t[e],"billing")}populateNameFields(t,e=""){let i,s;Array.isArray(t)?[i,s]=t:({given_name:i,surname:s}=t),(0,r.setFieldValue)("first_name",i,e),(0,r.setFieldValue)("last_name",s,e)}populateCheckoutFields(t){if(!(0,o.isEmpty)(t?.payer?.address)){let e=(0,r.convertPayPalAddressToCart)(t.payer.address);this.populateBillingAddressFields(e)}if(t?.payer?.name&&this.populateNameFields(t.payer.name,"billing"),t?.payer?.email_address&&(0,r.setFieldValue)("billing_email",t.payer.email_address),t?.payer?.phone?.phone_number?.national_number&&((0,r.setFieldValue)("billing_phone",t.payer.phone.phone_number.national_number),(0,r.setFieldValue)("shipping_phone",t.payer.phone.phone_number.national_number)),this.needsShipping()&&t?.purchase_units?.[0]?.shipping){const e=(0,r.convertPayPalAddressToCart)(t.purchase_units[0].shipping.address);if(this.populateShippingAddressFields(e),t.purchase_units[0].shipping?.name?.full_name){const e=(0,r.extractFullName)(t.purchase_units[0].shipping.name.full_name);this.populateNameFields(e,"shipping")}(0,r.isValidAddress)(this.getCartFullAddress("billing"),["phone","email"])||this.populateBillingAddressFields(e)}}processCartCheckout(){return this.showProcessing(),n()({method:"POST",url:(0,r.getRestRoute)("cart/checkout"),data:this.getCartCheckoutData()}).then(t=>{if(t.result&&"success"==t.result)window.location=t.redirect;else if(t.messages)return this.submitError(t.messages)}).catch(t=>{t.code&&this.submitError(t.message)})}getCartCheckoutData(){return{payment_method:this.id,context:this.getPage(),...(0,r.fieldsToJson)()}}getProcessingSelector(){return"body"}showProcessing(){i()(this.getProcessingSelector())?.block({message:this.getProcessingMessage(),overlayCSS:{background:"#fff",opacity:.6}})}hideProcessing(){i()(this.getProcessingSelector())?.unblock()}getProcessingMessage(){return'<div class="wc-ppcp-loader">\n                        <div></div>\n                        <div></div>\n                        <div></div>\n                      </div>'}getFullName(t){const e=[(0,r.getFieldValue)("first_name",t),(0,r.getFieldValue)("last_name",t)].filter(Boolean);return 0==e.length?null:1==e.length?e[0]:`${e[0]} ${e[1]}`}},d=window.wcPPCP.product;var h=t.n(d);const u=window.wcPPCP.cart;var p=t.n(u);const c=window.wcPPCP.actions;var g=t.n(c);new class extends l{_excludedKeys=["add-to-cart","quantity","variation_id"];constructor(t,e,i){super(i),this.settings={...this.settings,...(0,r.getSetting)("productSettings")},this.product=t,this.cart=e,this.initialize()}initialize(){this.actions.addAction("found_variation",this.onFoundVariation.bind(this)),this.actions.addAction("reset_variation",this.onResetVariation.bind(this)),this.setMaxWidth(),super.initialize()}onInit(...t){super.onInit(...t),this.actions.doAction("product_button_on_init"),this.product.isVariableProduct()&&(this.product.isVariationSelected()&&this.product?.variation?.is_in_stock?this.enableButtons():this.disableButtons())}setOptions(t){for(let e in t)this.setOption(e,t[e])}needsShipping(){return this.product.needsShipping()}getButtonContainer(){const t=document.querySelectorAll(".wc-ppcp-product-button-container");return t&&t.length>0?t:document.getElementById("wc-ppcp-product-button-container")}setMaxWidth(){if("add_to_cart"==this.settings?.product?.button_width){this.buttonWidth=i()("form.cart div.quantity").outerWidth(!0)+i()(".single_add_to_cart_button").outerWidth();var t=i()(".single_add_to_cart_button").css("marginLeft");t&&(this.buttonWidth+=parseInt(t.replace("px",""))),i()(this.container).css("max-width",this.buttonWidth+"px")}}submitError(t){this.hideProcessing(),(0,r.submitErrorMessage)(t,"div.woocommerce-notices-wrapper")}getFunding(){const t=[],e=this.settings?.funding||[];return e.includes("paypal")&&t.push(paypal.FUNDING.PAYPAL),e.includes("paylater")&&t.push(paypal.FUNDING.PAYLATER),e.includes("card")&&t.push(paypal.FUNDING.CARD),this.getSortedFunding(t)}addToCart(){return this.cart.addToCart({payment_method:this.id,product_id:this.product.getId(),variation_id:this.product.getVariationId(),qty:this.product.getQuantity(),variation:this.product.getVariationData(),...(0,r.convertFormToJson)(i()("form.cart"),this._excludedKeys)}).then(t=>{if(!t.code)return t.order_id;this.currentError=t}).catch(t=>(this.currentError=t,this.submitError(t)))}createOrder(t,e){return this.addToCart()}createBillingAgreement(t,e){return this.addToCart().then(()=>super.createBillingAgreement(t,e))}handleBillingToken(t){super.handleBillingToken(t),this.processCartCheckout()}onFoundVariation(t,e){t?(this.destroyButtons(),this.createButton()):e.variation.is_in_stock?this.enableButtons():this.disableButtons()}onResetVariation(){this.disableButtons()}enableButtons(){this?.$button?.removeClass("disabled"),super.enableButtons()}disableButtons(){this?.$button?.addClass("disabled"),super.disableButtons()}}(h(),p(),{id:"ppcp",actions:new(g()),context:"product"}),(this.wcPPCP=this.wcPPCP||{}).paypalProduct={}})();