Plugin Directory

Changeset 3431463


Ignore:
Timestamp:
01/03/2026 06:28:06 AM (7 weeks ago)
Author:
squarewoosync
Message:

Cash App

Location:
squarewoosync/trunk
Files:
18 edited

Legend:

Unmodified
Added
Removed
  • squarewoosync/trunk/assets/js/checkout-handler.js

    r3163614 r3431463  
    11// checkout-handler.js
    2 function handleError(errors) {
    3     errors.forEach(function (error) {
    4         console.error('Error:', error.code, error.message);
    5         alert('Payment failed: ' + error.message);
    6     });
     2function handleError( errors ) {
     3    errors.forEach( function ( error ) {
     4        console.error( 'Error:', error.code, error.message );
     5        alert( 'Payment failed: ' + error.message );
     6    } );
    77}
  • squarewoosync/trunk/assets/js/square-gateway.js

    r3310892 r3431463  
    1 (function ($) {
    2   let payments = null;
    3   let walletPaymentRequest = null;
    4   let paymentInProgress = false;
    5 
    6   let alreadyInitialized = false; // Guard for initial load
    7 
    8   // Debounce timer
    9   let squareInitTimeout = null;
    10   const DEBOUNCE_DELAY = 20;
    11 
    12   // We remove lastKnownTotal logic & the booleans, allowing each partial refresh to re-init
    13 
    14   /**
    15    * Debounces the Square init calls so multiple near-simultaneous triggers
    16    * only cause a single actual initialization attempt.
    17    */
    18   function scheduleSquareInit() {
    19     if (squareInitTimeout) {
    20       clearTimeout(squareInitTimeout);
    21     }
    22     squareInitTimeout = setTimeout(handleSquareInit, DEBOUNCE_DELAY);
    23   }
    24 
    25   /**
    26    * Main initialization if squaresync_credit is chosen.
    27    * Called after the debounce timer.
    28    */
    29   async function handleSquareInit() {
    30     const selectedMethod = $('#payment input[name="payment_method"]:checked').val();
    31     if (selectedMethod !== 'squaresync_credit') {
    32       return;
    33     }
    34 
    35 
    36     clearStoredTokens();
    37 
    38     if (typeof Square === 'undefined') {
    39       console.error('Square Web Payments SDK not loaded');
    40       console.log('return 2')
    41       return;
    42     }
    43 
    44 
    45     try {
    46       // Create 'payments' once if not done yet
    47       if (!payments) {
    48         const applicationId = SquareConfig.applicationId;
    49         const locationId = SquareConfig.locationId;
    50         payments = await Square.payments(applicationId, locationId);
    51         console.log(payments)
    52         if (!payments) {
    53           throw new Error('Square payments init failed');
    54         }
    55       }
    56 
    57       const needsShipping = await checkNeedsShipping();
    58       const couponApplied = false;
    59       // Build or refresh the PaymentRequest object
    60       walletPaymentRequest = await initPaymentRequest(payments, needsShipping, couponApplied);
    61 
    62       // Show/hide card fields
    63       toggleCardFields();
    64 
    65       // Force-clean the container and re-mount the card
    66       forceCleanCardContainer();
    67       initCreditCardPayment(payments, walletPaymentRequest);
    68 
    69       // Also forcibly remove leftover wallet buttons, then re-init
    70       if (walletPaymentRequest) {
    71         forceCleanWalletButtons();
    72         initWalletPayments(payments, walletPaymentRequest, needsShipping, couponApplied);
    73       }
    74 
    75       alreadyInitialized = true;
    76 
    77     } catch (err) {
    78       console.error('Square init error:', err);
    79     }
    80   }
    81 
    82   /**
    83    * Remove any leftover .sq-card-wrapper from partial refresh
    84    */
    85   function forceCleanCardContainer() {
    86     const $container = $('#payment #card-container');
    87     if ($container.length) {
    88       $container.find('.sq-card-wrapper').remove();
    89     }
    90   }
    91 
    92   /**
    93    * Remove leftover wallet button elements
    94    */
    95   function forceCleanWalletButtons() {
    96     jQuery("#apple-pay-button").empty();
    97     jQuery("#google-pay-button").empty();
    98     jQuery("#afterpay-button").empty();
    99 
    100     // Also re-allow initWalletPayments() if you use a guard inside it
    101     // e.g. `walletPaymentsInitialized = false;`
    102     window.walletPaymentsInitialized = false;
    103     walletPaymentsInitialized = false;
    104   }
    105 
    106   /**
    107    * Intercept place_order if squaresync_credit is chosen, so we can tokenize.
    108    */
    109   $(document).on('click', '#place_order', function (e) {
    110     const method = $('#payment input[name="payment_method"]:checked').val();
    111     if (method !== 'squaresync_credit' || paymentInProgress) return;
    112 
    113     e.preventDefault();
    114     paymentInProgress = true;
    115     $(document.body).trigger('checkout_place_order_squaresync_credit');
    116   });
    117 
    118   /**
    119    * Actually tokenize the card, store nonce, then re-submit.
    120    */
    121   $(document.body).on('checkout_place_order_squaresync_credit', async function () {
    122     const success = await processCreditCardPayment(payments, walletPaymentRequest);
    123     paymentInProgress = false;
    124     if (success) {
    125       if (SquareConfig.context === 'account') {
    126         $('#add_payment_method').trigger('submit');
    127       } else {
    128         $('form.checkout').trigger('submit');
    129       }
    130     } else {
    131       clearStoredTokens();
    132     }
    133   });
    134 
    135   $( document.body ).on( 'wc_payment_method_selected', scheduleSquareInit );
    136 
    137   /**
    138    * Show/hide the new card fields vs. saved tokens
    139    */
    140   function toggleCardFields() {
    141     const token = $('#payment input[name="wc-squaresync_credit-payment-token"]:checked').val();
    142     if (token && token !== 'new') {
    143       $('#payment-form').hide();
    144       $('.woocommerce-SavedPaymentMethods-saveNew').hide();
    145     } else {
    146       $('#payment-form').show();
    147       $('.woocommerce-SavedPaymentMethods-saveNew').show();
    148     }
    149   }
    150 
    151   // Debounced triggers from WooCommerce
    152   $(document.body).on('updated_checkout', scheduleSquareInit);
    153   $(document.body).on('change', '#payment input[name="payment_method"]', scheduleSquareInit);
    154 
    155   $(document).on('click', '#wc-squaresync_credit-payment-token-new', function (e) {
    156     $('#payment-form').show();
    157   });
    158   $(document).on('click', '.woocommerce-SavedPaymentMethods-token input', function (e) {
    159     $('#payment-form').hide();
    160   });
    161 
    162   // If user picks "Use a new card," re-check
    163   // $(document).on('change', '#payment input[name="wc-squaresync_credit-payment-token"]', function () {
    164   //   toggleCardFields();
    165   //   const method = $('#payment input[name="payment_method"]:checked').val();
    166   //   if ($(this).val() === 'new' && method === 'squaresync_credit') {
    167   //     forceCleanCardContainer()
    168   //     forceCleanWalletButtons()
    169   //     scheduleSquareInit();
    170   //   }
    171   // });
    172 
    173   // On account page "Add Payment Method", do an init once
    174   $(document).ready(function () {
    175     if (SquareConfig.context === 'account') {
    176       $(document.body).trigger('wc_payment_method_selected');
    177     }
    178   });
    179 
    180   // On checkout_error, clear tokens
    181   $(document.body).on('checkout_error', function () {
    182     clearStoredTokens();
    183   });
    184 
    185 })(jQuery);
     1( function ( $ ) {
     2    let payments = null;
     3    let walletPaymentRequest = null;
     4    let paymentInProgress = false;
     5    let initializationInProgress = false;
     6    let sdkLoadPromise = null;
     7
     8    let alreadyInitialized = false; // Guard for initial load
     9
     10    // Debounce timer
     11    let squareInitTimeout = null;
     12    const DEBOUNCE_DELAY = 300; // Increased from 20ms to 300ms for better stability
     13
     14    // Cached jQuery selectors
     15    const $cachedSelectors = {};
     16
     17    // Helper to get cached jQuery selector
     18    function getCached(selector) {
     19        if (!$cachedSelectors[selector]) {
     20            $cachedSelectors[selector] = $(selector);
     21        }
     22        return $cachedSelectors[selector];
     23    }
     24
     25    // Clear cached selectors on checkout update
     26    function clearSelectorCache() {
     27        for (let key in $cachedSelectors) {
     28            delete $cachedSelectors[key];
     29        }
     30    }
     31
     32    // We remove lastKnownTotal logic & the booleans, allowing each partial refresh to re-init
     33
     34    /**
     35     * Wait for Square SDK to be loaded
     36     */
     37    function waitForSquareSDK() {
     38        if (sdkLoadPromise) {
     39            return sdkLoadPromise;
     40        }
     41
     42        sdkLoadPromise = new Promise((resolve, reject) => {
     43            let attempts = 0;
     44            const maxAttempts = 50; // 5 seconds total wait time
     45
     46            const checkSquare = () => {
     47                if (typeof Square !== 'undefined' && Square.payments) {
     48                    resolve(Square);
     49                } else if (attempts >= maxAttempts) {
     50                    reject(new Error('Square SDK failed to load after 5 seconds'));
     51                } else {
     52                    attempts++;
     53                    setTimeout(checkSquare, 100);
     54                }
     55            };
     56
     57            checkSquare();
     58        });
     59
     60        return sdkLoadPromise;
     61    }
     62
     63    /**
     64     * Debounces the Square init calls so multiple near-simultaneous triggers
     65     * only cause a single actual initialization attempt.
     66     */
     67    function scheduleSquareInit() {
     68        if ( squareInitTimeout ) {
     69            clearTimeout( squareInitTimeout );
     70        }
     71        squareInitTimeout = setTimeout( handleSquareInit, DEBOUNCE_DELAY );
     72    }
     73
     74    /**
     75     * Main initialization if squaresync_credit is chosen.
     76     * Called after the debounce timer.
     77     */
     78    async function handleSquareInit() {
     79        // Prevent concurrent initialization attempts
     80        if (initializationInProgress) {
     81            console.log('Square initialization already in progress, skipping...');
     82            return;
     83        }
     84
     85        const selectedMethod = $(
     86            '#payment input[name="payment_method"]:checked'
     87        ).val();
     88        if ( selectedMethod !== 'squaresync_credit' ) {
     89            return;
     90        }
     91
     92        initializationInProgress = true;
     93        clearStoredTokens();
     94
     95        try {
     96            // Wait for Square SDK to be fully loaded
     97            await waitForSquareSDK();
     98            console.log('Square SDK loaded successfully');
     99            // Create 'payments' once if not done yet
     100            if ( ! payments ) {
     101                const applicationId = SquareConfig.applicationId;
     102                const locationId = SquareConfig.locationId;
     103
     104                if (!applicationId || !locationId) {
     105                    throw new Error('Square configuration missing: applicationId or locationId');
     106                }
     107
     108                payments = await Square.payments( applicationId, locationId );
     109                console.log( 'Square payments instance created:', payments );
     110                if ( ! payments ) {
     111                    throw new Error( 'Square payments init failed' );
     112                }
     113            }
     114
     115            const needsShipping = await checkNeedsShipping();
     116            const couponApplied = false;
     117            // Build or refresh the PaymentRequest object
     118            walletPaymentRequest = await initPaymentRequest(
     119                payments,
     120                needsShipping,
     121                couponApplied
     122            );
     123
     124            // Show/hide card fields
     125            toggleCardFields();
     126
     127            // Only clean and reinitialize card if it doesn't exist or is broken
     128            const cardContainer = document.getElementById('card-container');
     129            const existingCardIframe = cardContainer ? cardContainer.querySelector('.sq-card-iframe-container iframe') : null;
     130
     131            if (!existingCardIframe || !window.squareCard) {
     132                // Card needs initialization
     133                forceCleanCardContainer();
     134                initCreditCardPayment( payments, walletPaymentRequest );
     135            } else {
     136                // Card already exists and is working, skip reinitialization
     137                console.log('Credit card form already initialized, keeping existing instance');
     138            }
     139
     140            // Also forcibly remove leftover wallet buttons, then re-init
     141            if ( walletPaymentRequest ) {
     142                forceCleanWalletButtons();
     143                initWalletPayments(
     144                    payments,
     145                    walletPaymentRequest,
     146                    needsShipping,
     147                    couponApplied
     148                );
     149            }
     150
     151            alreadyInitialized = true;
     152        } catch ( err ) {
     153            console.error( 'Square init error:', err );
     154            // Reset payments on error to allow retry
     155            if (err.message && err.message.includes('Square SDK')) {
     156                sdkLoadPromise = null; // Allow retry of SDK loading
     157            }
     158            logPaymentError('Payment system initialization failed. Please refresh the page.');
     159        } finally {
     160            initializationInProgress = false;
     161        }
     162    }
     163
     164    /**
     165     * Remove any leftover .sq-card-wrapper from partial refresh
     166     * Only call this when you actually need to reinitialize the card
     167     */
     168    function forceCleanCardContainer() {
     169        const $container = $( '#payment #card-container' );
     170        if ( $container.length ) {
     171            // Check if card instance exists and properly detach it
     172            if (window.squareCard && typeof window.squareCard.destroy === 'function') {
     173                try {
     174                    window.squareCard.destroy();
     175                    window.squareCard = null;
     176                    console.log('Destroyed existing card instance');
     177                } catch (e) {
     178                    console.warn('Error destroying card instance:', e);
     179                }
     180            }
     181            $container.find( '.sq-card-wrapper' ).remove();
     182            $container.find( '.sq-card-iframe-container' ).remove();
     183        }
     184    }
     185
     186    /**
     187     * Remove leftover wallet button elements
     188     */
     189    function forceCleanWalletButtons() {
     190        // Clean up wallet instances if cleanup function exists
     191        if (typeof cleanupWalletInstances === 'function') {
     192            cleanupWalletInstances();
     193        }
     194
     195        // Don't empty Google Pay if button already exists
     196        const googlePayExists = document.querySelector('#gpay-button-online-api-id');
     197        if (!googlePayExists) {
     198            jQuery( '#google-pay-button' ).empty();
     199        }
     200
     201        // Don't empty Afterpay if button already exists
     202        const afterpayExists = document.querySelector('.sq-ap__button');
     203        if (!afterpayExists) {
     204            jQuery( '#afterpay-button' ).empty();
     205        }
     206
     207        // Apple Pay can be safely emptied as it doesn't persist
     208        jQuery( '#apple-pay-button' ).empty();
     209
     210        // Also re-allow initWalletPayments() if you use a guard inside it
     211        // e.g. `walletPaymentsInitialized = false;`
     212        window.walletPaymentsInitialized = false;
     213        walletPaymentsInitialized = false;
     214    }
     215
     216    /**
     217     * Intercept place_order if squaresync_credit is chosen, so we can tokenize.
     218     */
     219    $( document ).on( 'click', '#place_order', function ( e ) {
     220        const method = $(
     221            '#payment input[name="payment_method"]:checked'
     222        ).val();
     223        if ( method !== 'squaresync_credit' || paymentInProgress ) return;
     224
     225        e.preventDefault();
     226        paymentInProgress = true;
     227        $( document.body ).trigger( 'checkout_place_order_squaresync_credit' );
     228    } );
     229
     230    /**
     231     * Actually tokenize the card, store nonce, then re-submit.
     232     */
     233    $( document.body ).on(
     234        'checkout_place_order_squaresync_credit',
     235        async function () {
     236            // Clear any stale nonces before generating a new one
     237            clearStoredTokens();
     238            console.log('Starting payment processing - cleared any stale nonces');
     239
     240            const success = await processCreditCardPayment(
     241                payments,
     242                walletPaymentRequest
     243            );
     244            paymentInProgress = false;
     245            if ( success ) {
     246                if ( SquareConfig.context === 'account' ) {
     247                    $( '#add_payment_method' ).trigger( 'submit' );
     248                } else {
     249                    // Handle both checkout and pay-for-order forms
     250                    const $form = $( 'form.checkout, form#order_review' );
     251                    if ( $form.length ) {
     252                        $form.trigger( 'submit' );
     253                    } else {
     254                        console.error( 'Could not find checkout form to submit' );
     255                    }
     256                }
     257            } else {
     258                console.log('Payment processing failed - nonces cleared');
     259                clearStoredTokens();
     260            }
     261        }
     262    );
     263
     264    $( document.body ).on( 'wc_payment_method_selected', scheduleSquareInit );
     265
     266    /**
     267     * Show/hide the new card fields vs. saved tokens
     268     */
     269    function toggleCardFields() {
     270        const token = $(
     271            '#payment input[name="wc-squaresync_credit-payment-token"]:checked'
     272        ).val();
     273        if ( token && token !== 'new' ) {
     274            $( '#payment-form' ).hide();
     275            $( '.woocommerce-SavedPaymentMethods-saveNew' ).hide();
     276        } else {
     277            $( '#payment-form' ).show();
     278            $( '.woocommerce-SavedPaymentMethods-saveNew' ).show();
     279        }
     280    }
     281
     282    // Debounced triggers from WooCommerce
     283    $( document.body ).on( 'updated_checkout', function(e, data) {
     284        // Check if this is a minor update (like coupon application)
     285        const isMinorUpdate = data && (data.coupon_applied || data.coupon_removed);
     286
     287        if (!isMinorUpdate) {
     288            clearSelectorCache();
     289        }
     290
     291        // Always schedule init but it will skip if card already exists
     292        scheduleSquareInit();
     293    });
     294    $( document.body ).on(
     295        'change',
     296        '#payment input[name="payment_method"]',
     297        function() {
     298            // Payment method changed, need full reinit
     299            clearSelectorCache();
     300            scheduleSquareInit();
     301        }
     302    );
     303
     304    $( document ).on(
     305        'click',
     306        '#wc-squaresync_credit-payment-token-new',
     307        function ( e ) {
     308            $( '#payment-form' ).show();
     309            // Initialize Square when switching to new payment method
     310            // Only trigger on pay-for-order pages where updated_checkout doesn't fire
     311            const method = $('#payment input[name="payment_method"]:checked').val();
     312            const isPayForOrderPage = $('body').hasClass('woocommerce-order-pay');
     313            if (method === 'squaresync_credit' && isPayForOrderPage) {
     314                scheduleSquareInit();
     315            }
     316        }
     317    );
     318    $( document ).on(
     319        'click',
     320        '.woocommerce-SavedPaymentMethods-token input',
     321        function ( e ) {
     322            $( '#payment-form' ).hide();
     323        }
     324    );
     325
     326    // If user picks "Use a new card," re-check
     327    // $(document).on('change', '#payment input[name="wc-squaresync_credit-payment-token"]', function () {
     328    //   toggleCardFields();
     329    //   const method = $('#payment input[name="payment_method"]:checked').val();
     330    //   if ($(this).val() === 'new' && method === 'squaresync_credit') {
     331    //     forceCleanCardContainer()
     332    //     forceCleanWalletButtons()
     333    //     scheduleSquareInit();
     334    //   }
     335    // });
     336
     337    // On account page "Add Payment Method", do an init once
     338    $( document ).ready( function () {
     339        if ( SquareConfig.context === 'account' ) {
     340            $( document.body ).trigger( 'wc_payment_method_selected' );
     341        }
     342
     343        // On pay-for-order pages, initialize Square if the payment method is already selected
     344        const isPayForOrderPage = $('body').hasClass('woocommerce-order-pay');
     345        const isSquareSelected = $('#payment_method_squaresync_credit').is(':checked');
     346        if ( isPayForOrderPage && isSquareSelected ) {
     347            scheduleSquareInit();
     348        }
     349    } );
     350
     351    // On checkout_error, clear tokens and fully re-initialize card + wallets
     352    $( document.body ).on( 'checkout_error', function () {
     353        try {
     354            console.log('checkout_error event fired - clearing nonces and reinitializing');
     355            clearStoredTokens();
     356            // Clean existing UI/instances to avoid stale nonce or stuck state
     357            forceCleanCardContainer();
     358            forceCleanWalletButtons();
     359            // Re-run initialization to mount fresh instances
     360            scheduleSquareInit();
     361            paymentInProgress = false;
     362        } catch (e) {
     363            console.warn('Square re-init after checkout_error failed:', e);
     364        }
     365    } );
     366
     367    // Additional handler: Reset on form submission failure (defense-in-depth for customized checkouts)
     368    // This catches cases where checkout_error might not fire consistently
     369    let formSubmissionAttempted = false;
     370    $( document ).on( 'submit', 'form.checkout, form#order_review', function() {
     371        const method = $( '#payment input[name="payment_method"]:checked' ).val();
     372        if ( method === 'squaresync_credit' ) {
     373            formSubmissionAttempted = true;
     374            console.log('Form submission attempted with Square payment');
     375        }
     376    } );
     377
     378    // Monitor for WooCommerce error notices appearing after form submission
     379    const observer = new MutationObserver(function(mutations) {
     380        mutations.forEach(function(mutation) {
     381            if (mutation.addedNodes.length) {
     382                mutation.addedNodes.forEach(function(node) {
     383                    // Check if error notices were added to the page
     384                    if (node.nodeType === 1 && (
     385                        $(node).hasClass('woocommerce-error') ||
     386                        $(node).hasClass('woocommerce-NoticeGroup-checkout') ||
     387                        $(node).find('.woocommerce-error').length
     388                    )) {
     389                        const method = $( '#payment input[name="payment_method"]:checked' ).val();
     390                        if (formSubmissionAttempted && method === 'squaresync_credit') {
     391                            console.log('Payment error detected via notice - clearing nonces for retry');
     392                            clearStoredTokens();
     393                            paymentInProgress = false;
     394                            formSubmissionAttempted = false;
     395                            // Card instance should remain for retry, but nonces are cleared
     396                        }
     397                    }
     398                });
     399            }
     400        });
     401    });
     402
     403    // Start observing the checkout form area for error notices
     404    $( document ).ready( function() {
     405        const checkoutForm = document.querySelector('.woocommerce-checkout, .woocommerce-order-pay');
     406        if (checkoutForm) {
     407            observer.observe(checkoutForm, { childList: true, subtree: true });
     408        }
     409
     410        // Clear stale nonces when page is shown from browser cache (back button)
     411        window.addEventListener('pageshow', function(event) {
     412            if (event.persisted) {
     413                // Page was loaded from cache (back/forward button)
     414                console.log('Page shown from cache - clearing any stale payment nonces');
     415                clearStoredTokens();
     416                paymentInProgress = false;
     417                formSubmissionAttempted = false;
     418            }
     419        });
     420    } );
     421
     422    // Handle coupon-specific events to prevent card destruction
     423    $( document.body ).on( 'applied_coupon removed_coupon', function(e) {
     424        console.log('Coupon event detected, preserving card fields');
     425        // Just update payment request without destroying card
     426        if (payments && walletPaymentRequest) {
     427            checkNeedsShipping().then(needsShipping => {
     428                initPaymentRequest(payments, needsShipping, true).then(updatedRequest => {
     429                    if (updatedRequest) {
     430                        walletPaymentRequest = updatedRequest;
     431                        console.log('Payment request updated for coupon change');
     432                    }
     433                });
     434            });
     435        }
     436    });
     437} )( jQuery );
  • squarewoosync/trunk/assets/js/wallets.js

    r3310892 r3431463  
    11let walletPaymentsInitialized = false;
     2let walletInstances = {}; // Cache wallet instances
     3
     4// Global helper functions to avoid duplication
     5/**********************************************************/
     6/** Helper: transformContact                             **/
     7/**********************************************************/
     8function transformContact( contact, isAfterpay, fallback = {} ) {
     9    // If there's no contact at all, we immediately fallback.
     10    if ( ! contact || typeof contact !== 'object' ) {
     11        contact = {};
     12    }
     13
     14    const {
     15        familyName,
     16        givenName,
     17        region, // Afterpay uses `region`
     18        state, // Apple/Google Pay uses `state`
     19        country, // Afterpay uses `country`
     20        countryCode, // Apple/Google uses `countryCode`
     21        city,
     22        addressLines,
     23        postalCode,
     24        phone,
     25        email,
     26    } = contact;
     27
     28    const {
     29        first_name: fallbackGivenName = '',
     30        last_name: fallbackFamilyName = '',
     31        address_1: fallbackAddress1 = '',
     32        address_2: fallbackAddress2 = '',
     33        city: fallbackCity = '',
     34        state: fallbackState = '',
     35        country: fallbackCountry = '',
     36        postcode: fallbackPostcode = '',
     37        phone: fallbackPhone = '',
     38        email: fallbackEmail = '',
     39    } = fallback;
     40
     41    // Use || instead of ?? to handle empty strings from Apple Pay
     42    const mergedGivenName = givenName || fallbackGivenName;
     43    const mergedFamilyName = familyName || fallbackFamilyName;
     44    const mergedCity = city || fallbackCity;
     45    const mergedPostalCode = postalCode || fallbackPostcode;
     46    const mergedEmail = email || fallbackEmail;
     47    const mergedPhone = phone || fallbackPhone;
     48
     49    // For region/state
     50    const mergedState = isAfterpay
     51        ? region || fallbackState
     52        : state || region || fallbackState;
     53
     54    // For country / countryCode
     55    const mergedCountry = isAfterpay
     56        ? country || fallbackCountry
     57        : countryCode || country || fallbackCountry;
     58
     59    // For address lines
     60    let mergedAddressLines = [];
     61    if ( Array.isArray( addressLines ) && addressLines.length > 0 ) {
     62        mergedAddressLines = addressLines;
     63    } else {
     64        // Merge fallback address_1 and address_2 if present
     65        mergedAddressLines = [ fallbackAddress1, fallbackAddress2 ].filter(
     66            Boolean
     67        );
     68    }
     69
     70    return {
     71        givenName: mergedGivenName,
     72        familyName: mergedFamilyName,
     73        state: mergedState,
     74        countryCode: mergedCountry,
     75        city: mergedCity,
     76        addressLines: mergedAddressLines,
     77        postalCode: mergedPostalCode,
     78        phone: mergedPhone,
     79        email: mergedEmail,
     80    };
     81}
     82
     83/**********************************************************/
     84/** Helper: isBillingComplete                            **/
     85/**********************************************************/
     86function isBillingComplete( billingContact ) {
     87    // Define whatever fields you consider "required"
     88    // Adjust as needed for your store's requirements
     89    return (
     90        billingContact &&
     91        billingContact.givenName &&
     92        billingContact.familyName &&
     93        billingContact.addressLines &&
     94        billingContact.addressLines.length > 0 &&
     95        billingContact.city &&
     96        billingContact.state &&
     97        billingContact.postalCode &&
     98        billingContact.countryCode
     99    );
     100}
     101
     102/**********************************************************/
     103/** Helper: isExistingBillingComplete                    **/
     104/** Check if WooCommerce billing form fields are filled  **/
     105/**********************************************************/
     106function isExistingBillingComplete() {
     107    const firstName = jQuery( '#billing_first_name' ).val();
     108    const lastName = jQuery( '#billing_last_name' ).val();
     109    const address1 = jQuery( '#billing_address_1' ).val();
     110    const city = jQuery( '#billing_city' ).val();
     111    const postcode = jQuery( '#billing_postcode' ).val();
     112    const country = jQuery( '#billing_country' ).val();
     113
     114    return (
     115        firstName && firstName.trim() &&
     116        lastName && lastName.trim() &&
     117        address1 && address1.trim() &&
     118        city && city.trim() &&
     119        postcode && postcode.trim() &&
     120        country && country.trim()
     121    );
     122}
     123
     124/**********************************************************/
     125/** Helper: isExistingShippingComplete                   **/
     126/** Check if WooCommerce shipping form fields are filled **/
     127/**********************************************************/
     128function isExistingShippingComplete() {
     129    const firstName = jQuery( '#shipping_first_name' ).val();
     130    const lastName = jQuery( '#shipping_last_name' ).val();
     131    const address1 = jQuery( '#shipping_address_1' ).val();
     132    const city = jQuery( '#shipping_city' ).val();
     133    const postcode = jQuery( '#shipping_postcode' ).val();
     134    const country = jQuery( '#shipping_country' ).val();
     135
     136    return (
     137        firstName && firstName.trim() &&
     138        lastName && lastName.trim() &&
     139        address1 && address1.trim() &&
     140        city && city.trim() &&
     141        postcode && postcode.trim() &&
     142        country && country.trim()
     143    );
     144}
     145
     146/**********************************************************/
     147/** Helper: cleanupWalletInstances                       **/
     148/**********************************************************/
     149function cleanupWalletInstances() {
     150    // Destroy existing wallet instances to prevent memory leaks
     151    for (let key in walletInstances) {
     152        if (walletInstances[key]) {
     153            // Reset the attached flag
     154            if (walletInstances[key]._isAttached) {
     155                walletInstances[key]._isAttached = false;
     156            }
     157            // Try to destroy if method exists
     158            if (typeof walletInstances[key].destroy === 'function') {
     159                try {
     160                    walletInstances[key].destroy();
     161                } catch (e) {
     162                    console.warn(`Error destroying ${key} instance:`, e);
     163                }
     164            }
     165        }
     166        delete walletInstances[key];
     167    }
     168}
    2169
    3170async function initWalletPayments(
    4   payments,
    5   walletPaymentRequest,
    6   needsShipping,
    7   couponApplied
     171    payments,
     172    walletPaymentRequest,
     173    needsShipping,
     174    couponApplied
    8175) {
    9   if (walletPaymentsInitialized) {
    10     return; // Don't run again
    11   }
    12   walletPaymentsInitialized = true;
    13 
    14   if (!payments) {
    15     console.error("Payments object is required for wallet payments.");
    16     return;
    17   }
    18 
    19   // Initialize or reinitialize wallet buttons with updated payment request
    20   async function reinitializeWalletButtons() {
    21     const updatedWalletPaymentRequest = await initPaymentRequest(
    22       payments,
    23       needsShipping,
    24       couponApplied
    25     );
    26 
    27     if (updatedWalletPaymentRequest) {
    28       await attachWalletButtons(
    29         updatedWalletPaymentRequest,
    30         payments,
    31         needsShipping,
    32         couponApplied
    33       );
    34     }
    35   }
    36 
    37   // Attach initial wallet buttons on page load
    38   if (walletPaymentRequest) {
    39     await attachWalletButtons(
    40       walletPaymentRequest,
    41       payments,
    42       needsShipping,
    43       couponApplied
    44     );
    45   }
    46   // reinitializeWalletButtons();
    47   // // Reinitialize wallet buttons whenever cart totals update
    48   // jQuery(document.body).on(
    49   //     "wc_cart_totals_updated updated_shipping_method applied_coupon removed_coupon updated_checkout",
    50   //     async function () {
    51   //         await reinitializeWalletButtons();  // Reinitialize when any cart updates occur
    52   //     }
    53   // );
     176    if ( walletPaymentsInitialized ) {
     177        return; // Don't run again
     178    }
     179    walletPaymentsInitialized = true;
     180
     181    if ( ! payments ) {
     182        console.error( 'Payments object is required for wallet payments.' );
     183        return;
     184    }
     185
     186    // Initialize or reinitialize wallet buttons with updated payment request
     187    async function reinitializeWalletButtons() {
     188        const updatedWalletPaymentRequest = await initPaymentRequest(
     189            payments,
     190            needsShipping,
     191            couponApplied
     192        );
     193
     194        if ( updatedWalletPaymentRequest ) {
     195            await attachWalletButtons(
     196                updatedWalletPaymentRequest,
     197                payments,
     198                needsShipping,
     199                couponApplied
     200            );
     201        }
     202    }
     203
     204    // Attach initial wallet buttons on page load
     205    if ( walletPaymentRequest ) {
     206        await attachWalletButtons(
     207            walletPaymentRequest,
     208            payments,
     209            needsShipping,
     210            couponApplied
     211        );
     212    }
    54213}
    55214
    56 /**********************************************************/
    57 /** 1) Helper: transformContact                          **/
    58 /**********************************************************/
    59 function transformContact(contact, isAfterpay, fallback = {}) {
    60   // If there's no contact at all, we immediately fallback.
    61   if (!contact || typeof contact !== "object") {
    62     contact = {};
    63   }
    64 
    65   const {
    66     familyName,
    67     givenName,
    68     region, // Afterpay uses `region`
    69     state, // Apple/Google Pay uses `state`
    70     country, // Afterpay uses `country`
    71     countryCode, // Apple/Google uses `countryCode`
    72     city,
    73     addressLines,
    74     postalCode,
    75     phone,
    76     email,
    77   } = contact;
    78 
    79   const {
    80     first_name: fallbackGivenName = "",
    81     last_name: fallbackFamilyName = "",
    82     address_1: fallbackAddress1 = "",
    83     address_2: fallbackAddress2 = "",
    84     city: fallbackCity = "",
    85     state: fallbackState = "",
    86     country: fallbackCountry = "",
    87     postcode: fallbackPostcode = "",
    88     phone: fallbackPhone = "",
    89     email: fallbackEmail = "",
    90   } = fallback;
    91 
    92   const mergedGivenName = givenName ?? fallbackGivenName;
    93   const mergedFamilyName = familyName ?? fallbackFamilyName;
    94   const mergedCity = city ?? fallbackCity;
    95   const mergedPostalCode = postalCode ?? fallbackPostcode;
    96   const mergedEmail = email ?? fallbackEmail;
    97   const mergedPhone = phone ?? fallbackPhone;
    98 
    99   // For region/state
    100   const mergedState = isAfterpay
    101     ? region ?? fallbackState
    102     : state ?? region ?? fallbackState;
    103 
    104   // For country / countryCode
    105   const mergedCountry = isAfterpay
    106     ? country ?? fallbackCountry
    107     : countryCode ?? country ?? fallbackCountry;
    108 
    109   // For address lines
    110   let mergedAddressLines = [];
    111   if (Array.isArray(addressLines) && addressLines.length > 0) {
    112     mergedAddressLines = addressLines;
    113   } else {
    114     // Merge fallback address_1 and address_2 if present
    115     mergedAddressLines = [fallbackAddress1, fallbackAddress2].filter(Boolean);
    116   }
    117 
    118   return {
    119     givenName: mergedGivenName,
    120     familyName: mergedFamilyName,
    121     state: mergedState,
    122     countryCode: mergedCountry,
    123     city: mergedCity,
    124     addressLines: mergedAddressLines,
    125     postalCode: mergedPostalCode,
    126     phone: mergedPhone,
    127     email: mergedEmail,
    128   };
     215async function attachWalletButtons(
     216    paymentRequest,
     217    payments,
     218    needsShipping,
     219    couponApplied
     220) {
     221    // Ensure payments object exists
     222    if (!payments) {
     223        console.error('Payments object is required for wallet buttons');
     224        return;
     225    }
     226
     227    // Add event listeners to paymentRequest for Apple Pay / Google Pay
     228    // These must be added before wallet button initialization
     229    // Using window-scoped functions from utils.js for proper cross-script access
     230    if (paymentRequest && !paymentRequest._walletListenersAdded) {
     231        paymentRequest.addEventListener(
     232            'shippingcontactchanged',
     233            async ( shippingContact ) => {
     234                return await window.handleShippingAddressChanged( shippingContact );
     235            }
     236        );
     237        paymentRequest.addEventListener(
     238            'shippingoptionchanged',
     239            async ( option ) => {
     240                return await window.handleShippingOptionChanged( option );
     241            }
     242        );
     243        paymentRequest._walletListenersAdded = true;
     244    }
     245
     246    // Track which wallets were successfully initialized
     247    let activeWallets = 0;
     248
     249    // Get all wallet containers and remove the has-wallets class initially
     250    const walletContainers = document.querySelectorAll('.sws-legacy-wallets');
     251    walletContainers.forEach(container => {
     252        container.classList.remove('has-wallets');
     253    });
     254
     255    /**********************************************************/
     256    /** handleTokenizationAndVerification                    **/
     257    /**********************************************************/
     258    async function handleTokenizationAndVerification(
     259        walletInstance,
     260        walletType
     261    ) {
     262        if (!walletInstance) {
     263            console.error(`${walletType} instance is null or undefined`);
     264            return;
     265        }
     266
     267        try {
     268            const tokenResult = await walletInstance.tokenize();
     269
     270            if ( tokenResult.status === 'OK' ) {
     271                // Attach raw nonce/token to a hidden field
     272                attachTokenToForm( tokenResult.token );
     273
     274                // We assume `walletType === "AfterpayClearpay"` for Afterpay logic
     275                const isAfterpay = walletType === 'Afterpay';
     276
     277                // Ensure "Ship to a different address" is checked if we have shipping details
     278                const shipToDifferentAddressCheckbox = jQuery(
     279                    '#ship-to-different-address-checkbox'
     280                );
     281                if ( shipToDifferentAddressCheckbox.length && ! shipToDifferentAddressCheckbox.is( ':checked' ) ) {
     282                    shipToDifferentAddressCheckbox.prop( 'checked', true );
     283                    jQuery( 'div.shipping_address' ).show(); // Make sure shipping fields are visible
     284                }
     285
     286                /*******************************************************/
     287                /** Extract shipping & billing from tokenResult      **/
     288                /*******************************************************/
     289                const shippingDetails =
     290                    tokenResult?.details?.shipping?.contact || {};
     291                const billingDetails = tokenResult?.details?.billing || {};
     292
     293                // In case your legacy checkout still needs to fallback to
     294                // current form values if the contact is missing data:
     295                const fallbackShipping = {
     296                    first_name: jQuery( '#shipping_first_name' ).val(),
     297                    last_name: jQuery( '#shipping_last_name' ).val(),
     298                    address_1: jQuery( '#shipping_address_1' ).val(),
     299                    address_2: jQuery( '#shipping_address_2' ).val(),
     300                    city: jQuery( '#shipping_city' ).val(),
     301                    state: jQuery( '#shipping_state' ).val(),
     302                    postcode: jQuery( '#shipping_postcode' ).val(),
     303                    country: jQuery( '#shipping_country' ).val(),
     304                    phone: jQuery( '#shipping_phone' ).val(),
     305                    email: jQuery( '#billing_email' ).val(), // Sometimes shipping doesn't have its own email
     306                };
     307                const fallbackBilling = {
     308                    first_name: jQuery( '#billing_first_name' ).val(),
     309                    last_name: jQuery( '#billing_last_name' ).val(),
     310                    address_1: jQuery( '#billing_address_1' ).val(),
     311                    address_2: jQuery( '#billing_address_2' ).val(),
     312                    city: jQuery( '#billing_city' ).val(),
     313                    state: jQuery( '#billing_state' ).val(),
     314                    postcode: jQuery( '#billing_postcode' ).val(),
     315                    country: jQuery( '#billing_country' ).val(),
     316                    phone: jQuery( '#billing_phone' ).val(),
     317                    email: jQuery( '#billing_email' ).val(),
     318                };
     319
     320                // Transform shipping contact
     321                const shippingContact = transformContact(
     322                    shippingDetails,
     323                    isAfterpay,
     324                    fallbackShipping
     325                );
     326
     327                // Transform billing contact
     328                let billingContact = transformContact(
     329                    billingDetails,
     330                    isAfterpay,
     331                    fallbackBilling
     332                );
     333
     334                // If billing is incomplete, prioritize WooCommerce billing fields
     335                if ( ! isBillingComplete( billingContact ) ) {
     336                    // First try WooCommerce billing form fields directly
     337                    const wooCommerceBilling = transformContact(
     338                        {},  // No Apple Pay data - use fallback only
     339                        isAfterpay,
     340                        fallbackBilling  // Use WooCommerce BILLING form fields
     341                    );
     342
     343                    // Only use shipping as last resort if WooCommerce billing is also empty
     344                    if ( ! isBillingComplete( wooCommerceBilling ) ) {
     345                        const shippingAsBilling = transformContact(
     346                            shippingDetails,
     347                            isAfterpay,
     348                            fallbackBilling  // Still use billing fallback, not shipping
     349                        );
     350                        billingContact = {
     351                            ...shippingAsBilling,
     352                            email:
     353                                billingContact.email ||
     354                                shippingAsBilling.email ||
     355                                shippingDetails.email,
     356                        };
     357                    } else {
     358                        // Use WooCommerce billing as primary fallback
     359                        billingContact = {
     360                            ...wooCommerceBilling,
     361                            email: billingContact.email || wooCommerceBilling.email,
     362                        };
     363                    }
     364                }
     365
     366                // Verify buyer for SCA compliance (3D Secure)
     367                const orderTotal = SquareConfig.orderTotal || '0.00';
     368                const verificationDetails = {
     369                    intent: 'CHARGE',
     370                    amount: orderTotal,
     371                    currencyCode: SquareConfig.currency || 'USD',
     372                    billingContact: {
     373                        givenName: billingContact.givenName || '',
     374                        familyName: billingContact.familyName || '',
     375                        email: billingContact.email || '',
     376                        phone: billingContact.phone || '',
     377                        country: billingContact.countryCode || '',
     378                        region: billingContact.state || '',
     379                        city: billingContact.city || '',
     380                        postalCode: billingContact.postalCode || '',
     381                        addressLines: billingContact.addressLines || [],
     382                    },
     383                };
     384
     385                try {
     386                    const verificationResult = await payments.verifyBuyer(
     387                        tokenResult.token,
     388                        verificationDetails
     389                    );
     390                    if ( verificationResult && verificationResult.token ) {
     391                        attachVerificationTokenToForm( verificationResult.token );
     392                    }
     393                } catch ( verifyError ) {
     394                    console.error( 'Buyer verification failed:', verifyError );
     395                    // Continue anyway for non-SCA regions, but log the error
     396                }
     397
     398                // Shipping:
     399                // Only update shipping if store needs shipping AND existing shipping is incomplete
     400                const shouldUpdateShipping = typeof needsShipping !== 'undefined' && needsShipping && ! isExistingShippingComplete();
     401
     402                if ( shouldUpdateShipping ) {
     403                    jQuery( '#shipping_first_name' ).val(
     404                        shippingContact.givenName || ''
     405                    );
     406                    jQuery( '#shipping_last_name' ).val(
     407                        shippingContact.familyName || ''
     408                    );
     409                    jQuery( '#shipping_company' ).val( '' );
     410                    jQuery( '#shipping_address_1' ).val(
     411                        shippingContact.addressLines[ 0 ] || ''
     412                    );
     413                    jQuery( '#shipping_address_2' ).val(
     414                        shippingContact.addressLines[ 1 ] || ''
     415                    );
     416                    jQuery( '#shipping_city' ).val(
     417                        shippingContact.city || ''
     418                    );
     419                    jQuery( '#shipping_state' ).val(
     420                        shippingContact.state || ''
     421                    );
     422                    jQuery( '#shipping_postcode' ).val(
     423                        shippingContact.postalCode || ''
     424                    );
     425                    jQuery( '#shipping_country' ).val(
     426                        shippingContact.countryCode || ''
     427                    );
     428                    jQuery( '#shipping_phone' ).val(
     429                        shippingContact.phone || ''
     430                    );
     431                }
     432
     433                /*********************************************************/
     434                /** Update Legacy Billing & Shipping form fields       **/
     435                /*********************************************************/
     436                // Only update billing fields if existing billing is incomplete
     437                const shouldUpdateBilling = ! isExistingBillingComplete();
     438
     439                if ( shouldUpdateBilling ) {
     440                    // — now country/state —
     441                    jQuery( '#billing_country' )
     442                        .val( billingContact.countryCode || '' )
     443                        .trigger( 'change' ); // ⬅️ rebuild states
     444                }
     445
     446                // give WooCommerce a moment to repopulate the state <select>
     447                setTimeout( function () {
     448                    if ( shouldUpdateBilling ) {
     449                        jQuery( '#billing_state' )
     450                            .val( billingContact.state || '' )
     451                            .trigger( 'change' );
     452
     453                        // Billing:
     454                        jQuery( '#billing_first_name' ).val(
     455                            billingContact.givenName || ''
     456                        );
     457                        jQuery( '#billing_last_name' ).val(
     458                            billingContact.familyName || ''
     459                        );
     460                        jQuery( '#billing_company' ).val( '' ); // no company in token result
     461                        jQuery( '#billing_address_1' ).val(
     462                            billingContact.addressLines[ 0 ] || ''
     463                        );
     464                        jQuery( '#billing_address_2' ).val(
     465                            billingContact.addressLines[ 1 ] || ''
     466                        );
     467                        // … your other field‐fills …
     468                        jQuery( '#billing_city' ).val( billingContact.city || '' );
     469                        jQuery( '#billing_postcode' ).val(
     470                            billingContact.postalCode || ''
     471                        );
     472
     473                        // … then the rest …
     474                        jQuery( '#billing_phone' ).val(
     475                            billingContact.phone || ''
     476                        );
     477                        jQuery( '#billing_email' ).val(
     478                            billingContact.email || ''
     479                        );
     480                    }
     481
     482                    // Handle both checkout and pay-for-order forms
     483                    const $form = jQuery( 'form.checkout, form#order_review' );
     484                    $form.trigger( 'submit' );
     485                }, 100 );
     486            } else {
     487                // Clear stored tokens or error-handling
     488                clearStoredTokens();
     489                if ( tokenResult.status !== 'Cancel' ) {
     490                    const errorMessage = tokenResult.errors
     491                        ? tokenResult.errors.map(e => e.message || e).join(', ')
     492                        : 'Unknown error';
     493                    logPaymentError(`${walletType} payment failed: ${errorMessage}`);
     494                }
     495            }
     496        } catch ( error ) {
     497            clearStoredTokens();
     498            logPaymentError(
     499                `${ walletType } tokenization or verification error: ${ error.message }`
     500            );
     501        }
     502    }
     503
     504    // Apple Pay Initialization or Update
     505    if ( SquareConfig.applePayEnabled === 'yes' ) {
     506        try {
     507            const applePayButtonContainer =
     508                document.querySelector( '#sws-applepay-legacy' );
     509            if ( applePayButtonContainer ) {
     510                // Remove active class initially
     511                applePayButtonContainer.classList.remove('wallet-active');
     512
     513                try {
     514                    // Reuse existing instance if available
     515                    if (!walletInstances.applePay) {
     516                        // Apple Pay also needs the paymentRequest object
     517                        walletInstances.applePay = await payments.applePay(
     518                            paymentRequest
     519                        );
     520                    }
     521
     522                    // Only show if initialization was successful
     523                    if (walletInstances.applePay) {
     524                        applePayButtonContainer.classList.add('wallet-active');
     525                        applePayButtonContainer.style.display = 'block'; // Override for Apple Pay
     526                        activeWallets++;
     527
     528                        jQuery( '#sws-applepay-legacy' )
     529                            .off( 'click.squarepay' )
     530                            .on( 'click.squarepay', async function ( e ) {
     531                                e.preventDefault();
     532                                await handleTokenizationAndVerification(
     533                                    walletInstances.applePay,
     534                                    'Apple Pay'
     535                                );
     536                            } );
     537                    }
     538                } catch (initError) {
     539                    // Apple Pay genuinely not available (expected on non-Safari browsers)
     540                    if (!initError.message || (!initError.message.includes('not supported') && !initError.message.includes('not available'))) {
     541                        console.error('Apple Pay initialization error:', initError);
     542                    }
     543                    walletInstances.applePay = null;
     544                }
     545            }
     546        } catch ( error ) {
     547            console.error( 'Apple Pay outer error:', error );
     548            walletInstances.applePay = null;
     549            // Remove active class from the Apple Pay button
     550            const applePayButton = document.querySelector('#sws-applepay-legacy');
     551            if (applePayButton) {
     552                applePayButton.classList.remove('wallet-active');
     553            }
     554        }
     555    }
     556
     557    // Google Pay Initialization or Update
     558    if ( SquareConfig.googlePayEnabled === 'yes' ) {
     559        try {
     560            const googlePayButtonContainer =
     561                document.querySelector( '#sws-gpay-legacy' );
     562
     563            // Check if the Google Pay button is already present
     564            const googlePayButtonExists = document.querySelector(
     565                '#gpay-button-online-api-id'
     566            );
     567
     568            if ( googlePayButtonContainer ) {
     569                // Remove active class initially
     570                googlePayButtonContainer.classList.remove('wallet-active');
     571
     572                if ( ! googlePayButtonExists ) {
     573                    try {
     574                        // Reuse existing instance if available
     575                        if (!walletInstances.googlePay) {
     576                            // Google Pay requires the actual paymentRequest object
     577                            if (!paymentRequest || typeof paymentRequest !== 'object') {
     578                                console.error('Invalid payment request object for Google Pay:', paymentRequest);
     579                                return;
     580                            }
     581                            // Pass the paymentRequest directly without modification
     582                            walletInstances.googlePay = await payments.googlePay(
     583                                paymentRequest
     584                            );
     585                        }
     586
     587                        if (walletInstances.googlePay) {
     588                            // Remove any existing click handler before attaching the new one
     589                            jQuery( '#sws-gpay-legacy' )
     590                                .off( 'click.squarepay' )
     591                                .on( 'click.squarepay', async function ( e ) {
     592                                    e.preventDefault();
     593                                    await handleTokenizationAndVerification(
     594                                        walletInstances.googlePay,
     595                                        'Google Pay'
     596                                    );
     597                                } );
     598
     599                            // Attach the Google Pay button
     600                            await walletInstances.googlePay.attach( '#sws-gpay-legacy' );
     601                            googlePayButtonContainer.classList.add('wallet-active');
     602                            googlePayButtonContainer.style.display = 'block'; // Override inline
     603                            activeWallets++;
     604                        }
     605                    } catch (attachError) {
     606                        // Check if it's a real availability issue or just an initialization error
     607                        if (!attachError.message || !attachError.message.includes('not supported')) {
     608                            console.error('Google Pay initialization error:', attachError);
     609                            // Try to show more details about the error
     610                            if (attachError.statusCode) {
     611                                console.error('Status code:', attachError.statusCode);
     612                            }
     613                            if (attachError.errors) {
     614                                console.error('Errors:', attachError.errors);
     615                            }
     616                        }
     617                        walletInstances.googlePay = null;
     618                    }
     619                } else if (googlePayButtonExists) {
     620                    // Button already exists, just mark as active
     621                    googlePayButtonContainer.classList.add('wallet-active');
     622                    googlePayButtonContainer.style.display = 'block';
     623                    activeWallets++;
     624                }
     625            }
     626        } catch ( error ) {
     627            console.error( 'Google Pay outer error:', error );
     628            walletInstances.googlePay = null;
     629            // Remove active class from the Google Pay button
     630            const googlePayButton = document.querySelector('#sws-gpay-legacy');
     631            if (googlePayButton) {
     632                googlePayButton.classList.remove('wallet-active');
     633            }
     634        }
     635    }
     636
     637    // Afterpay Initialization or Update
     638    if ( SquareConfig.afterPayEnabled === 'yes' ) {
     639        try {
     640            const afterPayButtonContainer =
     641                document.querySelector( '#sws-afterpay-legacy' );
     642            // Check for an existing Afterpay button *inside* the container
     643            const afterPayButtonExists = afterPayButtonContainer
     644                ? afterPayButtonContainer.querySelector( '.sq-ap__button' )
     645                : null;
     646
     647            if ( afterPayButtonContainer ) {
     648                // Remove active class initially
     649                afterPayButtonContainer.classList.remove('wallet-active');
     650                afterPayButtonContainer.style.minWidth = '240px';
     651
     652                if ( ! afterPayButtonExists ) {
     653                    try {
     654                        // Add event listeners to paymentRequest BEFORE creating Afterpay instance
     655                        // Using window-scoped functions from utils.js for proper cross-script access
     656                        if (paymentRequest && !paymentRequest._afterpayListenersAdded) {
     657                            paymentRequest.addEventListener(
     658                                'afterpay_shippingaddresschanged',
     659                                async ( shippingContact ) => {
     660                                    const result = await window.handleShippingAddressChanged( shippingContact );
     661                                    return result;
     662                                }
     663                            );
     664                            paymentRequest.addEventListener(
     665                                'afterpay_shippingoptionchanged',
     666                                async ( option ) => {
     667                                    const result = await window.handleShippingOptionChanged( option );
     668                                    return result;
     669                                }
     670                            );
     671                            paymentRequest._afterpayListenersAdded = true;
     672                        }
     673
     674                        // Reuse existing instance if available
     675                        if (!walletInstances.afterPay) {
     676                            walletInstances.afterPay =
     677                                await payments.afterpayClearpay( paymentRequest );
     678                        }
     679
     680                        if (walletInstances.afterPay) {
     681                            // Only attach if we haven't already
     682                            if (!walletInstances.afterPay._isAttached) {
     683                                await walletInstances.afterPay.attach( '#sws-afterpay-legacy' );
     684                                walletInstances.afterPay._isAttached = true;
     685
     686                                // Add click handler to button - Afterpay's attach() does NOT add auto-tokenization
     687                                // We must manually call tokenize() when the user clicks
     688                                const afterpayButtonContainer = document.getElementById('sws-afterpay-legacy');
     689
     690                                if (afterpayButtonContainer) {
     691                                    // Remove any existing click handlers
     692                                    jQuery(afterpayButtonContainer).off('click.afterpay');
     693
     694                                    // Add our click handler
     695                                    jQuery(afterpayButtonContainer).on('click.afterpay', async function(event) {
     696                                        // Prevent double-submission
     697                                        if (jQuery(this).hasClass('processing')) {
     698                                            return;
     699                                        }
     700
     701                                        jQuery(this).addClass('processing');
     702
     703                                        try {
     704                                            // This opens the Afterpay modal and waits for user to complete
     705                                            const tokenResult = await walletInstances.afterPay.tokenize();
     706
     707                                            if (tokenResult.status === 'OK') {
     708                                                // Process the token result
     709                                                attachTokenToForm( tokenResult.token );
     710
     711                                                const isAfterpay = true;
     712
     713                                                // Apply the selected shipping method if one was chosen in Afterpay
     714                                                if (window._afterpaySelectedShipping && window._afterpaySelectedShipping.id) {
     715                                                    const shippingRadio = jQuery(
     716                                                        `input[name="shipping_method[0]"][value="${window._afterpaySelectedShipping.id}"]`
     717                                                    );
     718                                                    if (shippingRadio.length) {
     719                                                        shippingRadio.prop('checked', true);
     720                                                    }
     721                                                    // Clear the stored value
     722                                                    delete window._afterpaySelectedShipping;
     723                                                }
     724
     725                                                // Ensure "Ship to a different address" is checked if we have shipping details
     726                                                const shipToDifferentAddressCheckbox = jQuery(
     727                                                    '#ship-to-different-address-checkbox'
     728                                                );
     729                                                if ( shipToDifferentAddressCheckbox.length && ! shipToDifferentAddressCheckbox.is( ':checked' ) ) {
     730                                                    shipToDifferentAddressCheckbox.prop( 'checked', true );
     731                                                    jQuery( 'div.shipping_address' ).show();
     732                                                }
     733
     734                                                // Extract shipping & billing from tokenResult
     735                                                const shippingDetails =
     736                                                    tokenResult?.details?.shipping?.contact || {};
     737                                                const billingDetails = tokenResult?.details?.billing || {};
     738
     739                                                const fallbackShipping = {
     740                                                    first_name: jQuery( '#shipping_first_name' ).val(),
     741                                                    last_name: jQuery( '#shipping_last_name' ).val(),
     742                                                    address_1: jQuery( '#shipping_address_1' ).val(),
     743                                                    address_2: jQuery( '#shipping_address_2' ).val(),
     744                                                    city: jQuery( '#shipping_city' ).val(),
     745                                                    state: jQuery( '#shipping_state' ).val(),
     746                                                    postcode: jQuery( '#shipping_postcode' ).val(),
     747                                                    country: jQuery( '#shipping_country' ).val(),
     748                                                    phone: jQuery( '#shipping_phone' ).val(),
     749                                                    email: jQuery( '#billing_email' ).val(),
     750                                                };
     751                                                const fallbackBilling = {
     752                                                    first_name: jQuery( '#billing_first_name' ).val(),
     753                                                    last_name: jQuery( '#billing_last_name' ).val(),
     754                                                    address_1: jQuery( '#billing_address_1' ).val(),
     755                                                    address_2: jQuery( '#billing_address_2' ).val(),
     756                                                    city: jQuery( '#billing_city' ).val(),
     757                                                    state: jQuery( '#billing_state' ).val(),
     758                                                    postcode: jQuery( '#billing_postcode' ).val(),
     759                                                    country: jQuery( '#billing_country' ).val(),
     760                                                    phone: jQuery( '#billing_phone' ).val(),
     761                                                    email: jQuery( '#billing_email' ).val(),
     762                                                };
     763
     764                                                // Transform shipping contact
     765                                                const shippingContact = transformContact(
     766                                                    shippingDetails,
     767                                                    isAfterpay,
     768                                                    fallbackShipping
     769                                                );
     770
     771                                                // Transform billing contact
     772                                                let billingContact = transformContact(
     773                                                    billingDetails,
     774                                                    isAfterpay,
     775                                                    fallbackBilling
     776                                                );
     777
     778                                                // If billing is incomplete, prioritize WooCommerce billing fields
     779                                                if ( ! isBillingComplete( billingContact ) ) {
     780                                                    // First try WooCommerce billing form fields directly
     781                                                    const wooCommerceBilling = transformContact(
     782                                                        {},  // No Afterpay data - use fallback only
     783                                                        isAfterpay,
     784                                                        fallbackBilling  // Use WooCommerce BILLING form fields
     785                                                    );
     786
     787                                                    // Only use shipping as last resort if WooCommerce billing is also empty
     788                                                    if ( ! isBillingComplete( wooCommerceBilling ) ) {
     789                                                        const shippingAsBilling = transformContact(
     790                                                            shippingDetails,
     791                                                            isAfterpay,
     792                                                            fallbackBilling  // Still use billing fallback, not shipping
     793                                                        );
     794                                                        billingContact = {
     795                                                            ...shippingAsBilling,
     796                                                            email:
     797                                                                billingContact.email ||
     798                                                                shippingAsBilling.email ||
     799                                                                shippingDetails.email,
     800                                                        };
     801                                                    } else {
     802                                                        // Use WooCommerce billing as primary fallback
     803                                                        billingContact = {
     804                                                            ...wooCommerceBilling,
     805                                                            email: billingContact.email || wooCommerceBilling.email,
     806                                                        };
     807                                                    }
     808                                                }
     809
     810                                                // Verify buyer for SCA compliance (3D Secure) - Afterpay
     811                                                const afterpayOrderTotal = SquareConfig.orderTotal || '0.00';
     812                                                const afterpayVerificationDetails = {
     813                                                    intent: 'CHARGE',
     814                                                    amount: afterpayOrderTotal,
     815                                                    currencyCode: SquareConfig.currency || 'USD',
     816                                                    billingContact: {
     817                                                        givenName: billingContact.givenName || '',
     818                                                        familyName: billingContact.familyName || '',
     819                                                        email: billingContact.email || '',
     820                                                        phone: billingContact.phone || '',
     821                                                        country: billingContact.countryCode || '',
     822                                                        region: billingContact.state || '',
     823                                                        city: billingContact.city || '',
     824                                                        postalCode: billingContact.postalCode || '',
     825                                                        addressLines: billingContact.addressLines || [],
     826                                                    },
     827                                                };
     828
     829                                                try {
     830                                                    const verificationResult = await payments.verifyBuyer(
     831                                                        tokenResult.token,
     832                                                        afterpayVerificationDetails
     833                                                    );
     834                                                    if ( verificationResult && verificationResult.token ) {
     835                                                        attachVerificationTokenToForm( verificationResult.token );
     836                                                    }
     837                                                } catch ( verifyError ) {
     838                                                    console.error( 'Afterpay buyer verification failed:', verifyError );
     839                                                    // Continue anyway for non-SCA regions, but log the error
     840                                                }
     841
     842                                                // Update shipping fields only if existing shipping is incomplete
     843                                                const shouldUpdateShippingAfterpay = typeof needsShipping !== 'undefined' && needsShipping && ! isExistingShippingComplete();
     844
     845                                                if ( shouldUpdateShippingAfterpay ) {
     846                                                    jQuery( '#shipping_first_name' ).val(
     847                                                        shippingContact.givenName || ''
     848                                                    );
     849                                                    jQuery( '#shipping_last_name' ).val(
     850                                                        shippingContact.familyName || ''
     851                                                    );
     852                                                    jQuery( '#shipping_company' ).val( '' );
     853                                                    jQuery( '#shipping_address_1' ).val(
     854                                                        shippingContact.addressLines[ 0 ] || ''
     855                                                    );
     856                                                    jQuery( '#shipping_address_2' ).val(
     857                                                        shippingContact.addressLines[ 1 ] || ''
     858                                                    );
     859                                                    jQuery( '#shipping_city' ).val(
     860                                                        shippingContact.city || ''
     861                                                    );
     862                                                    jQuery( '#shipping_state' ).val(
     863                                                        shippingContact.state || ''
     864                                                    );
     865                                                    jQuery( '#shipping_postcode' ).val(
     866                                                        shippingContact.postalCode || ''
     867                                                    );
     868                                                    jQuery( '#shipping_country' ).val(
     869                                                        shippingContact.countryCode || ''
     870                                                    );
     871                                                    jQuery( '#shipping_phone' ).val(
     872                                                        shippingContact.phone || ''
     873                                                    );
     874                                                }
     875
     876                                                // Only update billing fields if existing billing is incomplete
     877                                                const shouldUpdateBillingAfterpay = ! isExistingBillingComplete();
     878
     879                                                if ( shouldUpdateBillingAfterpay ) {
     880                                                    // Update billing fields
     881                                                    jQuery( '#billing_country' )
     882                                                        .val( billingContact.countryCode || '' )
     883                                                        .trigger( 'change' );
     884                                                }
     885
     886                                                // Give WooCommerce time to repopulate state dropdown
     887                                                setTimeout( function () {
     888                                                    if ( shouldUpdateBillingAfterpay ) {
     889                                                        jQuery( '#billing_state' )
     890                                                            .val( billingContact.state || '' )
     891                                                            .trigger( 'change' );
     892
     893                                                        jQuery( '#billing_first_name' ).val(
     894                                                            billingContact.givenName || ''
     895                                                        );
     896                                                        jQuery( '#billing_last_name' ).val(
     897                                                            billingContact.familyName || ''
     898                                                        );
     899                                                        jQuery( '#billing_company' ).val( '' );
     900                                                        jQuery( '#billing_address_1' ).val(
     901                                                            billingContact.addressLines[ 0 ] || ''
     902                                                        );
     903                                                        jQuery( '#billing_address_2' ).val(
     904                                                            billingContact.addressLines[ 1 ] || ''
     905                                                        );
     906                                                        jQuery( '#billing_city' ).val( billingContact.city || '' );
     907                                                        jQuery( '#billing_postcode' ).val(
     908                                                            billingContact.postalCode || ''
     909                                                        );
     910                                                        jQuery( '#billing_phone' ).val(
     911                                                            billingContact.phone || ''
     912                                                        );
     913                                                        jQuery( '#billing_email' ).val(
     914                                                            billingContact.email || ''
     915                                                        );
     916                                                    }
     917
     918                                                    // Submit the checkout form
     919                                                    // Handle both checkout and pay-for-order forms
     920                                                    const $form = jQuery( 'form.checkout, form#order_review' );
     921                                                    $form.trigger( 'submit' );
     922                                                }, 100 );
     923                                            } else if (tokenResult.status === 'CANCEL') {
     924                                                // User cancelled, don't show error
     925                                            } else {
     926                                                clearStoredTokens();
     927                                                const errorMessage = tokenResult.errors
     928                                                    ? tokenResult.errors.map(e => e.message || e).join(', ')
     929                                                    : 'Unknown error';
     930                                                logPaymentError(`Afterpay payment failed: ${errorMessage}`);
     931                                            }
     932                                        } catch (error) {
     933                                            clearStoredTokens();
     934                                            logPaymentError(`Afterpay error: ${error.message || 'Unknown error'}`);
     935                                        } finally {
     936                                            // Remove processing class
     937                                            jQuery(afterpayButtonContainer).removeClass('processing');
     938                                        }
     939                                    });
     940                                }
     941                            }
     942                            afterPayButtonContainer.classList.add('wallet-active');
     943                            afterPayButtonContainer.style.display = 'block'; // Override inline
     944                            activeWallets++;
     945                        }
     946                    } catch (initError) {
     947                        if (!initError.message || !initError.message.includes('not available')) {
     948                            console.error('Afterpay initialization error:', initError);
     949                        }
     950                        walletInstances.afterPay = null;
     951                    }
     952                } else if (afterPayButtonExists) {
     953                    // Button already exists, just mark as active
     954                    afterPayButtonContainer.classList.add('wallet-active');
     955                    afterPayButtonContainer.style.display = 'block';
     956                    activeWallets++;
     957                }
     958            }
     959        } catch ( error ) {
     960            console.error( 'Afterpay outer error:', error );
     961            walletInstances.afterPay = null;
     962            // Remove active class from the Afterpay button
     963            const afterPayButton = document.querySelector('#sws-afterpay-legacy');
     964            if (afterPayButton) {
     965                afterPayButton.classList.remove('wallet-active');
     966            }
     967        }
     968    }
     969
     970    // Cash App Pay Initialization
     971    if ( SquareConfig.cashAppPayEnabled === 'yes' ) {
     972        try {
     973            const cashAppPayButtonContainer =
     974                document.querySelector( '#sws-cashapp-legacy' );
     975
     976            if ( cashAppPayButtonContainer ) {
     977                // Remove active class initially
     978                cashAppPayButtonContainer.classList.remove('wallet-active');
     979
     980                // Check if button already exists
     981                const cashAppPayButtonExists = cashAppPayButtonContainer.querySelector( '[data-cashapp-button]' );
     982
     983                if ( ! cashAppPayButtonExists ) {
     984                    try {
     985                        // Reuse existing instance if available
     986                        if (!walletInstances.cashAppPay) {
     987                            // Cash App Pay requires redirectURL for mobile flow
     988                            const redirectURL = window.location.href;
     989                            const referenceId = `order-${Date.now()}`;
     990
     991                            walletInstances.cashAppPay = await payments.cashAppPay(
     992                                paymentRequest,
     993                                {
     994                                    redirectURL,
     995                                    referenceId,
     996                                }
     997                            );
     998                        }
     999
     1000                        if (walletInstances.cashAppPay) {
     1001                            // Attach the Cash App Pay button with styling options
     1002                            await walletInstances.cashAppPay.attach( '#sws-cashapp-legacy', {
     1003                                shape: 'semiround',
     1004                                width: 'static',
     1005                                size: 'medium',
     1006                                theme: 'dark',
     1007                            } );
     1008
     1009                            // Add tokenization event listener for Cash App Pay
     1010                            walletInstances.cashAppPay.addEventListener('ontokenization', async function(event) {
     1011                                const { tokenResult, error } = event.detail;
     1012
     1013                                if (error) {
     1014                                    console.error('Cash App Pay tokenization error:', error);
     1015                                    clearStoredTokens();
     1016                                    logPaymentError(`Cash App Pay error: ${error.message || 'Unknown error'}`);
     1017                                    return;
     1018                                }
     1019
     1020                                if (tokenResult && tokenResult.status === 'OK') {
     1021                                    // Process the token result using existing handler
     1022                                    await handleTokenizationAndVerification(
     1023                                        walletInstances.cashAppPay,
     1024                                        'Cash App Pay'
     1025                                    );
     1026                                } else if (tokenResult && tokenResult.status !== 'Cancel') {
     1027                                    clearStoredTokens();
     1028                                    const errorMessage = tokenResult.errors
     1029                                        ? tokenResult.errors.map(e => e.message || e).join(', ')
     1030                                        : 'Unknown error';
     1031                                    logPaymentError(`Cash App Pay payment failed: ${errorMessage}`);
     1032                                }
     1033                            });
     1034
     1035                            cashAppPayButtonContainer.classList.add('wallet-active');
     1036                            cashAppPayButtonContainer.style.display = 'block';
     1037                            activeWallets++;
     1038                        }
     1039                    } catch (initError) {
     1040                        if (!initError.message || (!initError.message.includes('not supported') && !initError.message.includes('not available'))) {
     1041                            console.error('Cash App Pay initialization error:', initError);
     1042                        }
     1043                        walletInstances.cashAppPay = null;
     1044                    }
     1045                } else if (cashAppPayButtonExists) {
     1046                    // Button already exists, just mark as active
     1047                    cashAppPayButtonContainer.classList.add('wallet-active');
     1048                    cashAppPayButtonContainer.style.display = 'block';
     1049                    activeWallets++;
     1050                }
     1051            }
     1052        } catch ( error ) {
     1053            console.error( 'Cash App Pay outer error:', error );
     1054            walletInstances.cashAppPay = null;
     1055            // Remove active class from the Cash App Pay button
     1056            const cashAppPayButton = document.querySelector('#sws-cashapp-legacy');
     1057            if (cashAppPayButton) {
     1058                cashAppPayButton.classList.remove('wallet-active');
     1059            }
     1060        }
     1061    }
     1062
     1063    // Show the wallet container only if at least one wallet was successfully initialized
     1064    if (activeWallets > 0) {
     1065        walletContainers.forEach(container => {
     1066            container.classList.add('has-wallets');
     1067            container.style.display = 'block'; // Override the initial hidden state
     1068        });
     1069    } else {
     1070        // Ensure containers stay hidden
     1071        walletContainers.forEach(container => {
     1072            container.style.display = 'none';
     1073        });
     1074    }
    1291075}
    1301076
    131 /**********************************************************/
    132 /** 2) Helper: isBillingComplete                         **/
    133 /**********************************************************/
    134 function isBillingComplete(billingContact) {
    135   // Define whatever fields you consider "required"
    136   // Adjust as needed for your store’s requirements
    137   return (
    138     billingContact &&
    139     billingContact.givenName &&
    140     billingContact.familyName &&
    141     billingContact.addressLines &&
    142     billingContact.addressLines.length > 0 &&
    143     billingContact.city &&
    144     billingContact.state &&
    145     billingContact.postalCode &&
    146     billingContact.countryCode
    147   );
     1077function updateWooCommerceShippingFields( shipping ) {
     1078    // Bail out if shipping or addressLines is missing
     1079    if (
     1080        ! shipping ||
     1081        ! Array.isArray( shipping.addressLines ) ||
     1082        shipping.addressLines.length === 0
     1083    ) {
     1084        return;
     1085    }
     1086
     1087    jQuery( '#shipping_first_name' ).val( shipping.givenName );
     1088    jQuery( '#shipping_last_name' ).val( shipping.familyName );
     1089    jQuery( '#shipping_address_1' ).val( shipping.addressLines[ 0 ] );
     1090    jQuery( '#shipping_city' ).val( shipping.city );
     1091    jQuery( '#shipping_postcode' ).val( shipping.postalCode );
     1092    jQuery( '#shipping_state' ).val( shipping.state );
     1093    jQuery( '#shipping_country' ).val( shipping.countryCode );
     1094    jQuery( '#shipping_phone' ).val( shipping.phone );
    1481095}
    1491096
    150 async function attachWalletButtons(
    151   paymentRequest,
    152   payments,
    153   needsShipping,
    154   couponApplied
    155 ) {
    156   // Common function to handle wallet tokenization and verification
    157   /**********************************************************/
    158   /** 1) Helper: transformContact                          **/
    159   /**********************************************************/
    160   function transformContact(contact, isAfterpay, fallback = {}) {
    161     // If there's no contact at all, we immediately fallback.
    162     if (!contact || typeof contact !== "object") {
    163       contact = {};
    164     }
    165 
    166     const {
    167       familyName,
    168       givenName,
    169       region, // Afterpay uses `region`
    170       state, // Apple/Google Pay uses `state`
    171       country, // Afterpay uses `country`
    172       countryCode, // Apple/Google uses `countryCode`
    173       city,
    174       addressLines,
    175       postalCode,
    176       phone,
    177       email,
    178     } = contact;
    179 
    180     const {
    181       first_name: fallbackGivenName = "",
    182       last_name: fallbackFamilyName = "",
    183       address_1: fallbackAddress1 = "",
    184       address_2: fallbackAddress2 = "",
    185       city: fallbackCity = "",
    186       state: fallbackState = "",
    187       country: fallbackCountry = "",
    188       postcode: fallbackPostcode = "",
    189       phone: fallbackPhone = "",
    190       email: fallbackEmail = "",
    191     } = fallback;
    192 
    193     const mergedGivenName = givenName ?? fallbackGivenName;
    194     const mergedFamilyName = familyName ?? fallbackFamilyName;
    195     const mergedCity = city ?? fallbackCity;
    196     const mergedPostalCode = postalCode ?? fallbackPostcode;
    197     const mergedEmail = email ?? fallbackEmail;
    198     const mergedPhone = phone ?? fallbackPhone;
    199 
    200     // For region/state
    201     const mergedState = isAfterpay
    202       ? region ?? fallbackState
    203       : state ?? region ?? fallbackState;
    204 
    205     // For country / countryCode
    206     const mergedCountry = isAfterpay
    207       ? country ?? fallbackCountry
    208       : countryCode ?? country ?? fallbackCountry;
    209 
    210     // For address lines
    211     let mergedAddressLines = [];
    212     if (Array.isArray(addressLines) && addressLines.length > 0) {
    213       mergedAddressLines = addressLines;
    214     } else {
    215       // Merge fallback address_1 and address_2 if present
    216       mergedAddressLines = [fallbackAddress1, fallbackAddress2].filter(Boolean);
    217     }
    218 
    219     return {
    220       givenName: mergedGivenName,
    221       familyName: mergedFamilyName,
    222       state: mergedState,
    223       countryCode: mergedCountry,
    224       city: mergedCity,
    225       addressLines: mergedAddressLines,
    226       postalCode: mergedPostalCode,
    227       phone: mergedPhone,
    228       email: mergedEmail,
    229     };
    230   }
    231 
    232   /**********************************************************/
    233   /** 2) Helper: isBillingComplete                         **/
    234   /**********************************************************/
    235   function isBillingComplete(billingContact) {
    236     // Define whatever fields you consider "required"
    237     // Adjust as needed for your store’s requirements
    238     return (
    239       billingContact &&
    240       billingContact.givenName &&
    241       billingContact.familyName &&
    242       billingContact.addressLines &&
    243       billingContact.addressLines.length > 0 &&
    244       billingContact.city &&
    245       billingContact.state &&
    246       billingContact.postalCode &&
    247       billingContact.countryCode
    248     );
    249   }
    250 
    251   /**********************************************************/
    252   /** 3) handleTokenizationAndVerification (UPDATED)       **/
    253   /**********************************************************/
    254   async function handleTokenizationAndVerification(walletInstance, walletType) {
    255     try {
    256       const tokenResult = await walletInstance.tokenize();
    257 
    258       if (tokenResult.status === "OK") {
    259         // Attach raw nonce/token to a hidden field
    260         attachTokenToForm(tokenResult.token);
    261 
    262         // We assume `walletType === "AfterpayClearpay"` for Afterpay logic
    263         const isAfterpay = walletType === "AfterpayClearpay";
    264 
    265         // Ensure "Ship to a different address" is checked if we have shipping details
    266         const shipToDifferentAddressCheckbox = jQuery(
    267           "#ship-to-different-address-checkbox"
    268         );
    269         if (!shipToDifferentAddressCheckbox.is(":checked")) {
    270           shipToDifferentAddressCheckbox.prop("checked", true);
    271           jQuery("div.shipping_address").show(); // Make sure shipping fields are visible
    272         }
    273 
    274         /*******************************************************/
    275         /** 3a) Extract shipping & billing from tokenResult   **/
    276         /*******************************************************/
    277         const shippingDetails = tokenResult?.details?.shipping?.contact || {};
    278         const billingDetails = tokenResult?.details?.billing || {};
    279 
    280         // In case your legacy checkout still needs to fallback to
    281         // current form values if the contact is missing data:
    282         const fallbackShipping = {
    283           first_name: jQuery("#shipping_first_name").val(),
    284           last_name: jQuery("#shipping_last_name").val(),
    285           address_1: jQuery("#shipping_address_1").val(),
    286           address_2: jQuery("#shipping_address_2").val(),
    287           city: jQuery("#shipping_city").val(),
    288           state: jQuery("#shipping_state").val(),
    289           postcode: jQuery("#shipping_postcode").val(),
    290           country: jQuery("#shipping_country").val(),
    291           phone: jQuery("#shipping_phone").val(),
    292           email: jQuery("#billing_email").val(), // Sometimes shipping doesn't have its own email
    293         };
    294         const fallbackBilling = {
    295           first_name: jQuery("#billing_first_name").val(),
    296           last_name: jQuery("#billing_last_name").val(),
    297           address_1: jQuery("#billing_address_1").val(),
    298           address_2: jQuery("#billing_address_2").val(),
    299           city: jQuery("#billing_city").val(),
    300           state: jQuery("#billing_state").val(),
    301           postcode: jQuery("#billing_postcode").val(),
    302           country: jQuery("#billing_country").val(),
    303           phone: jQuery("#billing_phone").val(),
    304           email: jQuery("#billing_email").val(),
    305         };
    306 
    307         // Transform shipping contact
    308         const shippingContact = transformContact(
    309           shippingDetails,
    310           isAfterpay,
    311           fallbackShipping
    312         );
    313 
    314         // Transform billing contact
    315         let billingContact = transformContact(
    316           billingDetails,
    317           isAfterpay,
    318           fallbackBilling
    319         );
    320 
    321         // If billing is incomplete, fallback to shipping
    322         if (!isBillingComplete(billingContact)) {
    323           const shippingAsBilling = transformContact(
    324             shippingDetails,
    325             isAfterpay,
    326             fallbackShipping
    327           );
    328           // Preserve billingContact.email if it exists, otherwise use shipping email
    329           billingContact = {
    330             ...shippingAsBilling,
    331             email:
    332               billingContact.email ||
    333               shippingAsBilling.email ||
    334               shippingDetails.email,
    335           };
    336         }
    337 
    338 
    339         // Shipping:
    340         // Only update shipping if your store "needs shipping"
    341         if (typeof needsShipping !== "undefined" && needsShipping) {
    342           jQuery("#shipping_first_name").val(shippingContact.givenName || "");
    343           jQuery("#shipping_last_name").val(shippingContact.familyName || "");
    344           jQuery("#shipping_company").val("");
    345           jQuery("#shipping_address_1").val(
    346             shippingContact.addressLines[0] || ""
    347           );
    348           jQuery("#shipping_address_2").val(
    349             shippingContact.addressLines[1] || ""
    350           );
    351           jQuery("#shipping_city").val(shippingContact.city || "");
    352           jQuery("#shipping_state").val(shippingContact.state || "");
    353           jQuery("#shipping_postcode").val(shippingContact.postalCode || "");
    354           jQuery("#shipping_country").val(shippingContact.countryCode || "");
    355           jQuery("#shipping_phone").val(shippingContact.phone || "");
    356         }
    357 
    358         /*********************************************************/
    359         /** 3b) Update Legacy Billing & Shipping form fields    **/
    360         /*********************************************************/
    361         // — now country/state —
    362         jQuery("#billing_country")
    363           .val(billingContact.countryCode || "")
    364           .trigger("change");  // ⬅️ rebuild states
    365 
    366 
    367 
    368 
    369         // give WooCommerce a moment to repopulate the state <select>
    370         setTimeout(function () {
    371           jQuery("#billing_state")
    372             .val(billingContact.state || "")
    373             .trigger("change");
    374 
    375           // Billing:
    376           jQuery("#billing_first_name").val(billingContact.givenName || "");
    377           jQuery("#billing_last_name").val(billingContact.familyName || "");
    378           jQuery("#billing_company").val(""); // no company in token result
    379           jQuery("#billing_address_1").val(billingContact.addressLines[0] || "");
    380           jQuery("#billing_address_2").val(billingContact.addressLines[1] || "");
    381           // … your other field‐fills …
    382           jQuery("#billing_city").val(billingContact.city || "");
    383           jQuery("#billing_postcode").val(billingContact.postalCode || "");
    384 
    385           // … then the rest …
    386           jQuery("#billing_phone").val(billingContact.phone || "");
    387           jQuery("#billing_email").val(billingContact.email || "");
    388 
    389           jQuery("form.checkout").trigger("submit");
    390         }, 100);
    391 
    392 
    393       } else {
    394         // Clear stored tokens or error-handling
    395         clearStoredTokens();
    396         if (tokenResult.status !== "Cancel") {
    397           logPaymentError(
    398             `${walletType} tokenization failed: ${JSON.stringify(
    399               tokenResult.errors
    400             )}`
    401           );
    402         }
    403       }
    404     } catch (error) {
    405       clearStoredTokens();
    406       logPaymentError(
    407         `${walletType} tokenization or verification error: ${error.message}`
    408       );
    409     }
    410   }
    411 
    412   // Apple Pay Initialization or Update
    413   if (SquareConfig.applePayEnabled === "yes") {
    414     try {
    415       const applePayButtonContainer =
    416         document.querySelector("#apple-pay-button");
    417       if (applePayButtonContainer) {
    418         applePayButtonContainer.style.display = "block";
    419 
    420         const removedShippingOptions = paymentRequest;
    421         removedShippingOptions["_shippingOptions"] = [];
    422 
    423         const applePayInstance = await payments.applePay(
    424           removedShippingOptions
    425         );
    426 
    427 
    428         jQuery("#apple-pay-button")
    429           .off("click")
    430           .on("click", async function (e) {
    431             e.preventDefault();
    432             await handleTokenizationAndVerification(
    433               applePayInstance,
    434               "Apple Pay"
    435             );
    436           });
    437       }
    438     } catch (error) {
    439       console.error("Failed to initialize Apple Pay:", error);
    440     }
    441   }
    442 
    443   // Google Pay Initialization or Update
    444   if (SquareConfig.googlePayEnabled === "yes") {
    445     try {
    446       const googlePayButtonContainer =
    447         document.querySelector("#google-pay-button");
    448 
    449       // Check if the Google Pay button is already present by checking the element 'gpay-button-online-api-id'
    450       const googlePayButtonExists = document.querySelector(
    451         "#gpay-button-online-api-id"
    452       );
    453 
    454       if (googlePayButtonContainer && !googlePayButtonExists) {
    455         const removedShippingOptions = paymentRequest;
    456         removedShippingOptions["_shippingOptions"] = [];
    457 
    458         // Initialize the Google Pay instance
    459         const googlePayInstance = await payments.googlePay(
    460           removedShippingOptions
    461         );
    462         // Remove any existing click handler before attaching the new one
    463         jQuery("#google-pay-button")
    464           .off("click")
    465           .on("click", async function (e) {
    466             e.preventDefault();
    467             await handleTokenizationAndVerification(
    468               googlePayInstance,
    469               "Google Pay"
    470             );
    471           });
    472 
    473         // Attach the Google Pay button
    474         await googlePayInstance.attach("#google-pay-button");
    475         googlePayButtonContainer.style.display = "block"; // Ensure the button is visible
    476       }
    477     } catch (error) {
    478       console.error("Failed to initialize Google Pay:", error);
    479     }
    480   }
    481 
    482   if (SquareConfig.afterPayEnabled === "yes") {
    483     try {
    484       const afterPayButtonContainer =
    485         document.querySelector("#afterpay-button");
    486       // Check for an existing Afterpay button *inside* the container
    487       const afterPayButtonExists = afterPayButtonContainer
    488         ? afterPayButtonContainer.querySelector(".sq-ap__button")
    489         : null;
    490 
    491       if (afterPayButtonContainer && !afterPayButtonExists) {
    492         const afterPayInstance =
    493           await payments.afterpayClearpay(paymentRequest);
    494 
    495         jQuery("#afterpay-button")
    496           .off("click")
    497           .on("click", async function (e) {
    498             e.preventDefault();
    499             await handleTokenizationAndVerification(
    500               afterPayInstance,
    501               "Afterpay"
    502             );
    503           });
    504 
    505         await afterPayInstance.attach("#afterpay-button");
    506 
    507         // Set a minimum width to prevent it from being cut off
    508         afterPayButtonContainer.style.minWidth = "240px";
    509 
    510         paymentRequest?.addEventListener(
    511           "afterpay_shippingaddresschanged",
    512           (shippingContact) => handleShippingAddressChanged(shippingContact)
    513         );
    514         paymentRequest?.addEventListener(
    515           "afterpay_shippingoptionchanged",
    516           (option) => handleShippingOptionChanged(option)
    517         );
    518       }
    519     } catch (error) {
    520       console.error("Failed to initialize Afterpay:", error);
    521     }
    522   }
    523 }
    524 
    525 function updateWooCommerceShippingFields(shipping) {
    526   // Bail out if shipping or addressLines is missing
    527   if (
    528     !shipping ||
    529     !Array.isArray(shipping.addressLines) ||
    530     shipping.addressLines.length === 0
    531   ) {
    532     return;
    533   }
    534 
    535   jQuery("#shipping_first_name").val(shipping.givenName);
    536   jQuery("#shipping_last_name").val(shipping.familyName);
    537   jQuery("#shipping_address_1").val(shipping.addressLines[0]);
    538   jQuery("#shipping_city").val(shipping.city);
    539   jQuery("#shipping_postcode").val(shipping.postalCode);
    540   jQuery("#shipping_state").val(shipping.state);
    541   jQuery("#shipping_country").val(shipping.countryCode);
    542   jQuery("#shipping_phone").val(shipping.phone);
    543 }
     1097// Cleanup on page unload
     1098jQuery( window ).on( 'beforeunload', function() {
     1099    cleanupWalletInstances();
     1100});
  • squarewoosync/trunk/assets/styles/checkout.css

    r3310892 r3431463  
    1 .wallets-container {
    2   display: flex;
    3   gap: 2rem;
     1/* SWS wallet container - hidden by default, shown only when wallets are available */
     2.sws-legacy-wallets {
     3  display: none;
     4  margin-bottom: 1rem;
    45}
    56
    6 #apple-pay-button {
     7/* Show container when it has active wallet buttons */
     8.sws-legacy-wallets.has-wallets {
     9  display: block;
     10}
     11
     12/* Individual wallet button containers */
     13.sws-legacy-wallets > div {
     14  display: none;
    715  height: 40px;
    8   width: 100%;
    9   display: inline-block;
     16  margin: 0 0 1em 0;
     17}
     18
     19/* Show only wallet buttons that are successfully initialized */
     20.sws-legacy-wallets > div.wallet-active {
     21  display: block;
     22}
     23
     24#sws-applepay-legacy {
     25  height: 40px;
     26  display: none;
    1027  -webkit-appearance: -apple-pay-button;
    1128  -apple-pay-button-type: plain;
    1229  -apple-pay-button-style: black;
    1330}
     31
     32#sws-applepay-legacy.wallet-active {
     33  display: inline-block;
     34}
     35
     36#sws-gpay-legacy {
     37  display: none;
     38}
     39
     40#sws-gpay-legacy.wallet-active {
     41  display: block;
     42}
     43
     44#sws-afterpay-legacy {
     45  display: none;
     46}
     47
     48#sws-afterpay-legacy.wallet-active {
     49  display: block;
     50}
     51
     52#sws-cashapp-legacy {
     53  display: none;
     54}
     55
     56#sws-cashapp-legacy.wallet-active {
     57  display: block;
     58}
     59
    1460.sq-card-iframe-container {
    1561  height: auto !important;
    1662}
    17 .sq-card-iframe-container iframe {
     63
     64/* Ensure proper spacing only when wallet buttons are visible */
     65.sws-legacy-wallets:empty,
     66.sws-legacy-wallets:not(.has-wallets) {
     67  display: none !important;
     68  margin: 0 !important;
    1869}
    19 
    20 #afterpay-button {
    21   min-width: 220px;
    22 }
  • squarewoosync/trunk/build/assets/frontend/wallet.asset.php

    r3198659 r3431463  
    1 <?php return array('dependencies' => array(), 'version' => 'dab66e314ae019192b81');
     1<?php return array('dependencies' => array(), 'version' => '6d39672cd9ae5718a30a');
  • squarewoosync/trunk/build/assets/frontend/wallet.css

    r3198659 r3431463  
    1 @supports(-webkit-appearance: -apple-pay-button){.apple-pay-button{-webkit-appearance:-apple-pay-button;cursor:pointer}.apple-pay-button>*{display:none}}@supports not (-webkit-appearance: -apple-pay-button){.apple-pay-button{background-size:100% 60%;background-repeat:no-repeat;background-position:50% 50%;border-radius:5px;padding:0px;box-sizing:border-box;min-width:200px;min-height:32px;max-height:64px;cursor:pointer}.apple-pay-button.wc-square-wallet-button-with-text{--apple-pay-scale: 1;justify-content:center;font-size:12px;background:none}.apple-pay-button.wc-square-wallet-button-with-text .text{font-family:-apple-system;font-size:calc(1em*var(--apple-pay-scale));font-weight:300;align-self:center;margin-right:calc(2px*var(--apple-pay-scale))}.apple-pay-button.wc-square-wallet-button-with-text .logo{width:calc(35px*var(--scale));height:100%;background-size:100% 60%;background-repeat:no-repeat;background-position:0 50%;margin-left:calc(2px*var(--apple-pay-scale));border:none}.apple-pay-button.wc-square-wallet-button-black{background-color:#000;color:#fff}.apple-pay-button.wc-square-wallet-button-black .logo{background-image:-webkit-named-image(apple-pay-logo-white);background-color:#000}.apple-pay-button.wc-square-wallet-button-white{background-color:#fff;color:#000}.apple-pay-button.wc-square-wallet-button-white .logo{background-image:-webkit-named-image(apple-pay-logo-black);background-color:#fff}.apple-pay-button.wc-square-wallet-button-white-outline{background-color:#fff;color:#000;border:.5px solid #000}.apple-pay-button.wc-square-wallet-button-white-outline .logo{background-image:-webkit-named-image(apple-pay-logo-black);background-color:#fff}}
     1.sws-wallets-container{display:none}.sws-wallets-container.has-wallets{display:block}.sws-wallets-container:empty{display:none !important}.sws-wallet-btn{height:40px;margin:0 0 1em 0;cursor:pointer}.sws-gpay-btn{height:40px;margin:0 0 1em 0}.sws-afterpay-btn{height:40px;margin:0 0 1em 0}.sws-cashapp-btn{height:40px;margin:0 0 1em 0}@supports(-webkit-appearance: -apple-pay-button){.sws-applepay-btn{-webkit-appearance:-apple-pay-button;cursor:pointer}.sws-applepay-btn>*{display:none}}@supports not (-webkit-appearance: -apple-pay-button){.sws-applepay-btn{background-size:100% 60%;background-repeat:no-repeat;background-position:50% 50%;border-radius:5px;padding:0px;box-sizing:border-box;min-width:200px;min-height:32px;max-height:64px;cursor:pointer}.sws-applepay-btn.sws-wallet-btn-text{--apple-pay-scale: 1;justify-content:center;font-size:12px;background:none}.sws-applepay-btn.sws-wallet-btn-text .text{font-family:-apple-system;font-size:calc(1em*var(--apple-pay-scale));font-weight:300;align-self:center;margin-right:calc(2px*var(--apple-pay-scale))}.sws-applepay-btn.sws-wallet-btn-text .logo{width:calc(35px*var(--scale));height:100%;background-size:100% 60%;background-repeat:no-repeat;background-position:0 50%;margin-left:calc(2px*var(--apple-pay-scale));border:none}.sws-applepay-btn.sws-wallet-btn-black{background-color:#000;color:#fff}.sws-applepay-btn.sws-wallet-btn-black .logo{background-image:-webkit-named-image(apple-pay-logo-white);background-color:#000}.sws-applepay-btn.sws-wallet-btn-white{background-color:#fff;color:#000}.sws-applepay-btn.sws-wallet-btn-white .logo{background-image:-webkit-named-image(apple-pay-logo-black);background-color:#fff}.sws-applepay-btn.sws-wallet-btn-white-outline{background-color:#fff;color:#000;border:.5px solid #000}.sws-applepay-btn.sws-wallet-btn-white-outline .logo{background-image:-webkit-named-image(apple-pay-logo-black);background-color:#fff}}
  • squarewoosync/trunk/build/blocks/gateway.asset.php

    r3360355 r3431463  
    1 <?php return array('dependencies' => array('wp-data', 'wp-element'), 'version' => 'a831b59204cd92f08125');
     1<?php return array('dependencies' => array('wp-data', 'wp-element'), 'version' => 'fa70ea82be053456f9a0');
  • squarewoosync/trunk/build/blocks/gateway.js

    r3360355 r3431463  
    1 (()=>{"use strict";const t=window.wp.element;var e=window.wc.wcSettings.getSetting,r=function(){var t=e("squaresync_credit_data",null);if(!t)throw new Error("Square initialization data is not available");return{title:t.title||"",applicationId:t.applicationId||"",locationId:t.locationId||"",isSandbox:t.is_sandbox||!1,availableCardTypes:t.accepted_credit_cards||{},loggingEnabled:t.logging_enabled||!1,generalError:t.general_error||"",showSavedCards:t.show_saved_cards||!1,showSaveOption:t.show_save_option||!1,supports:t.supports||{},isTokenizationForced:t.is_tokenization_forced||!1,paymentTokenNonce:t.payment_token_nonce||"",isDigitalWalletsEnabled:"yes"===t.enable_apple_pay||"yes"===t.enable_google_pay||"yes"===t.enable_after_pay||!1,googlePay:t.enable_google_pay||"no",applePay:t.enable_apple_pay||"no",afterPay:t.enable_after_pay||"no",isPayForOrderPage:t.is_pay_for_order_page||!1,recalculateTotalNonce:t.recalculate_totals_nonce||!1,context:t.context||"",ajaxUrl:t.ajax_url||"",paymentRequestNonce:t.payment_request_nonce||"",googlePayColor:t.google_pay_color||"black",applePayColor:t.apple_pay_color||"black",applePayType:t.apple_pay_type||"buy",hideButtonOptions:t.hide_button_options||[],hasSubscription:t.hasSubscription||!1}};function n(t){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},n(t)}function o(){o=function(){return e};var t,e={},r=Object.prototype,i=r.hasOwnProperty,a=Object.defineProperty||function(t,e,r){t[e]=r.value},c="function"==typeof Symbol?Symbol:{},u=c.iterator||"@@iterator",l=c.asyncIterator||"@@asyncIterator",s=c.toStringTag||"@@toStringTag";function f(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{f({},"")}catch(t){f=function(t,e,r){return t[e]=r}}function h(t,e,r,n){var o=e&&e.prototype instanceof w?e:w,i=Object.create(o.prototype),c=new N(n||[]);return a(i,"_invoke",{value:O(t,r,c)}),i}function p(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=h;var y="suspendedStart",v="suspendedYield",d="executing",m="completed",g={};function w(){}function b(){}function x(){}var E={};f(E,u,(function(){return this}));var L=Object.getPrototypeOf,_=L&&L(L(I([])));_&&_!==r&&i.call(_,u)&&(E=_);var S=x.prototype=w.prototype=Object.create(E);function C(t){["next","throw","return"].forEach((function(e){f(t,e,(function(t){return this._invoke(e,t)}))}))}function k(t,e){function r(o,a,c,u){var l=p(t[o],t,a);if("throw"!==l.type){var s=l.arg,f=s.value;return f&&"object"==n(f)&&i.call(f,"__await")?e.resolve(f.__await).then((function(t){r("next",t,c,u)}),(function(t){r("throw",t,c,u)})):e.resolve(f).then((function(t){s.value=t,c(s)}),(function(t){return r("throw",t,c,u)}))}u(l.arg)}var o;a(this,"_invoke",{value:function(t,n){function i(){return new e((function(e,o){r(t,n,e,o)}))}return o=o?o.then(i,i):i()}})}function O(e,r,n){var o=y;return function(i,a){if(o===d)throw Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=j(c,n);if(u){if(u===g)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===y)throw o=m,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=d;var l=p(e,r,n);if("normal"===l.type){if(o=n.done?m:v,l.arg===g)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=m,n.method="throw",n.arg=l.arg)}}}function j(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,j(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=p(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function P(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function T(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function N(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(P,this),this.reset(!0)}function I(e){if(e||""===e){var r=e[u];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,a=function r(){for(;++o<e.length;)if(i.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return a.next=a}}throw new TypeError(n(e)+" is not iterable")}return b.prototype=x,a(S,"constructor",{value:x,configurable:!0}),a(x,"constructor",{value:b,configurable:!0}),b.displayName=f(x,s,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===b||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,x):(t.__proto__=x,f(t,s,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},C(k.prototype),f(k.prototype,l,(function(){return this})),e.AsyncIterator=k,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new k(h(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},C(S),f(S,s,"Generator"),f(S,u,(function(){return this})),f(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=I,N.prototype={constructor:N,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(T),!e)for(var r in this)"t"===r.charAt(0)&&i.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function n(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var o=this.tryEntries.length-1;o>=0;--o){var a=this.tryEntries[o],c=a.completion;if("root"===a.tryLoc)return n("end");if(a.tryLoc<=this.prev){var u=i.call(a,"catchLoc"),l=i.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return n(a.catchLoc,!0);if(this.prev<a.finallyLoc)return n(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return n(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return n(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&i.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var o=n;break}}o&&("break"===t||"continue"===t)&&o.tryLoc<=e&&e<=o.finallyLoc&&(o=null);var a=o?o.completion:{};return a.type=t,a.arg=e,o?(this.method="next",this.next=o.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),T(r),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;T(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:I(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),g}},e}function i(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,n)}return r}function a(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?i(Object(r),!0).forEach((function(e){c(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):i(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}function c(t,e,r){return(e=function(t){var e=function(t,e){if("object"!=n(t)||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var o=r.call(t,"string");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==n(e)?e:e+""}(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function u(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}var l=(0,t.createContext)(!1),s=function(e){var n=e.checkoutFormHandler,i=e.eventRegistration,c=e.emitResponse,s=(0,t.useContext)(l),f=i.onPaymentSetup,h=i.onCheckoutAfterProcessingWithError,p=i.onCheckoutAfterProcessingWithSuccess;return function(e,n,i,c,l,s){var f=(0,t.useRef)(i);(0,t.useEffect)((function(){f.current=i}),[i]),(0,t.useEffect)((function(){var t=function(){var t,e=(t=o().mark((function t(){var e,i,u,h,p,y,v,d,m,g,w,b,x,E;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(i={type:n.responseTypes.SUCCESS},u={nonce:"",notices:[],logs:[]},null===(e=f.current)||void 0===e||!e.token){t.next=20;break}return t.prev=3,h=r(),p=h.paymentTokenNonce,t.next=7,fetch("".concat(wc.wcSettings.ADMIN_URL,"admin-ajax.php?action=squaresync_credit_card_get_token_by_id&token_id=").concat(f.current.token,"&nonce=").concat(p));case 7:return y=t.sent,t.next=10,y.json();case 10:v=t.sent,d=v.success,m=v.data,u.token=d?m:"",t.next=18;break;case 16:t.prev=16,t.t0=t.catch(3);case 18:t.next=31;break;case 20:return t.prev=20,t.next=23,l(f.current.card);case 23:b=t.sent,u.nonce=b.token,null!=b&&null!==(g=b.details)&&void 0!==g&&g.card&&null!=b&&null!==(w=b.details)&&void 0!==w&&w.billing&&(u.cardData=a(a({},b.details.card),b.details.billing)),t.next=31;break;case 28:t.prev=28,t.t1=t.catch(20),console.error("Error creating nonce:",t.t1);case 31:if(!(x=u.token||u.nonce)){t.next=45;break}return t.prev=33,t.next=36,s(f.current.payments,x);case 36:E=t.sent,u.verificationToken=E.verificationToken||"",u.logs=u.logs.concat(E.log||[]),u.errors=u.notices.concat(E.errors||[]),t.next=45;break;case 42:t.prev=42,t.t2=t.catch(33),console.error("Error during buyer verification:",t.t2);case 45:return x||u.logs.length>0?i.meta={paymentMethodData:c(u)}:u.notices.length>0&&(console.log("Errors or notices found:",u.notices),i.type=n.responseTypes.ERROR,i.message=u.notices),t.abrupt("return",i);case 47:case"end":return t.stop()}}),t,null,[[3,16],[20,28],[33,42]])})),function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){u(i,n,o,a,c,"next",t)}function c(t){u(i,n,o,a,c,"throw",t)}a(void 0)}))});return function(){return e.apply(this,arguments)}}();return e(t)}),[e,n.responseTypes.SUCCESS,n.responseTypes.ERROR,l,s,c])}(f,c,s,n.getPaymentMethodData,n.createNonce,n.verifyBuyer),function(e,r,n){(0,t.useEffect)((function(){var t=function(t){var e={type:n.responseTypes.SUCCESS},r=t.processingResponse,o=r.paymentStatus,i=r.paymentDetails;return o===n.responseTypes.ERROR&&i.checkoutNotices&&(e={type:n.responseTypes.ERROR,message:JSON.parse(i.checkoutNotices),messageContext:n.noticeContexts.PAYMENTS,retry:!0}),e},o=e(t),i=r(t);return function(){o(),i()}}),[e,r,n.noticeContexts.PAYMENTS,n.responseTypes.ERROR,n.responseTypes.SUCCESS])}(h,p,c),null};function f(t){return f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},f(t)}function h(){h=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof w?e:w,a=Object.create(i.prototype),c=new N(n||[]);return o(a,"_invoke",{value:O(t,r,c)}),a}function p(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var y="suspendedStart",v="suspendedYield",d="executing",m="completed",g={};function w(){}function b(){}function x(){}var E={};l(E,a,(function(){return this}));var L=Object.getPrototypeOf,_=L&&L(L(I([])));_&&_!==r&&n.call(_,a)&&(E=_);var S=x.prototype=w.prototype=Object.create(E);function C(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function k(t,e){function r(o,i,a,c){var u=p(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==f(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function O(e,r,n){var o=y;return function(i,a){if(o===d)throw Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=j(c,n);if(u){if(u===g)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===y)throw o=m,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=d;var l=p(e,r,n);if("normal"===l.type){if(o=n.done?m:v,l.arg===g)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=m,n.method="throw",n.arg=l.arg)}}}function j(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,j(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=p(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function P(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function T(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function N(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(P,this),this.reset(!0)}function I(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(f(e)+" is not iterable")}return b.prototype=x,o(S,"constructor",{value:x,configurable:!0}),o(x,"constructor",{value:b,configurable:!0}),b.displayName=l(x,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===b||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,x):(t.__proto__=x,l(t,u,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},C(k.prototype),l(k.prototype,c,(function(){return this})),e.AsyncIterator=k,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new k(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},C(S),l(S,u,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=I,N.prototype={constructor:N,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(T),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),T(r),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;T(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:I(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),g}},e}function p(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function y(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){p(i,n,o,a,c,"next",t)}function c(t){p(i,n,o,a,c,"throw",t)}a(void 0)}))}}function v(t,e,r){return(e=function(t){var e=function(t,e){if("object"!=f(t)||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var n=r.call(t,"string");if("object"!=f(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==f(e)?e:e+""}(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function d(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,c=[],u=!0,l=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(c.push(n.value),c.length!==e);u=!0);}catch(t){l=!0,o=t}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return c}}(t,e)||function(t,e){if(t){if("string"==typeof t)return m(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?m(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function m(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}function g(t){return g="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},g(t)}function w(){w=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),c=new N(n||[]);return o(a,"_invoke",{value:O(t,r,c)}),a}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var h="suspendedStart",p="suspendedYield",y="executing",v="completed",d={};function m(){}function b(){}function x(){}var E={};l(E,a,(function(){return this}));var L=Object.getPrototypeOf,_=L&&L(L(I([])));_&&_!==r&&n.call(_,a)&&(E=_);var S=x.prototype=m.prototype=Object.create(E);function C(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function k(t,e){function r(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==g(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function O(e,r,n){var o=h;return function(i,a){if(o===y)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=j(c,n);if(u){if(u===d)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(e,r,n);if("normal"===l.type){if(o=n.done?v:p,l.arg===d)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=v,n.method="throw",n.arg=l.arg)}}}function j(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,j(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),d;var i=f(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,d;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,d):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,d)}function P(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function T(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function N(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(P,this),this.reset(!0)}function I(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(g(e)+" is not iterable")}return b.prototype=x,o(S,"constructor",{value:x,configurable:!0}),o(x,"constructor",{value:b,configurable:!0}),b.displayName=l(x,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===b||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,x):(t.__proto__=x,l(t,u,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},C(k.prototype),l(k.prototype,c,(function(){return this})),e.AsyncIterator=k,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new k(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},C(S),l(S,u,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=I,N.prototype={constructor:N,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(T),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,d):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),d},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),T(r),d}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;T(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:I(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),d}},e}function b(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function x(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,c=[],u=!0,l=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(c.push(n.value),c.length!==e);u=!0);}catch(t){l=!0,o=t}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return c}}(t,e)||function(t,e){if(t){if("string"==typeof t)return E(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?E(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function E(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}var L=function(e){var n=e.children,o=e.token,i=void 0===o?null:o,a=e.defaults.postalCode,c=void 0===a?"":a,u=x((0,t.useState)(!1),2),s=u[0],f=u[1],h=x((0,t.useState)(!1),2),p=h[0],y=h[1],v=r(),d=v.applicationId,m=v.locationId;return(0,t.useEffect)((function(){if(!s){var t=function(){if(window.Square&&d&&m)try{f(window.Square.payments(d,m))}catch(t){console.error("Failed to initialize Square payments:",t)}};if(t(),!window.Square){var e=0,r=setInterval((function(){e++,window.Square?(clearInterval(r),t()):e>=20&&(clearInterval(r),console.error("Square SDK failed to load after 10 seconds"))}),500);return function(){return clearInterval(r)}}}}),[d,m,s]),(0,t.useEffect)((function(){if(s&&!p&&!i){var t=function(){var t,e=(t=w().mark((function t(){var e;return w().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,s.card({postalCode:c});case 2:e=t.sent,y(e);case 4:case"end":return t.stop()}}),t)})),function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){b(i,n,o,a,c,"next",t)}function c(t){b(i,n,o,a,c,"throw",t)}a(void 0)}))});return function(){return e.apply(this,arguments)}}();t()}}),[s,p,i,c]),s?wp.element.createElement(l.Provider,{value:{payments:s,card:p,token:i}},n):null};function _(t){return _="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_(t)}function S(){S=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),c=new N(n||[]);return o(a,"_invoke",{value:O(t,r,c)}),a}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var h="suspendedStart",p="suspendedYield",y="executing",v="completed",d={};function m(){}function g(){}function w(){}var b={};l(b,a,(function(){return this}));var x=Object.getPrototypeOf,E=x&&x(x(I([])));E&&E!==r&&n.call(E,a)&&(b=E);var L=w.prototype=m.prototype=Object.create(b);function C(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function k(t,e){function r(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==_(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function O(e,r,n){var o=h;return function(i,a){if(o===y)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=j(c,n);if(u){if(u===d)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(e,r,n);if("normal"===l.type){if(o=n.done?v:p,l.arg===d)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=v,n.method="throw",n.arg=l.arg)}}}function j(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,j(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),d;var i=f(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,d;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,d):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,d)}function P(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function T(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function N(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(P,this),this.reset(!0)}function I(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(_(e)+" is not iterable")}return g.prototype=w,o(L,"constructor",{value:w,configurable:!0}),o(w,"constructor",{value:g,configurable:!0}),g.displayName=l(w,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===g||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,l(t,u,"GeneratorFunction")),t.prototype=Object.create(L),t},e.awrap=function(t){return{__await:t}},C(k.prototype),l(k.prototype,c,(function(){return this})),e.AsyncIterator=k,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new k(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},C(L),l(L,u,"Generator"),l(L,a,(function(){return this})),l(L,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=I,N.prototype={constructor:N,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(T),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,d):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),d},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),T(r),d}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;T(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:I(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),d}},e}function C(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}var k=function(){var e=(0,t.useContext)(l).card,r=(0,t.useRef)(!1);return(0,t.useEffect)((function(){if(e){var t=function(){var t,n=(t=S().mark((function t(){return S().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:e.attach(r.current);case 1:case"end":return t.stop()}}),t)})),function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){C(i,n,o,a,c,"next",t)}function c(t){C(i,n,o,a,c,"throw",t)}a(void 0)}))});return function(){return n.apply(this,arguments)}}();t()}}),[e]),wp.element.createElement(React.Fragment,null,wp.element.createElement("div",{ref:r}))},O=function(e){var n=e.billing,o=e.eventRegistration,i=e.emitResponse,a=(e.shouldSavePayment,function(e){var n=arguments.length>1&&void 0!==arguments[1]&&arguments[1],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=d((0,t.useState)(!1),2),a=i[0],c=i[1],u=d((0,t.useState)(""),2),l=u[0],s=u[1],f=(0,t.useMemo)((function(){var t=n&&!o?"STORE":"CHARGE",r={billingContact:{familyName:e.billingData.last_name||"",givenName:e.billingData.first_name||"",email:e.billingData.email||"",country:e.billingData.country||"",region:e.billingData.state||"",city:e.billingData.city||"",postalCode:e.billingData.postcode||"",phone:e.billingData.phone||"",addressLines:[e.billingData.address_1||"",e.billingData.address_2||""]},intent:t};return"CHARGE"===t&&(r.amount=(e.cartTotal.value/100).toString(),r.currencyCode=e.currency.code),r}),[e.billingData,e.cartTotal.value,e.currency.code,n,o]),p=(0,t.useCallback)((function(t){var e,r,i,a=t.cardData,c=void 0===a?{}:a,u=t.nonce,l=t.verificationToken,s=t.notices,f=(t.logs,v(v(v(v(v(v(v(v(v(v(i={},"wc-squaresync_credit-card-type",(null==c?void 0:c.brand)||""),"wc-squaresync_credit-last-four",(null==c?void 0:c.last4)||""),"wc-squaresync_credit-exp-month",(null==c||null===(e=c.expMonth)||void 0===e?void 0:e.toString())||""),"wc-squaresync_credit-exp-year",(null==c||null===(r=c.expYear)||void 0===r?void 0:r.toString())||""),"wc-squaresync_credit-payment-postcode",(null==c?void 0:c.postalCode)||""),"wc-squaresync_credit-payment-nonce",u||""),"wc-squaresync_credit-payment-token",o||""),"wc-squaresync_credit-buyer-verification-token",l||""),"wc-squaresync_credit-tokenize-payment-method",n||!1),"log-data",""),v(i,"checkout-notices",s.length>0?JSON.stringify(s):""));return o&&(f.token=o),f}),[l,n,o]),m=(0,t.useCallback)(function(){var t=y(h().mark((function t(e){return h().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(o){t.next=4;break}return t.next=3,e.tokenize();case 3:return t.abrupt("return",t.sent);case 4:return t.abrupt("return",o);case 5:case"end":return t.stop()}}),t)})));return function(_x){return t.apply(this,arguments)}}(),[o]),g=(0,t.useCallback)((function(t){var e={notices:[],logs:[]};return t&&t.token?e.verificationToken=t.token:console.log("Verification token is missing from the Square response",e),e}),[]),w=(0,t.useCallback)(function(){var t=y(h().mark((function t(e,r){var n;return h().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,e.verifyBuyer(r,f);case 3:return n=t.sent,t.abrupt("return",g(n));case 7:t.prev=7,t.t0=t.catch(0),console.error("Error in verifyBuyer:",t.t0);case 10:return t.abrupt("return",!1);case 11:case"end":return t.stop()}}),t,null,[[0,7]])})));return function(e,r){return t.apply(this,arguments)}}(),[f,g]);return{handleInputReceived:(0,t.useCallback)((function(t){if("cardBrandChanged"===t.eventType){var e=t.cardBrand,n="plain";null!==e&&"unknown"!==e||(n=""),null!==r().availableCardTypes[e]&&(n=r().availableCardTypes[e]),s(n)}}),[]),isLoaded:a,setLoaded:c,getPostalCode:(0,t.useCallback)((function(){return e.billingData.postcode||""}),[e.billingData.postcode]),cardType:l,createNonce:m,verifyBuyer:w,getPaymentMethodData:p}}(n,!1));return wp.element.createElement(L,{defaults:{postalCode:a.getPostalCode()}},wp.element.createElement(k,null),wp.element.createElement(s,{checkoutFormHandler:a,eventRegistration:o,emitResponse:i}))},j=["RenderedComponent"],P=window.wc.wcBlocksRegistry,T=(P.registerPaymentMethod,P.registerExpressPaymentMethod,function(t){var e=t.RenderedComponent,r=function(t,e){if(null==t)return{};var r,n,o=function(t,e){if(null==t)return{};var r={};for(var n in t)if({}.hasOwnProperty.call(t,n)){if(e.includes(n))continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n<i.length;n++)r=i[n],e.includes(r)||{}.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,j);return wp.element.createElement(e,r)});const N={name:"squaresync_credit",paymentMethodId:"squaresync_credit",label:wp.element.createElement((function(t){var e=t.components.PaymentMethodLabel,r=t.labelText;return wp.element.createElement(e,{text:r})}),{labelText:"Credit Card"}),content:wp.element.createElement(T,{RenderedComponent:O}),edit:wp.element.createElement(T,{RenderedComponent:O}),ariaLabel:"Square",canMakePayment:function(){return!(!r().applicationId||!r().locationId)},supports:{features:r().supports,showSaveOption:!r().hasSubscription}},I=window.wp.data;function A(t){return A="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},A(t)}function G(){G=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),c=new P(n||[]);return o(a,"_invoke",{value:C(t,r,c)}),a}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var h="suspendedStart",p="suspendedYield",y="executing",v="completed",d={};function m(){}function g(){}function w(){}var b={};l(b,a,(function(){return this}));var x=Object.getPrototypeOf,E=x&&x(x(T([])));E&&E!==r&&n.call(E,a)&&(b=E);var L=w.prototype=m.prototype=Object.create(b);function _(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function S(t,e){function r(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==A(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function C(e,r,n){var o=h;return function(i,a){if(o===y)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=k(c,n);if(u){if(u===d)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(e,r,n);if("normal"===l.type){if(o=n.done?v:p,l.arg===d)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=v,n.method="throw",n.arg=l.arg)}}}function k(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,k(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),d;var i=f(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,d;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,d):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,d)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function j(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function T(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(A(e)+" is not iterable")}return g.prototype=w,o(L,"constructor",{value:w,configurable:!0}),o(w,"constructor",{value:g,configurable:!0}),g.displayName=l(w,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===g||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,l(t,u,"GeneratorFunction")),t.prototype=Object.create(L),t},e.awrap=function(t){return{__await:t}},_(S.prototype),l(S.prototype,c,(function(){return this})),e.AsyncIterator=S,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new S(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},_(L),l(L,u,"Generator"),l(L,a,(function(){return this})),l(L,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=T,P.prototype={constructor:P,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(j),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,d):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),d},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),j(r),d}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:T(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),d}},e}function R(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function F(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){R(i,n,o,a,c,"next",t)}function c(t){R(i,n,o,a,c,"throw",t)}a(void 0)}))}}var H=function(t){return r().ajaxUrl.replace("%%endpoint%%","square_digital_wallet_".concat(t))},M=function(){var t=F(G().mark((function t(e){return G().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",new Promise((function(t,r){return jQuery.post(H("recalculate_totals"),e,(function(e){return e.success?t(e.data):r(e.data)}))})));case 1:case"end":return t.stop()}}),t)})));return function(_x){return t.apply(this,arguments)}}(),q=function(){var t=F(G().mark((function t(e){var n,o;return G().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n={context:r().context,shipping_option:e.id,security:r().recalculateTotalNonce,is_pay_for_order_page:r().isPayForOrderPage},t.next=3,M(n);case 3:return o=t.sent,t.abrupt("return",o);case 5:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}(),D=function(){var t=F(G().mark((function t(e){var n,o;return G().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n={context:r().context,shipping_contact:e,security:r().recalculateTotalNonce,is_pay_for_order_page:r().isPayForOrderPage},t.next=3,M(n);case 3:return o=t.sent,t.abrupt("return",o);case 5:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}(),V=function(){var t=F(G().mark((function t(e){var r;return G().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,e.tokenize();case 3:if("OK"!==(r=t.sent).status){t.next=6;break}return t.abrupt("return",r);case 6:t.next=11;break;case 8:return t.prev=8,t.t0=t.catch(0),t.abrupt("return",!1);case 11:return t.abrupt("return",!1);case 12:case"end":return t.stop()}}),t,null,[[0,8]])})));return function(e){return t.apply(this,arguments)}}();function Z(t){return Z="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Z(t)}function Y(){Y=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),c=new P(n||[]);return o(a,"_invoke",{value:C(t,r,c)}),a}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var h="suspendedStart",p="suspendedYield",y="executing",v="completed",d={};function m(){}function g(){}function w(){}var b={};l(b,a,(function(){return this}));var x=Object.getPrototypeOf,E=x&&x(x(T([])));E&&E!==r&&n.call(E,a)&&(b=E);var L=w.prototype=m.prototype=Object.create(b);function _(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function S(t,e){function r(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==Z(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function C(e,r,n){var o=h;return function(i,a){if(o===y)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=k(c,n);if(u){if(u===d)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(e,r,n);if("normal"===l.type){if(o=n.done?v:p,l.arg===d)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=v,n.method="throw",n.arg=l.arg)}}}function k(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,k(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),d;var i=f(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,d;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,d):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,d)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function j(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function T(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(Z(e)+" is not iterable")}return g.prototype=w,o(L,"constructor",{value:w,configurable:!0}),o(w,"constructor",{value:g,configurable:!0}),g.displayName=l(w,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===g||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,l(t,u,"GeneratorFunction")),t.prototype=Object.create(L),t},e.awrap=function(t){return{__await:t}},_(S.prototype),l(S.prototype,c,(function(){return this})),e.AsyncIterator=S,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new S(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},_(L),l(L,u,"Generator"),l(L,a,(function(){return this})),l(L,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=T,P.prototype={constructor:P,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(j),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,d):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),d},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),j(r),d}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:T(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),d}},e}function U(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,c=[],u=!0,l=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(c.push(n.value),c.length!==e);u=!0);}catch(t){l=!0,o=t}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return c}}(t,e)||function(t,e){if(t){if("string"==typeof t)return z(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?z(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function z(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}function B(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function $(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){B(i,n,o,a,c,"next",t)}function c(t){B(i,n,o,a,c,"throw",t)}a(void 0)}))}}function J(t){return J="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},J(t)}function K(){K=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),c=new P(n||[]);return o(a,"_invoke",{value:C(t,r,c)}),a}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var h="suspendedStart",p="suspendedYield",y="executing",v="completed",d={};function m(){}function g(){}function w(){}var b={};l(b,a,(function(){return this}));var x=Object.getPrototypeOf,E=x&&x(x(T([])));E&&E!==r&&n.call(E,a)&&(b=E);var L=w.prototype=m.prototype=Object.create(b);function _(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function S(t,e){function r(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==J(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function C(e,r,n){var o=h;return function(i,a){if(o===y)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=k(c,n);if(u){if(u===d)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(e,r,n);if("normal"===l.type){if(o=n.done?v:p,l.arg===d)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=v,n.method="throw",n.arg=l.arg)}}}function k(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,k(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),d;var i=f(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,d;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,d):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,d)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function j(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function T(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(J(e)+" is not iterable")}return g.prototype=w,o(L,"constructor",{value:w,configurable:!0}),o(w,"constructor",{value:g,configurable:!0}),g.displayName=l(w,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===g||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,l(t,u,"GeneratorFunction")),t.prototype=Object.create(L),t},e.awrap=function(t){return{__await:t}},_(S.prototype),l(S.prototype,c,(function(){return this})),e.AsyncIterator=S,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new S(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},_(L),l(L,u,"Generator"),l(L,a,(function(){return this})),l(L,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=T,P.prototype={constructor:P,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(j),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,d):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),d},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),j(r),d}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:T(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),d}},e}function W(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function Q(t,e,r){return(e=function(t){var e=function(t,e){if("object"!=J(t)||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var n=r.call(t,"string");if("object"!=J(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==J(e)?e:e+""}(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function X(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,c=[],u=!0,l=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(c.push(n.value),c.length!==e);u=!0);}catch(t){l=!0,o=t}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return c}}(t,e)||function(t,e){if(t){if("string"==typeof t)return tt(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?tt(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function tt(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}var et=function(){return wp.element.createElement("svg",{width:"343",height:"50",viewBox:"0 0 343 50",fill:"none",xmlns:"http://www.w3.org/2000/svg"},wp.element.createElement("rect",{width:"343",height:"50",rx:"4",fill:"black"}),wp.element.createElement("path",{d:"M97.6482 17.68H103.048C103.622 17.68 104.162 17.78 104.668 17.98C105.188 18.1667 105.642 18.4333 106.028 18.78C106.428 19.1133 106.742 19.5133 106.968 19.98C107.195 20.4467 107.308 20.9533 107.308 21.5C107.308 22.2333 107.122 22.86 106.748 23.38C106.388 23.8867 105.928 24.2667 105.368 24.52V24.64C106.088 24.8933 106.668 25.3067 107.108 25.88C107.562 26.4533 107.788 27.1467 107.788 27.96C107.788 28.5733 107.668 29.1267 107.428 29.62C107.188 30.1133 106.862 30.54 106.448 30.9C106.035 31.2467 105.555 31.52 105.008 31.72C104.475 31.9067 103.902 32 103.288 32H97.6482V17.68ZM102.968 23.66C103.302 23.66 103.602 23.6067 103.868 23.5C104.135 23.38 104.355 23.2333 104.528 23.06C104.715 22.8733 104.855 22.6667 104.948 22.44C105.042 22.2 105.088 21.96 105.088 21.72C105.088 21.48 105.042 21.2467 104.948 21.02C104.855 20.78 104.722 20.5733 104.548 20.4C104.375 20.2133 104.162 20.0667 103.908 19.96C103.655 19.84 103.368 19.78 103.048 19.78H99.9082V23.66H102.968ZM103.288 29.9C103.648 29.9 103.968 29.84 104.248 29.72C104.528 29.6 104.762 29.44 104.948 29.24C105.135 29.04 105.275 28.8133 105.368 28.56C105.475 28.3067 105.528 28.0467 105.528 27.78C105.528 27.5133 105.475 27.26 105.368 27.02C105.275 26.7667 105.128 26.5467 104.928 26.36C104.728 26.16 104.482 26 104.188 25.88C103.908 25.76 103.582 25.7 103.208 25.7H99.9082V29.9H103.288ZM116.875 30.68H116.755C116.461 31.1467 116.041 31.54 115.495 31.86C114.961 32.1667 114.355 32.32 113.675 32.32C112.435 32.32 111.508 31.9533 110.895 31.22C110.281 30.4733 109.975 29.4867 109.975 28.26V22.2H112.195V27.96C112.195 28.8133 112.388 29.4133 112.775 29.76C113.175 30.0933 113.695 30.26 114.335 30.26C114.708 30.26 115.041 30.18 115.335 30.02C115.641 29.86 115.901 29.6467 116.115 29.38C116.328 29.1 116.488 28.7867 116.595 28.44C116.701 28.08 116.755 27.7067 116.755 27.32V22.2H118.975V32H116.875V30.68ZM124.747 31.44L120.667 22.2H123.147L125.847 28.7H125.947L128.567 22.2H131.027L124.887 36.32H122.527L124.747 31.44ZM136.589 22.2H139.009L140.909 28.98H140.989L143.189 22.2H145.489L147.669 28.98H147.749L149.629 22.2H152.009L148.869 32H146.529L144.309 25.14H144.229L142.069 32H139.729L136.589 22.2ZM154.995 20.46C154.568 20.46 154.208 20.3133 153.915 20.02C153.635 19.7267 153.495 19.3733 153.495 18.96C153.495 18.5467 153.635 18.1933 153.915 17.9C154.208 17.6067 154.568 17.46 154.995 17.46C155.408 17.46 155.755 17.6067 156.035 17.9C156.328 18.1933 156.475 18.5467 156.475 18.96C156.475 19.3733 156.328 19.7267 156.035 20.02C155.755 20.3133 155.408 20.46 154.995 20.46ZM153.875 32V22.2H156.095V32H153.875ZM159.982 24.16H158.262V22.2H159.982V19.2H162.202V22.2H164.622V24.16H162.202V28.52C162.202 28.76 162.229 28.98 162.282 29.18C162.336 29.38 162.416 29.5467 162.522 29.68C162.749 29.9333 163.036 30.06 163.382 30.06C163.596 30.06 163.762 30.0467 163.882 30.02C164.002 29.98 164.129 29.9267 164.262 29.86L164.942 31.82C164.662 31.9267 164.369 32.0067 164.062 32.06C163.756 32.1267 163.409 32.16 163.022 32.16C162.556 32.16 162.142 32.0867 161.782 31.94C161.422 31.7933 161.109 31.5933 160.842 31.34C160.269 30.7667 159.982 29.9867 159.982 29V24.16ZM167.059 17.68H169.279V21.94L169.159 23.52H169.279C169.559 23.0533 169.972 22.6667 170.519 22.36C171.065 22.04 171.672 21.88 172.339 21.88C172.979 21.88 173.532 21.98 173.999 22.18C174.465 22.3667 174.852 22.64 175.159 23C175.465 23.36 175.692 23.7933 175.839 24.3C175.985 24.7933 176.059 25.34 176.059 25.94V32H173.839V26.24C173.839 25.4267 173.639 24.84 173.239 24.48C172.852 24.12 172.359 23.94 171.759 23.94C171.372 23.94 171.025 24.0267 170.719 24.2C170.425 24.36 170.165 24.58 169.939 24.86C169.725 25.14 169.559 25.46 169.439 25.82C169.332 26.18 169.279 26.5533 169.279 26.94V32H167.059V17.68Z",fill:"white"}),wp.element.createElement("path",{d:"M213.951 24.6725V31.7485H211.69V14.2748H217.684C219.203 14.2748 220.498 14.7778 221.558 15.7836C222.641 16.7895 223.183 18.0175 223.183 19.4678C223.183 20.9532 222.641 22.1813 221.558 23.1754C220.51 24.1696 219.215 24.6608 217.684 24.6608H213.951V24.6725ZM213.951 16.4269V22.5204H217.731C218.626 22.5204 219.379 22.2164 219.968 21.6199C220.569 21.0234 220.875 20.2982 220.875 19.4795C220.875 18.6725 220.569 17.9591 219.968 17.3626C219.379 16.7427 218.638 16.4386 217.731 16.4386H213.951V16.4269Z",fill:"white"}),wp.element.createElement("path",{d:"M229.094 19.3976C230.766 19.3976 232.085 19.8421 233.05 20.731C234.016 21.6199 234.499 22.8362 234.499 24.3801V31.7485H232.344V30.0877H232.25C231.319 31.4561 230.071 32.1345 228.517 32.1345C227.186 32.1345 226.079 31.7485 225.185 30.9649C224.29 30.1813 223.842 29.2105 223.842 28.0409C223.842 26.8011 224.313 25.8187 225.255 25.0935C226.197 24.3567 227.457 23.9941 229.023 23.9941C230.366 23.9941 231.472 24.2397 232.332 24.731V24.2164C232.332 23.4327 232.026 22.7778 231.402 22.228C230.778 21.6783 230.048 21.4093 229.212 21.4093C227.952 21.4093 226.951 21.9357 226.221 23L224.231 21.7602C225.326 20.1813 226.951 19.3976 229.094 19.3976ZM226.174 28.076C226.174 28.6608 226.421 29.152 226.927 29.538C227.422 29.9239 228.011 30.1228 228.682 30.1228C229.636 30.1228 230.483 29.7719 231.225 29.0701C231.967 28.3684 232.344 27.5497 232.344 26.6023C231.637 26.0526 230.66 25.7719 229.4 25.7719C228.482 25.7719 227.716 25.9941 227.104 26.4269C226.48 26.883 226.174 27.4327 226.174 28.076Z",fill:"white"}),wp.element.createElement("path",{d:"M246.792 19.7836L239.256 37H236.924L239.727 30.9766L234.758 19.7836H237.219L240.798 28.3684H240.845L244.331 19.7836H246.792Z",fill:"white"}),wp.element.createElement("path",{d:"M204.959 23.2456C204.959 22.5134 204.893 21.8128 204.77 21.1392H195.294V24.9988L200.751 25C200.53 26.2842 199.818 27.3789 198.726 28.1087V30.6128H201.975C203.872 28.869 204.959 26.2912 204.959 23.2456Z",fill:"#4285F4"}),wp.element.createElement("path",{d:"M198.727 28.1088C197.823 28.7146 196.658 29.069 195.296 29.069C192.664 29.069 190.432 27.3076 189.632 24.9333H186.281V27.5158C187.941 30.7883 191.354 33.0339 195.296 33.0339C198.021 33.0339 200.31 32.1439 201.976 30.6117L198.727 28.1088Z",fill:"#34A853"}),wp.element.createElement("path",{d:"M189.317 23.0175C189.317 22.3509 189.428 21.7064 189.632 21.1006V18.5181H186.281C185.594 19.8713 185.208 21.3988 185.208 23.0175C185.208 24.6362 185.596 26.1637 186.281 27.5169L189.632 24.9345C189.428 24.3286 189.317 23.6842 189.317 23.0175Z",fill:"#FABB05"}),wp.element.createElement("path",{d:"M195.296 16.9649C196.783 16.9649 198.115 17.4737 199.166 18.4678L202.045 15.6105C200.297 13.993 198.017 13 195.296 13C191.355 13 187.941 15.2456 186.281 18.5181L189.632 21.1006C190.432 18.7263 192.664 16.9649 195.296 16.9649Z",fill:"#E94235"}))},rt=function(){return wp.element.createElement("svg",{width:"343",height:"50",viewBox:"0 0 343 50",fill:"none",xmlns:"http://www.w3.org/2000/svg"},wp.element.createElement("rect",{width:"343",height:"50",rx:"8",fill:"black"}),wp.element.createElement("path",{d:"M155.748 19.8275C154.411 19.8275 153.333 20.636 152.637 20.636C151.907 20.636 150.93 19.8724 149.773 19.8724C147.572 19.8724 145.337 21.7029 145.337 25.1282C145.337 27.2733 146.168 29.5306 147.19 31.0018C148.055 32.2259 148.83 33.2366 149.93 33.2366C151.02 33.2366 151.503 32.5179 152.862 32.5179C154.232 32.5179 154.546 33.2142 155.748 33.2142C156.95 33.2142 157.747 32.1248 158.499 31.0467C159.33 29.8001 159.69 28.5872 159.701 28.5311C159.634 28.5086 157.343 27.5765 157.343 24.9485C157.343 22.68 159.139 21.6693 159.241 21.5906C158.061 19.8724 156.253 19.8275 155.748 19.8275ZM155.13 18.3787C155.669 17.7161 156.051 16.8177 156.051 15.908C156.051 15.7845 156.04 15.6609 156.017 15.5599C155.141 15.5936 154.063 16.1439 153.423 16.8963C152.929 17.4691 152.457 18.3787 152.457 19.2884C152.457 19.4232 152.48 19.5692 152.491 19.6141C152.547 19.6253 152.637 19.6365 152.727 19.6365C153.524 19.6365 154.535 19.0975 155.13 18.3787ZM164.115 16.8289V33.0345H167.013V27.7225H170.528C173.807 27.7225 176.098 25.5213 176.098 22.3094C176.098 19.0413 173.886 16.8289 170.652 16.8289H164.115ZM167.013 19.2547H169.888C171.977 19.2547 173.156 20.3216 173.156 22.3094C173.156 24.241 171.943 25.3192 169.877 25.3192H167.013V19.2547ZM181.535 31.0467C180.3 31.0467 179.412 30.429 179.412 29.3958C179.412 28.3963 180.142 27.8348 181.703 27.7337L184.477 27.554V28.5311C184.477 29.9573 183.219 31.0467 181.535 31.0467ZM180.715 33.2366C182.321 33.2366 183.669 32.5403 184.354 31.3499H184.545V33.0345H187.229V24.6453C187.229 22.0399 185.454 20.5013 182.299 20.5013C179.379 20.5013 177.346 21.8826 177.121 24.0501H179.749C180.008 23.2191 180.884 22.7698 182.164 22.7698C183.669 22.7698 184.477 23.4437 184.477 24.6453V25.6785L181.31 25.8694C178.323 26.0491 176.65 27.3294 176.65 29.553C176.65 31.7991 178.345 33.2366 180.715 33.2366ZM190.329 37.493C193.081 37.493 194.395 36.4822 195.439 33.4276L199.875 20.7484H196.933L194.069 30.3392H193.878L191.003 20.7484H187.948L192.34 33.0906L192.194 33.6297C191.834 34.764 191.172 35.2132 189.992 35.2132C189.801 35.2132 189.386 35.202 189.229 35.1683V37.4481C189.408 37.4818 190.161 37.493 190.329 37.493Z",fill:"white"}),wp.element.createElement("rect",{width:"343",height:"50",rx:"8",stroke:"black"}))};const nt={name:"squaresync_credit_wallet",paymentMethodId:"squaresync_credit",content:wp.element.createElement((function(e){var n=e.billing,o=e.shippingData,i=e.onClick,a=e.onClose,c=e.onSubmit,u=e.setExpressPaymentError,l=e.emitResponse,s=e.eventRegistration,f=s.onPaymentSetup,h=s.onCheckoutFail,p=X((0,t.useState)(!1),2),y=p[0],v=p[1],d=o.needsShipping;(0,t.useEffect)((function(){var t=(0,I.subscribe)((function(){wp.data.select("wc/store/cart").isApplyingCoupon()||v((function(t){return!t}))}));return function(){t()}}),[]);var m=function(){var e=U((0,t.useState)(null),2),n=e[0],o=e[1];return(0,t.useEffect)((function(){var t=r().applicationId,e=r().locationId;if(window.Square)try{var n=Square.payments(t,e);o(n)}catch(t){console.error(t)}}),[]),n}(),g=function(e,n,o){var i=(0,t.useRef)(null),a=U((0,t.useState)(null),2),c=a[0],u=a[1];return(0,t.useEffect)((function(){if(e){var t=function(){var t=$(Y().mark((function t(){var o,a,c,l,s;return Y().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,new Promise((function(t,e){var n={context:r().context,security:r().paymentRequestNonce,is_pay_for_order_page:!1};jQuery.post(H("get_payment_request"),n,(function(r){return r.success?t(r.data):e(r.data)}))}));case 3:o=t.sent,(a=JSON.parse(o))&&(Array.isArray(a.lineItems)&&(-1!==(c=a.lineItems.findIndex((function(t){var e;return null===(e=t.label)||void 0===e?void 0:e.toLowerCase().includes("shipping")})))&&a.lineItems.splice(c,1),-1!==(l=a.lineItems.findIndex((function(t){var e;return null===(e=t.label)||void 0===e?void 0:e.toLowerCase().includes("discount")})))&&a.lineItems.splice(l,1)),n&&(a.requestShippingAddress=!0)),i.current?i.current.update(a):(s=e.paymentRequest(a),i.current=s,u(s)),t.next=12;break;case 9:t.prev=9,t.t0=t.catch(0),console.error("Failed to create or update payment request:",t.t0);case 12:case"end":return t.stop()}}),t,null,[[0,9]])})));return function(){return t.apply(this,arguments)}}();t()}}),[e,n,o]),c}(m,d,y),w=function(e,n){var o=U((0,t.useState)(null),2),i=o[0],a=o[1],c=(0,t.useRef)(null);return(0,t.useEffect)((function(){e&&n&&$(Y().mark((function t(){var o;return Y().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,e.googlePay(n);case 3:return o=t.sent,t.next=6,o.attach(c.current,{buttonColor:r().googlePayColor,buttonSizeMode:"fill",buttonType:"long"});case 6:a(o),t.next=11;break;case 9:t.prev=9,t.t0=t.catch(0);case 11:case"end":return t.stop()}}),t,null,[[0,9]])})))()}),[e,n]),[i,c]}(m,g),b=X(w,2),x=b[0],E=b[1],L=function(e,n){var o=U((0,t.useState)(null),2),i=o[0],a=o[1],c=(0,t.useRef)(null);return(0,t.useEffect)((function(){e&&n&&$(Y().mark((function t(){var r;return Y().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,e.applePay(n);case 3:r=t.sent,a(r),t.next=10;break;case 7:t.prev=7,t.t0=t.catch(0),console.log(t.t0);case 10:case"end":return t.stop()}}),t,null,[[0,7]])})))()}),[e,n]),(0,t.useEffect)((function(){if(null!=c&&c.current&&i){var t=r().applePayColor,e=r().applePayType;"plain"!==e&&(c.current.querySelector(".text").innerText="".concat(e.charAt(0).toUpperCase()).concat(e.slice(1)," with"),c.current.classList.add("wc-square-wallet-button-with-text")),c.current.style.cssText+="-apple-pay-button-type: ".concat(e,";"),c.current.style.cssText+="-apple-pay-button-style: ".concat(t,";"),c.current.style.display="block",c.current.classList.add("wc-square-wallet-button-".concat(t))}}),[i,c]),[i,c]}(m,g),_=X(L,2),S=_[0],C=_[1],k=function(e,r){var n=U((0,t.useState)(null),2),o=n[0],i=n[1],a=(0,t.useRef)(null);return(0,t.useEffect)((function(){e&&r&&$(Y().mark((function t(){var n;return Y().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,e.afterpayClearpay(r);case 3:return n=t.sent,t.next=6,n.attach(a.current,{buttonColor:"black",buttonSizeMode:"fill"});case 6:i(n),t.next=11;break;case 9:t.prev=9,t.t0=t.catch(0);case 11:case"end":return t.stop()}}),t,null,[[0,9]])})))()}),[e,r]),[o,a]}(m,g),O=X(k,2),j=O[0],P=O[1],T=X((0,t.useState)(!1),2),N=T[0],A=T[1],G=X((0,t.useState)(null),2),R=G[0],F=G[1];!function(e){(0,t.useEffect)((function(){null==e||e.addEventListener("shippingcontactchanged",(function(t){return D(t)})),null==e||e.addEventListener("afterpay_shippingaddresschanged",(function(t){return D(t)}))}),[e])}(g),function(e){(0,t.useEffect)((function(){null==e||e.addEventListener("shippingoptionchanged",(function(t){return q(t)})),null==e||e.addEventListener("afterpay_shippingoptionchanged",(function(t){return q(t)}))}),[e])}(g);var M=function(t){var e=t||N;if(!e||!e.token)return{type:l.responseTypes.ERROR,message:"Payment token is missing. Please try again."};var r=e.details,o=e.token,i=r||{},a=i.method,c=void 0===a?"":a,u=i.card,s=void 0===u?{}:u,f=i.billing,h=void 0===f?{}:f,p=i.shipping,y=(((void 0===p?{}:p)||{}).contact,{intent:"CHARGE",amount:(n.cartTotal.value/100).toString(),currencyCode:n.currency.code,billingContact:{familyName:h.familyName||n.billingData.last_name||"",givenName:h.givenName||n.billingData.first_name||"",email:h.email||n.billingData.email||"",country:h.countryCode||n.billingData.country||"",region:h.state||n.billingData.state||"",city:h.city||n.billingData.city||"",postalCode:h.postalCode||n.billingData.postcode||"",phone:h.phone||n.billingData.phone||"",addressLines:h.addressLines||[n.billingData.address_1,n.billingData.address_2].filter(Boolean)}});return m.verifyBuyer(o,y).then((function(t){var e,r,n="wc-squaresync_credit";return{type:l.responseTypes.SUCCESS,meta:{paymentMethodData:Q(Q(Q(Q(Q(Q(Q({},"".concat(n,"-card-type"),c||""),"".concat(n,"-last-four"),(null==s?void 0:s.last4)||""),"".concat(n,"-exp-month"),(null==s||null===(e=s.expMonth)||void 0===e?void 0:e.toString())||""),"".concat(n,"-exp-year"),(null==s||null===(r=s.expYear)||void 0===r?void 0:r.toString())||""),"".concat(n,"-payment-postcode"),(null==s?void 0:s.postalCode)||""),"".concat(n,"-payment-nonce"),o||""),"".concat(n,"-buyer-verification-token"),(null==t?void 0:t.token)||"")}}})).catch((function(t){return{type:l.responseTypes.ERROR,message:t.message||"Payment processing failed"}}))};(0,t.useEffect)((function(){return function(){R&&R()}}),[R]),(0,t.useEffect)((function(){return h((function(){return R&&(R(),F(null)),a(),!0}))}),[h,R]);var Z=r().googlePay.includes("no"),z=r().applePay.includes("no"),B=r().afterPay.includes("no");function J(t){var e;t&&(u(""),i(),(e=K().mark((function e(){var r,n,o,i,u,l,s,h;return K().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,V(t);case 2:if(r=e.sent){e.next=7;break}a(),e.next=31;break;case 7:if(!r||!r.token){e.next=24;break}return i=(null==r||null===(n=r.details)||void 0===n?void 0:n.billing)||{},u=(null==r||null===(o=r.details)||void 0===o||null===(o=o.shipping)||void 0===o?void 0:o.contact)||{},l={email:i.email||"",first_name:i.givenName||"",last_name:i.familyName||"",company:"",address_1:i.addressLines&&i.addressLines[0]||"",address_2:i.addressLines&&i.addressLines[1]||"",city:i.city||"",state:i.state||"",postcode:i.postalCode||"",country:i.countryCode||"",phone:i.phone||""},s={first_name:u.givenName||i.givenName||"",last_name:u.familyName||i.familyName||"",company:"",address_1:u.addressLines&&u.addressLines[0]||i.addressLines&&i.addressLines[0]||"",address_2:u.addressLines&&u.addressLines[1]||i.addressLines&&i.addressLines[1]||"",city:u.city||i.city||"",state:u.state||i.state||"",postcode:u.postalCode||i.postalCode||"",country:u.countryCode||i.countryCode||"",phone:u.phone||i.phone||""},e.prev=12,e.next=15,wp.data.dispatch("wc/store/cart").setBillingAddress(l);case 15:if(!d){e.next=18;break}return e.next=18,wp.data.dispatch("wc/store/cart").setShippingAddress(s);case 18:return e.next=20,new Promise((function(t){return setTimeout(t,100)}));case 20:e.next=24;break;case 22:e.prev=22,e.t0=e.catch(12);case 24:return A(r),R&&R(),h=f((function(){return M(r)})),F((function(){return h})),e.next=30,new Promise((function(t){return setTimeout(t,50)}));case 30:c();case 31:case"end":return e.stop()}}),e,null,[[12,22]])})),function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(t){W(i,n,o,a,c,"next",t)}function c(t){W(i,n,o,a,c,"throw",t)}a(void 0)}))})())}var tt=!Z&&wp.element.createElement("div",{tabIndex:0,role:"button",ref:E,onClick:function(){return J(x)}}),et=!B&&wp.element.createElement("div",{tabIndex:0,role:"button",ref:P,onClick:function(){return J(j)}}),rt=!z&&wp.element.createElement("div",{tabIndex:0,role:"button",ref:C,onClick:function(){return J(S)},className:"apple-pay-button wc-square-wallet-buttons"},wp.element.createElement("span",{className:"text"}),wp.element.createElement("span",{className:"logo"}));return wp.element.createElement(React.Fragment,null,rt,tt,et)}),null),edit:wp.element.createElement((function(){return wp.element.createElement(React.Fragment,null,wp.element.createElement(et,null),wp.element.createElement(rt,null))}),null),canMakePayment:function(){var t=!(!r().applicationId||!r().locationId),e=r().isDigitalWalletsEnabled;return t&&e},supports:{features:r().supports}};function ot(t){return ot="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ot(t)}function it(){it=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),c=new P(n||[]);return o(a,"_invoke",{value:C(t,r,c)}),a}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var h="suspendedStart",p="suspendedYield",y="executing",v="completed",d={};function m(){}function g(){}function w(){}var b={};l(b,a,(function(){return this}));var x=Object.getPrototypeOf,E=x&&x(x(T([])));E&&E!==r&&n.call(E,a)&&(b=E);var L=w.prototype=m.prototype=Object.create(b);function _(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function S(t,e){function r(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==ot(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function C(e,r,n){var o=h;return function(i,a){if(o===y)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=k(c,n);if(u){if(u===d)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(e,r,n);if("normal"===l.type){if(o=n.done?v:p,l.arg===d)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=v,n.method="throw",n.arg=l.arg)}}}function k(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,k(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),d;var i=f(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,d;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,d):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,d)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function j(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function T(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(ot(e)+" is not iterable")}return g.prototype=w,o(L,"constructor",{value:w,configurable:!0}),o(w,"constructor",{value:g,configurable:!0}),g.displayName=l(w,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===g||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,l(t,u,"GeneratorFunction")),t.prototype=Object.create(L),t},e.awrap=function(t){return{__await:t}},_(S.prototype),l(S.prototype,c,(function(){return this})),e.AsyncIterator=S,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new S(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},_(L),l(L,u,"Generator"),l(L,a,(function(){return this})),l(L,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=T,P.prototype={constructor:P,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(j),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,d):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),d},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),j(r),d}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:T(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),d}},e}function at(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function ct(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){at(i,n,o,a,c,"next",t)}function c(t){at(i,n,o,a,c,"throw",t)}a(void 0)}))}}var ut=function(){var t=ct(it().mark((function t(e,r,n){var o;return it().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,e.verifyBuyer(r,n);case 3:return o=t.sent,t.abrupt("return",o);case 7:throw t.prev=7,t.t0=t.catch(0),console.error("Error during buyer verification:",t.t0),t.t0;case 11:case"end":return t.stop()}}),t,null,[[0,7]])})));return function(e,r,n){return t.apply(this,arguments)}}(),lt=function(){var t=ct(it().mark((function t(e){var r;return it().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return console.log("[utils.js] tokenize() called with button:",e),t.prev=1,t.next=4,e.tokenize();case 4:if(r=t.sent,console.log("[utils.js] tokenize() => tokenResult:",r),"OK"!==r.status){t.next=9;break}return console.log("[utils.js] tokenize() => status=OK => returning tokenResult"),t.abrupt("return",r);case 9:r.errors&&r.errors.length&&r.errors.forEach((function(t){console.error("Afterpay tokenization error:",t)})),t.next=15;break;case 12:t.prev=12,t.t0=t.catch(1),console.error("[utils.js] Exception during Afterpay tokenization:",t.t0);case 15:return console.error("[utils.js] tokenize() => returning false (tokenization failed)"),t.abrupt("return",!1);case 17:case"end":return t.stop()}}),t,null,[[1,12]])})));return function(e){return t.apply(this,arguments)}}();function st(t){return st="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},st(t)}function ft(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=mt(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var _n=0,n=function(){};return{s:n,n:function(){return _n>=t.length?{done:!0}:{done:!1,value:t[_n++]}},e:function(t){throw t},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,i=!0,a=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return i=t.done,t},e:function(t){a=!0,o=t},f:function(){try{i||null==r.return||r.return()}finally{if(a)throw o}}}}function ht(t,e,r){return(e=function(t){var e=function(t,e){if("object"!=st(t)||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var n=r.call(t,"string");if("object"!=st(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==st(e)?e:e+""}(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function pt(){pt=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),c=new P(n||[]);return o(a,"_invoke",{value:C(t,r,c)}),a}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var h="suspendedStart",p="suspendedYield",y="executing",v="completed",d={};function m(){}function g(){}function w(){}var b={};l(b,a,(function(){return this}));var x=Object.getPrototypeOf,E=x&&x(x(T([])));E&&E!==r&&n.call(E,a)&&(b=E);var L=w.prototype=m.prototype=Object.create(b);function _(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function S(t,e){function r(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==st(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function C(e,r,n){var o=h;return function(i,a){if(o===y)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=k(c,n);if(u){if(u===d)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(e,r,n);if("normal"===l.type){if(o=n.done?v:p,l.arg===d)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=v,n.method="throw",n.arg=l.arg)}}}function k(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,k(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),d;var i=f(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,d;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,d):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,d)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function j(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function T(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(st(e)+" is not iterable")}return g.prototype=w,o(L,"constructor",{value:w,configurable:!0}),o(w,"constructor",{value:g,configurable:!0}),g.displayName=l(w,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===g||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,l(t,u,"GeneratorFunction")),t.prototype=Object.create(L),t},e.awrap=function(t){return{__await:t}},_(S.prototype),l(S.prototype,c,(function(){return this})),e.AsyncIterator=S,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new S(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},_(L),l(L,u,"Generator"),l(L,a,(function(){return this})),l(L,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=T,P.prototype={constructor:P,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(j),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,d):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),d},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),j(r),d}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:T(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),d}},e}function yt(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function vt(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){yt(i,n,o,a,c,"next",t)}function c(t){yt(i,n,o,a,c,"throw",t)}a(void 0)}))}}function dt(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,c=[],u=!0,l=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(c.push(n.value),c.length!==e);u=!0);}catch(t){l=!0,o=t}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return c}}(t,e)||mt(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function mt(t,e){if(t){if("string"==typeof t)return gt(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?gt(t,e):void 0}}function gt(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}function wt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return((parseInt(t,10)||0)/Math.pow(10,e)).toFixed(e)}function bt(){return xt.apply(this,arguments)}function xt(){return(xt=vt(pt().mark((function t(){var e,r,n,o,i,a,c,u,l,s,f,h,p,y,v,d,m,g,w;return pt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if((n=(0,I.select)("wc/store/cart").getShippingRates()||[]).length){t.next=3;break}return t.abrupt("return",[]);case 3:if(o=n[0],null!==(e=o.shipping_rates)&&void 0!==e&&e.length){t.next=6;break}return t.abrupt("return",[]);case 6:i=(0,I.select)("wc/store/cart").getCartTotals()||{},a=parseInt(i.currency_minor_unit,10)||2,c=null===(r=o.shipping_rates.find((function(t){return t.is_chosen})))||void 0===r?void 0:r.rate_id,u=[],l=ft(o.shipping_rates),t.prev=11,l.s();case 13:if((s=l.n()).done){t.next=25;break}return v=s.value,(0,I.dispatch)("wc/store/cart").selectShippingRate(v.rate_id,0),t.next=18,new Promise((function(t){return setTimeout(t,300)}));case 18:d=(0,I.select)("wc/store/cart").getCartTotals()||{},m=wt(null!==(f=d.total_price)&&void 0!==f?f:"0",a),g=wt(null!==(h=d.total_tax)&&void 0!==h?h:"0",a),w=wt(null!==(p=v.price)&&void 0!==p?p:"0",a),u.push({id:v.rate_id,label:v.name,amount:w,taxLineItems:[{id:"taxItem1",label:"Taxes",amount:g}],total:{label:null!==(y=d.total_label)&&void 0!==y?y:"Total",amount:m}});case 23:t.next=13;break;case 25:t.next=30;break;case 27:t.prev=27,t.t0=t.catch(11),l.e(t.t0);case 30:return t.prev=30,l.f(),t.finish(30);case 33:if(!c){t.next=37;break}return(0,I.dispatch)("wc/store/cart").selectShippingRate(c,0),t.next=37,new Promise((function(t){return setTimeout(t,300)}));case 37:return t.abrupt("return",u);case 38:case"end":return t.stop()}}),t,null,[[11,27,30,33]])})))).apply(this,arguments)}function Et(t){return Et="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Et(t)}function Lt(){Lt=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),c=new P(n||[]);return o(a,"_invoke",{value:C(t,r,c)}),a}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var h="suspendedStart",p="suspendedYield",y="executing",v="completed",d={};function m(){}function g(){}function w(){}var b={};l(b,a,(function(){return this}));var x=Object.getPrototypeOf,E=x&&x(x(T([])));E&&E!==r&&n.call(E,a)&&(b=E);var L=w.prototype=m.prototype=Object.create(b);function _(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function S(t,e){function r(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==Et(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function C(e,r,n){var o=h;return function(i,a){if(o===y)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=k(c,n);if(u){if(u===d)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(e,r,n);if("normal"===l.type){if(o=n.done?v:p,l.arg===d)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=v,n.method="throw",n.arg=l.arg)}}}function k(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,k(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),d;var i=f(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,d;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,d):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,d)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function j(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function T(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(Et(e)+" is not iterable")}return g.prototype=w,o(L,"constructor",{value:w,configurable:!0}),o(w,"constructor",{value:g,configurable:!0}),g.displayName=l(w,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===g||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,l(t,u,"GeneratorFunction")),t.prototype=Object.create(L),t},e.awrap=function(t){return{__await:t}},_(S.prototype),l(S.prototype,c,(function(){return this})),e.AsyncIterator=S,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new S(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},_(L),l(L,u,"Generator"),l(L,a,(function(){return this})),l(L,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=T,P.prototype={constructor:P,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(j),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,d):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),d},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),j(r),d}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:T(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),d}},e}function _t(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function St(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,c=[],u=!0,l=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(c.push(n.value),c.length!==e);u=!0);}catch(t){l=!0,o=t}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return c}}(t,e)||function(t,e){if(t){if("string"==typeof t)return Ct(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Ct(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Ct(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}wp.element.createElement((function(e){var n,o=e.billing,i=e.shippingData,a=e.onClick,c=e.onClose,u=(e.onSubmit,e.setExpressPaymentError),l=e.emitResponse,s=e.eventRegistration,f=s.onPaymentSetup,h=s.onCheckoutFail,p=St((0,t.useState)(!1),2),y=p[0],v=p[1],d=i.needsShipping;(0,t.useEffect)((function(){var t=(0,I.subscribe)((function(){wp.data.select("wc/store/cart").isApplyingCoupon()||v((function(t){return!t}))}));return function(){t()}}),[]);var m,g=function(){var e=dt((0,t.useState)(null),2),n=e[0],o=e[1];return(0,t.useEffect)((function(){var t=r(),e=t.applicationId,n=t.locationId;if(window.Square)try{var i=Square.payments(e,n);o(i)}catch(t){console.error("[useSquare] Error creating payments:",t)}else console.error("[useSquare] window.Square is not available!")}),[]),n}(),w=function(e,n,o){var i=(0,t.useRef)(null),a=dt((0,t.useState)(null),2),c=a[0],u=a[1];return(0,t.useEffect)((function(){function t(){return(t=vt(pt().mark((function t(){var o,a,c,l,s;return pt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,new Promise((function(t,e){var n,o={context:r().context,security:r().paymentRequestNonce,is_pay_for_order_page:!1};jQuery.post((n="get_payment_request",r().ajaxUrl.replace("%%endpoint%%","square_digital_wallet_".concat(n))),o,(function(r){r.success?t(r.data):e(r.data)}))}));case 3:o=t.sent,a=JSON.parse(o),Array.isArray(a.lineItems)&&(-1!==(c=a.lineItems.findIndex((function(t){var e;return null===(e=t.label)||void 0===e?void 0:e.toLowerCase().includes("shipping")})))&&a.lineItems.splice(c,1),-1!==(l=a.lineItems.findIndex((function(t){var e;return null===(e=t.label)||void 0===e?void 0:e.toLowerCase().includes("discount")})))&&a.lineItems.splice(l,1)),n&&(a.requestShippingAddress=!0),i.current?i.current.update(a):(s=e.paymentRequest(a),i.current=s,u(s)),t.next=13;break;case 10:t.prev=10,t.t0=t.catch(0),console.error("Failed to create/update PaymentRequest:",t.t0);case 13:case"end":return t.stop()}}),t,null,[[0,10]])})))).apply(this,arguments)}e&&function(){t.apply(this,arguments)}()}),[e,n,o]),[c]}(g,d,y),b=St(w,1)[0],x=function(e,r){var n=dt((0,t.useState)(null),2),o=n[0],i=n[1],a=(0,t.useRef)(null);return(0,t.useEffect)((function(){e&&r?vt(pt().mark((function t(){var n;return pt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return console.log(r),t.prev=1,t.next=4,e.afterpayClearpay(r);case 4:return n=t.sent,console.log(n),t.next=8,n.attach(a.current,{buttonColor:"black",buttonSizeMode:"fill"});case 8:i(n),t.next=13;break;case 11:t.prev=11,t.t0=t.catch(1);case 13:case"end":return t.stop()}}),t,null,[[1,11]])})))():console.log("no payment")}),[e,r]),[o,a]}(g,b),E=St(x,2),L=E[0],_=E[1],S=St((0,t.useState)(!1),2),C=S[0],k=S[1];return m=b,(0,t.useRef)(!1),(0,t.useEffect)((function(){if(m&&"function"==typeof m.addEventListener){var t=function(){var t=vt(pt().mark((function t(e){var r,n,o;return pt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,e.givenName,e.familyName,null===(r=e.addressLines)||void 0===r||r[0],null===(n=e.addressLines)||void 0===n||n[1],e.city,e.state,e.postalCode,e.countryCode,e.phone,t.next=4,new Promise((function(t){return setTimeout(t,300)}));case 4:return t.next=6,bt();case 6:if((o=t.sent).length){t.next=9;break}return t.abrupt("return");case 9:return t.abrupt("return",{shippingOptions:o});case 12:t.prev=12,t.t0=t.catch(0),console.error("Error in onAfterpayShippingAddressChanged:",t.t0);case 15:case"end":return t.stop()}}),t,null,[[0,12]])})));return function(_x){return t.apply(this,arguments)}}();return m.addEventListener("afterpay_shippingaddresschanged",t),function(){"function"==typeof m.removeEventListener&&m.removeEventListener("afterpay_shippingaddresschanged",t)}}}),[m]),function(e,r,n,o,i){console.log(n);var a=function(t){var e={familyName:t.billingData.last_name||"",givenName:t.billingData.first_name||"",email:t.billingData.email||"",country:t.billingData.country||"",region:t.billingData.state||"",city:t.billingData.city||"",postalCode:t.billingData.postcode||""};t.billingData.phone&&(e.phone=t.billingData.phone);var r=[t.billingData.address_1,t.billingData.address_2].filter(Boolean);return r.length&&(e.addressLines=r),{intent:"CHARGE",amount:(t.cartTotal.value/100).toString(),currencyCode:t.currency.code,billingContact:e}}(r);(0,t.useEffect)((function(){if(n)return i((function(){function t(){return(t=vt(pt().mark((function t(){var r,i,c,u,l,s,f,h,p,y,v,d,m,g,w,b,x,E,L,_,S,C,k,O,j,P,T,N,I,A,G,R,F,H,M,q,D,V,Z,Y;return pt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(console.log(n.token),O={type:o.responseTypes.SUCCESS},n){t.next=6;break}return console.error("[usePaymentProcessing] tokenResult is null/undefined!"),O={type:o.responseTypes.FAILURE},t.abrupt("return",O);case 6:return j=n.details,P=j.card,T=j.method,N=n.token,t.next=9,ut(e,N,a);case 9:if(I=t.sent,console.log(I),A=I.token,G="wc-squaresync_credit",R=(null==n||null===(r=n.details)||void 0===r?void 0:r.billing)||{},F=(null==n||null===(i=n.details)||void 0===i?void 0:i.shipping)||{},H=F.contact,M=void 0===H?{}:H,q=F.option,D=void 0===q?{}:q,V=null!==(c=null!==(u=null==R?void 0:R.email)&&void 0!==u?u:null==M?void 0:M.email)&&void 0!==c?c:"",Z=null!==(l=null!==(s=null==R?void 0:R.phone)&&void 0!==s?s:null==M?void 0:M.phone)&&void 0!==l?l:"",Y=null!==(f=null!==(h=null==M?void 0:M.phone)&&void 0!==h?h:null==R?void 0:R.phone)&&void 0!==f?f:"",O.meta={paymentMethodData:ht(ht(ht(ht(ht(ht(ht(ht({},"".concat(G,"-card-type"),T||""),"".concat(G,"-last-four"),(null==P?void 0:P.last4)||""),"".concat(G,"-exp-month"),(null==P||null===(p=P.expMonth)||void 0===p?void 0:p.toString())||""),"".concat(G,"-exp-year"),(null==P||null===(y=P.expYear)||void 0===y?void 0:y.toString())||""),"".concat(G,"-payment-postcode"),(null==P?void 0:P.postalCode)||""),"".concat(G,"-payment-nonce"),N||""),"".concat(G,"-buyer-verification-token"),A||""),"shipping_method",null!==(v=D.id)&&void 0!==v&&v),billingAddress:{email:V,first_name:null!==(d=R.givenName)&&void 0!==d?d:"",last_name:null!==(m=R.familyName)&&void 0!==m?m:"",company:"",address_1:R.addressLines?R.addressLines[0]:"",address_2:R.addressLines?R.addressLines[1]:"",city:null!==(g=R.city)&&void 0!==g?g:"",state:null!==(w=R.state)&&void 0!==w?w:"",postcode:null!==(b=R.postalCode)&&void 0!==b?b:"",country:null!==(x=R.countryCode)&&void 0!==x?x:"",phone:Z},shippingAddress:{first_name:null!==(E=M.givenName)&&void 0!==E?E:"",last_name:null!==(L=M.familyName)&&void 0!==L?L:"",company:"",address_1:M.addressLines?M.addressLines[0]:"",address_2:M.addressLines?M.addressLines[1]:"",city:null!==(_=M.city)&&void 0!==_?_:"",state:null!==(S=M.state)&&void 0!==S?S:"",postcode:null!==(C=M.postalCode)&&void 0!==C?C:"",country:null!==(k=M.countryCode)&&void 0!==k?k:"",phone:Y}},!wp.data.select("wc/store/cart").getNeedsShipping()){t.next=27;break}if(wp.data.select("wc/store/cart").getShippingRates().some((function(t){return t.shipping_rates.length}))){t.next=27;break}return console.error("[usePaymentProcessing] No shipping rates available => FAILURE"),O.type=o.responseTypes.FAILURE,console.log(O),t.abrupt("return",O);case 27:return console.log(O),t.abrupt("return",O);case 29:case"end":return t.stop()}}),t)})))).apply(this,arguments)}return function(){return t.apply(this,arguments)}()}));console.log("[usePaymentProcessing] no tokenResult yet, doing nothing.")}),[n])}(g,o,C,l,f),(0,t.useEffect)((function(){return h((function(){return c(),!0}))}),[h]),null===(n=r())||void 0===n||null===(n=n.afterpay)||void 0===n||n.includes("no"),wp.element.createElement(React.Fragment,null,wp.element.createElement("div",{ref:_,role:"button",tabIndex:0,className:"afterpay-button wc-square-wallet-buttons",onClick:function(){var t,e;(t=L)?(u(""),a(),(e=Lt().mark((function e(){var r;return Lt().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,lt(t);case 2:(r=e.sent)?k(r):(console.error("Tokenization failed in onClickHandler"),c());case 4:case"end":return e.stop()}}),e)})),function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(t){_t(i,n,o,a,c,"next",t)}function c(t){_t(i,n,o,a,c,"throw",t)}a(void 0)}))})()):console.error("Button instance is null or undefined")}}))}),null),wp.element.createElement((function(){return wp.element.createElement(React.Fragment,null,wp.element.createElement("div",null,"afterpay"))}),null),r().supports;var kt=window.wc.wcBlocksRegistry,Ot=kt.registerPaymentMethod;(0,kt.registerExpressPaymentMethod)(nt),Ot(N)})();
     1(()=>{"use strict";const t=window.wp.element;var e=window.wc.wcSettings.getSetting,r=function(){var t=e("squaresync_credit_data",null);if(!t)throw new Error("Square initialization data is not available");return{title:t.title||"",applicationId:t.applicationId||"",locationId:t.locationId||"",isSandbox:t.is_sandbox||!1,availableCardTypes:t.accepted_credit_cards||{},loggingEnabled:t.logging_enabled||!1,generalError:t.general_error||"",showSavedCards:t.show_saved_cards||!1,showSaveOption:t.show_save_option||!1,supports:t.supports||{},isTokenizationForced:t.is_tokenization_forced||!1,paymentTokenNonce:t.payment_token_nonce||"",isDigitalWalletsEnabled:"yes"===t.enable_apple_pay||"yes"===t.enable_google_pay||"yes"===t.enable_after_pay||"yes"===t.enable_cash_app_pay||!1,googlePay:t.enable_google_pay||"no",applePay:t.enable_apple_pay||"no",afterPay:t.enable_after_pay||"no",cashAppPay:t.enable_cash_app_pay||"no",isPayForOrderPage:t.is_pay_for_order_page||!1,recalculateTotalNonce:t.recalculate_totals_nonce||!1,context:t.context||"",ajaxUrl:t.ajax_url||"",paymentRequestNonce:t.payment_request_nonce||"",googlePayColor:t.google_pay_color||"black",applePayColor:t.apple_pay_color||"black",applePayType:t.apple_pay_type||"buy",hideButtonOptions:t.hide_button_options||[],hasSubscription:t.hasSubscription||!1}};function n(t){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},n(t)}function o(){o=function(){return e};var t,e={},r=Object.prototype,i=r.hasOwnProperty,a=Object.defineProperty||function(t,e,r){t[e]=r.value},c="function"==typeof Symbol?Symbol:{},u=c.iterator||"@@iterator",l=c.asyncIterator||"@@asyncIterator",s=c.toStringTag||"@@toStringTag";function f(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{f({},"")}catch(t){f=function(t,e,r){return t[e]=r}}function h(t,e,r,n){var o=e&&e.prototype instanceof w?e:w,i=Object.create(o.prototype),c=new N(n||[]);return a(i,"_invoke",{value:O(t,r,c)}),i}function p(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=h;var y="suspendedStart",d="suspendedYield",v="executing",m="completed",g={};function w(){}function b(){}function x(){}var L={};f(L,u,(function(){return this}));var E=Object.getPrototypeOf,_=E&&E(E(I([])));_&&_!==r&&i.call(_,u)&&(L=_);var S=x.prototype=w.prototype=Object.create(L);function C(t){["next","throw","return"].forEach((function(e){f(t,e,(function(t){return this._invoke(e,t)}))}))}function k(t,e){function r(o,a,c,u){var l=p(t[o],t,a);if("throw"!==l.type){var s=l.arg,f=s.value;return f&&"object"==n(f)&&i.call(f,"__await")?e.resolve(f.__await).then((function(t){r("next",t,c,u)}),(function(t){r("throw",t,c,u)})):e.resolve(f).then((function(t){s.value=t,c(s)}),(function(t){return r("throw",t,c,u)}))}u(l.arg)}var o;a(this,"_invoke",{value:function(t,n){function i(){return new e((function(e,o){r(t,n,e,o)}))}return o=o?o.then(i,i):i()}})}function O(e,r,n){var o=y;return function(i,a){if(o===v)throw Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=j(c,n);if(u){if(u===g)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===y)throw o=m,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=v;var l=p(e,r,n);if("normal"===l.type){if(o=n.done?m:d,l.arg===g)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=m,n.method="throw",n.arg=l.arg)}}}function j(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,j(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=p(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function P(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function T(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function N(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(P,this),this.reset(!0)}function I(e){if(e||""===e){var r=e[u];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,a=function r(){for(;++o<e.length;)if(i.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return a.next=a}}throw new TypeError(n(e)+" is not iterable")}return b.prototype=x,a(S,"constructor",{value:x,configurable:!0}),a(x,"constructor",{value:b,configurable:!0}),b.displayName=f(x,s,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===b||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,x):(t.__proto__=x,f(t,s,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},C(k.prototype),f(k.prototype,l,(function(){return this})),e.AsyncIterator=k,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new k(h(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},C(S),f(S,s,"Generator"),f(S,u,(function(){return this})),f(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=I,N.prototype={constructor:N,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(T),!e)for(var r in this)"t"===r.charAt(0)&&i.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function n(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var o=this.tryEntries.length-1;o>=0;--o){var a=this.tryEntries[o],c=a.completion;if("root"===a.tryLoc)return n("end");if(a.tryLoc<=this.prev){var u=i.call(a,"catchLoc"),l=i.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return n(a.catchLoc,!0);if(this.prev<a.finallyLoc)return n(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return n(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return n(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&i.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var o=n;break}}o&&("break"===t||"continue"===t)&&o.tryLoc<=e&&e<=o.finallyLoc&&(o=null);var a=o?o.completion:{};return a.type=t,a.arg=e,o?(this.method="next",this.next=o.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),T(r),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;T(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:I(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),g}},e}function i(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,n)}return r}function a(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?i(Object(r),!0).forEach((function(e){c(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):i(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}function c(t,e,r){return(e=function(t){var e=function(t,e){if("object"!=n(t)||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var o=r.call(t,"string");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==n(e)?e:e+""}(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function u(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}var l=(0,t.createContext)(!1),s=function(e){var n=e.checkoutFormHandler,i=e.eventRegistration,c=e.emitResponse,s=(0,t.useContext)(l),f=i.onPaymentSetup,h=i.onCheckoutAfterProcessingWithError,p=i.onCheckoutAfterProcessingWithSuccess;return function(e,n,i,c,l,s){var f=(0,t.useRef)(i);(0,t.useEffect)((function(){f.current=i}),[i]),(0,t.useEffect)((function(){var t=function(){var t,e=(t=o().mark((function t(){var e,i,u,h,p,y,d,v,m,g,w,b,x,L;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(i={type:n.responseTypes.SUCCESS},u={nonce:"",notices:[],logs:[]},null===(e=f.current)||void 0===e||!e.token){t.next=20;break}return t.prev=3,h=r(),p=h.paymentTokenNonce,t.next=7,fetch("".concat(wc.wcSettings.ADMIN_URL,"admin-ajax.php?action=squaresync_credit_card_get_token_by_id&token_id=").concat(f.current.token,"&nonce=").concat(p));case 7:return y=t.sent,t.next=10,y.json();case 10:d=t.sent,v=d.success,m=d.data,u.token=v?m:"",t.next=18;break;case 16:t.prev=16,t.t0=t.catch(3);case 18:t.next=31;break;case 20:return t.prev=20,t.next=23,l(f.current.card);case 23:b=t.sent,u.nonce=b.token,null!=b&&null!==(g=b.details)&&void 0!==g&&g.card&&null!=b&&null!==(w=b.details)&&void 0!==w&&w.billing&&(u.cardData=a(a({},b.details.card),b.details.billing)),t.next=31;break;case 28:t.prev=28,t.t1=t.catch(20),console.error("Error creating nonce:",t.t1);case 31:if(!(x=u.token||u.nonce)){t.next=45;break}return t.prev=33,t.next=36,s(f.current.payments,x);case 36:L=t.sent,u.verificationToken=L.verificationToken||"",u.logs=u.logs.concat(L.log||[]),u.errors=u.notices.concat(L.errors||[]),t.next=45;break;case 42:t.prev=42,t.t2=t.catch(33),console.error("Error during buyer verification:",t.t2);case 45:return x||u.logs.length>0?i.meta={paymentMethodData:c(u)}:u.notices.length>0&&(console.log("Errors or notices found:",u.notices),i.type=n.responseTypes.ERROR,i.message=u.notices),t.abrupt("return",i);case 47:case"end":return t.stop()}}),t,null,[[3,16],[20,28],[33,42]])})),function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){u(i,n,o,a,c,"next",t)}function c(t){u(i,n,o,a,c,"throw",t)}a(void 0)}))});return function(){return e.apply(this,arguments)}}();return e(t)}),[e,n.responseTypes.SUCCESS,n.responseTypes.ERROR,l,s,c])}(f,c,s,n.getPaymentMethodData,n.createNonce,n.verifyBuyer),function(e,r,n){(0,t.useEffect)((function(){var t=function(t){var e={type:n.responseTypes.SUCCESS},r=t.processingResponse,o=r.paymentStatus,i=r.paymentDetails;return o===n.responseTypes.ERROR&&i.checkoutNotices&&(e={type:n.responseTypes.ERROR,message:JSON.parse(i.checkoutNotices),messageContext:n.noticeContexts.PAYMENTS,retry:!0}),e},o=e(t),i=r(t);return function(){o(),i()}}),[e,r,n.noticeContexts.PAYMENTS,n.responseTypes.ERROR,n.responseTypes.SUCCESS])}(h,p,c),null};function f(t){return f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},f(t)}function h(){h=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof w?e:w,a=Object.create(i.prototype),c=new N(n||[]);return o(a,"_invoke",{value:O(t,r,c)}),a}function p(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var y="suspendedStart",d="suspendedYield",v="executing",m="completed",g={};function w(){}function b(){}function x(){}var L={};l(L,a,(function(){return this}));var E=Object.getPrototypeOf,_=E&&E(E(I([])));_&&_!==r&&n.call(_,a)&&(L=_);var S=x.prototype=w.prototype=Object.create(L);function C(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function k(t,e){function r(o,i,a,c){var u=p(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==f(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function O(e,r,n){var o=y;return function(i,a){if(o===v)throw Error("Generator is already running");if(o===m){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=j(c,n);if(u){if(u===g)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===y)throw o=m,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=v;var l=p(e,r,n);if("normal"===l.type){if(o=n.done?m:d,l.arg===g)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=m,n.method="throw",n.arg=l.arg)}}}function j(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,j(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=p(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function P(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function T(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function N(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(P,this),this.reset(!0)}function I(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(f(e)+" is not iterable")}return b.prototype=x,o(S,"constructor",{value:x,configurable:!0}),o(x,"constructor",{value:b,configurable:!0}),b.displayName=l(x,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===b||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,x):(t.__proto__=x,l(t,u,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},C(k.prototype),l(k.prototype,c,(function(){return this})),e.AsyncIterator=k,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new k(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},C(S),l(S,u,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=I,N.prototype={constructor:N,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(T),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),T(r),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;T(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:I(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),g}},e}function p(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function y(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){p(i,n,o,a,c,"next",t)}function c(t){p(i,n,o,a,c,"throw",t)}a(void 0)}))}}function d(t,e,r){return(e=function(t){var e=function(t,e){if("object"!=f(t)||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var n=r.call(t,"string");if("object"!=f(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==f(e)?e:e+""}(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function v(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,c=[],u=!0,l=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(c.push(n.value),c.length!==e);u=!0);}catch(t){l=!0,o=t}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return c}}(t,e)||function(t,e){if(t){if("string"==typeof t)return m(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?m(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function m(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}function g(t){return g="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},g(t)}function w(){w=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),c=new N(n||[]);return o(a,"_invoke",{value:O(t,r,c)}),a}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var h="suspendedStart",p="suspendedYield",y="executing",d="completed",v={};function m(){}function b(){}function x(){}var L={};l(L,a,(function(){return this}));var E=Object.getPrototypeOf,_=E&&E(E(I([])));_&&_!==r&&n.call(_,a)&&(L=_);var S=x.prototype=m.prototype=Object.create(L);function C(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function k(t,e){function r(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==g(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function O(e,r,n){var o=h;return function(i,a){if(o===y)throw Error("Generator is already running");if(o===d){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=j(c,n);if(u){if(u===v)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=d,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(e,r,n);if("normal"===l.type){if(o=n.done?d:p,l.arg===v)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=d,n.method="throw",n.arg=l.arg)}}}function j(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,j(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),v;var i=f(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,v;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,v):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,v)}function P(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function T(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function N(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(P,this),this.reset(!0)}function I(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(g(e)+" is not iterable")}return b.prototype=x,o(S,"constructor",{value:x,configurable:!0}),o(x,"constructor",{value:b,configurable:!0}),b.displayName=l(x,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===b||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,x):(t.__proto__=x,l(t,u,"GeneratorFunction")),t.prototype=Object.create(S),t},e.awrap=function(t){return{__await:t}},C(k.prototype),l(k.prototype,c,(function(){return this})),e.AsyncIterator=k,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new k(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},C(S),l(S,u,"Generator"),l(S,a,(function(){return this})),l(S,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=I,N.prototype={constructor:N,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(T),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,v):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),v},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),T(r),v}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;T(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:I(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),v}},e}function b(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function x(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,c=[],u=!0,l=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(c.push(n.value),c.length!==e);u=!0);}catch(t){l=!0,o=t}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return c}}(t,e)||function(t,e){if(t){if("string"==typeof t)return L(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?L(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function L(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}var E=function(e){var n=e.children,o=e.token,i=void 0===o?null:o,a=e.defaults.postalCode,c=void 0===a?"":a,u=x((0,t.useState)(!1),2),s=u[0],f=u[1],h=x((0,t.useState)(!1),2),p=h[0],y=h[1],d=r(),v=d.applicationId,m=d.locationId;return(0,t.useEffect)((function(){if(!s){var t=function(){if(window.Square&&v&&m)try{f(window.Square.payments(v,m))}catch(t){console.error("Failed to initialize Square payments:",t)}};if(t(),!window.Square){var e=0,r=setInterval((function(){e++,window.Square?(clearInterval(r),t()):e>=20&&(clearInterval(r),console.error("Square SDK failed to load after 10 seconds"))}),500);return function(){return clearInterval(r)}}}}),[v,m,s]),(0,t.useEffect)((function(){if(s&&!p&&!i){var t=function(){var t,e=(t=w().mark((function t(){var e;return w().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,s.card({postalCode:c});case 2:e=t.sent,y(e);case 4:case"end":return t.stop()}}),t)})),function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){b(i,n,o,a,c,"next",t)}function c(t){b(i,n,o,a,c,"throw",t)}a(void 0)}))});return function(){return e.apply(this,arguments)}}();t()}}),[s,p,i,c]),s?wp.element.createElement(l.Provider,{value:{payments:s,card:p,token:i}},n):null};function _(t){return _="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_(t)}function S(){S=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),c=new N(n||[]);return o(a,"_invoke",{value:O(t,r,c)}),a}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var h="suspendedStart",p="suspendedYield",y="executing",d="completed",v={};function m(){}function g(){}function w(){}var b={};l(b,a,(function(){return this}));var x=Object.getPrototypeOf,L=x&&x(x(I([])));L&&L!==r&&n.call(L,a)&&(b=L);var E=w.prototype=m.prototype=Object.create(b);function C(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function k(t,e){function r(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==_(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function O(e,r,n){var o=h;return function(i,a){if(o===y)throw Error("Generator is already running");if(o===d){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=j(c,n);if(u){if(u===v)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=d,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(e,r,n);if("normal"===l.type){if(o=n.done?d:p,l.arg===v)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=d,n.method="throw",n.arg=l.arg)}}}function j(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,j(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),v;var i=f(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,v;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,v):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,v)}function P(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function T(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function N(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(P,this),this.reset(!0)}function I(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(_(e)+" is not iterable")}return g.prototype=w,o(E,"constructor",{value:w,configurable:!0}),o(w,"constructor",{value:g,configurable:!0}),g.displayName=l(w,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===g||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,l(t,u,"GeneratorFunction")),t.prototype=Object.create(E),t},e.awrap=function(t){return{__await:t}},C(k.prototype),l(k.prototype,c,(function(){return this})),e.AsyncIterator=k,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new k(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},C(E),l(E,u,"Generator"),l(E,a,(function(){return this})),l(E,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=I,N.prototype={constructor:N,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(T),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,v):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),v},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),T(r),v}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;T(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:I(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),v}},e}function C(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}var k=function(){var e=(0,t.useContext)(l).card,r=(0,t.useRef)(!1);return(0,t.useEffect)((function(){if(e){var t=function(){var t,n=(t=S().mark((function t(){return S().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:e.attach(r.current);case 1:case"end":return t.stop()}}),t)})),function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){C(i,n,o,a,c,"next",t)}function c(t){C(i,n,o,a,c,"throw",t)}a(void 0)}))});return function(){return n.apply(this,arguments)}}();t()}}),[e]),wp.element.createElement(React.Fragment,null,wp.element.createElement("div",{ref:r}))},O=function(e){var n=e.billing,o=e.eventRegistration,i=e.emitResponse,a=(e.shouldSavePayment,function(e){var n=arguments.length>1&&void 0!==arguments[1]&&arguments[1],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=v((0,t.useState)(!1),2),a=i[0],c=i[1],u=v((0,t.useState)(""),2),l=u[0],s=u[1],f=(0,t.useMemo)((function(){var t=n&&!o?"STORE":"CHARGE",r={billingContact:{familyName:e.billingData.last_name||"",givenName:e.billingData.first_name||"",email:e.billingData.email||"",country:e.billingData.country||"",region:e.billingData.state||"",city:e.billingData.city||"",postalCode:e.billingData.postcode||"",phone:e.billingData.phone||"",addressLines:[e.billingData.address_1||"",e.billingData.address_2||""]},intent:t};return"CHARGE"===t&&(r.amount=(e.cartTotal.value/100).toString(),r.currencyCode=e.currency.code),r}),[e.billingData,e.cartTotal.value,e.currency.code,n,o]),p=(0,t.useCallback)((function(t){var e,r,i,a=t.cardData,c=void 0===a?{}:a,u=t.nonce,l=t.verificationToken,s=t.notices,f=(t.logs,d(d(d(d(d(d(d(d(d(d(i={},"wc-squaresync_credit-card-type",(null==c?void 0:c.brand)||""),"wc-squaresync_credit-last-four",(null==c?void 0:c.last4)||""),"wc-squaresync_credit-exp-month",(null==c||null===(e=c.expMonth)||void 0===e?void 0:e.toString())||""),"wc-squaresync_credit-exp-year",(null==c||null===(r=c.expYear)||void 0===r?void 0:r.toString())||""),"wc-squaresync_credit-payment-postcode",(null==c?void 0:c.postalCode)||""),"wc-squaresync_credit-payment-nonce",u||""),"wc-squaresync_credit-payment-token",o||""),"wc-squaresync_credit-buyer-verification-token",l||""),"wc-squaresync_credit-tokenize-payment-method",n||!1),"log-data",""),d(i,"checkout-notices",s.length>0?JSON.stringify(s):""));return o&&(f.token=o),f}),[l,n,o]),m=(0,t.useCallback)(function(){var t=y(h().mark((function t(e){return h().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(o){t.next=4;break}return t.next=3,e.tokenize();case 3:return t.abrupt("return",t.sent);case 4:return t.abrupt("return",o);case 5:case"end":return t.stop()}}),t)})));return function(_x){return t.apply(this,arguments)}}(),[o]),g=(0,t.useCallback)((function(t){var e={notices:[],logs:[]};return t&&t.token?e.verificationToken=t.token:console.log("Verification token is missing from the Square response",e),e}),[]),w=(0,t.useCallback)(function(){var t=y(h().mark((function t(e,r){var n;return h().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,e.verifyBuyer(r,f);case 3:return n=t.sent,t.abrupt("return",g(n));case 7:t.prev=7,t.t0=t.catch(0),console.error("Error in verifyBuyer:",t.t0);case 10:return t.abrupt("return",!1);case 11:case"end":return t.stop()}}),t,null,[[0,7]])})));return function(e,r){return t.apply(this,arguments)}}(),[f,g]);return{handleInputReceived:(0,t.useCallback)((function(t){if("cardBrandChanged"===t.eventType){var e=t.cardBrand,n="plain";null!==e&&"unknown"!==e||(n=""),null!==r().availableCardTypes[e]&&(n=r().availableCardTypes[e]),s(n)}}),[]),isLoaded:a,setLoaded:c,getPostalCode:(0,t.useCallback)((function(){return e.billingData.postcode||""}),[e.billingData.postcode]),cardType:l,createNonce:m,verifyBuyer:w,getPaymentMethodData:p}}(n,!1));return wp.element.createElement(E,{defaults:{postalCode:a.getPostalCode()}},wp.element.createElement(k,null),wp.element.createElement(s,{checkoutFormHandler:a,eventRegistration:o,emitResponse:i}))},j=["RenderedComponent"],P=window.wc.wcBlocksRegistry,T=(P.registerPaymentMethod,P.registerExpressPaymentMethod,function(t){var e=t.RenderedComponent,r=function(t,e){if(null==t)return{};var r,n,o=function(t,e){if(null==t)return{};var r={};for(var n in t)if({}.hasOwnProperty.call(t,n)){if(e.includes(n))continue;r[n]=t[n]}return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n<i.length;n++)r=i[n],e.includes(r)||{}.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}(t,j);return wp.element.createElement(e,r)});const N={name:"squaresync_credit",paymentMethodId:"squaresync_credit",label:wp.element.createElement((function(t){var e=t.components.PaymentMethodLabel,r=t.labelText;return wp.element.createElement(e,{text:r})}),{labelText:"Credit Card"}),content:wp.element.createElement(T,{RenderedComponent:O}),edit:wp.element.createElement(T,{RenderedComponent:O}),ariaLabel:"Square",canMakePayment:function(){return!(!r().applicationId||!r().locationId)},supports:{features:r().supports,showSaveOption:!r().hasSubscription}},I=window.wp.data;function A(t){return A="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},A(t)}function G(){G=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),c=new P(n||[]);return o(a,"_invoke",{value:C(t,r,c)}),a}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var h="suspendedStart",p="suspendedYield",y="executing",d="completed",v={};function m(){}function g(){}function w(){}var b={};l(b,a,(function(){return this}));var x=Object.getPrototypeOf,L=x&&x(x(T([])));L&&L!==r&&n.call(L,a)&&(b=L);var E=w.prototype=m.prototype=Object.create(b);function _(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function S(t,e){function r(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==A(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function C(e,r,n){var o=h;return function(i,a){if(o===y)throw Error("Generator is already running");if(o===d){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=k(c,n);if(u){if(u===v)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=d,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(e,r,n);if("normal"===l.type){if(o=n.done?d:p,l.arg===v)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=d,n.method="throw",n.arg=l.arg)}}}function k(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,k(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),v;var i=f(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,v;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,v):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,v)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function j(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function T(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(A(e)+" is not iterable")}return g.prototype=w,o(E,"constructor",{value:w,configurable:!0}),o(w,"constructor",{value:g,configurable:!0}),g.displayName=l(w,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===g||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,l(t,u,"GeneratorFunction")),t.prototype=Object.create(E),t},e.awrap=function(t){return{__await:t}},_(S.prototype),l(S.prototype,c,(function(){return this})),e.AsyncIterator=S,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new S(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},_(E),l(E,u,"Generator"),l(E,a,(function(){return this})),l(E,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=T,P.prototype={constructor:P,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(j),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,v):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),v},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),j(r),v}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:T(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),v}},e}function R(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function F(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){R(i,n,o,a,c,"next",t)}function c(t){R(i,n,o,a,c,"throw",t)}a(void 0)}))}}var H=function(t){return r().ajaxUrl.replace("%%endpoint%%","square_digital_wallet_".concat(t))},M=function(){var t=F(G().mark((function t(e){return G().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",new Promise((function(t,r){return jQuery.post(H("recalculate_totals"),e,(function(e){return e.success?t(e.data):r(e.data)}))})));case 1:case"end":return t.stop()}}),t)})));return function(_x){return t.apply(this,arguments)}}(),q=function(){var t=F(G().mark((function t(e){var n,o;return G().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n={context:r().context,shipping_option:e.id,security:r().recalculateTotalNonce,is_pay_for_order_page:r().isPayForOrderPage},t.next=3,M(n);case 3:return o=t.sent,t.abrupt("return",o);case 5:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}(),D=function(){var t=F(G().mark((function t(e){var n,o;return G().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n={context:r().context,shipping_contact:e,security:r().recalculateTotalNonce,is_pay_for_order_page:r().isPayForOrderPage},t.next=3,M(n);case 3:return o=t.sent,t.abrupt("return",o);case 5:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}(),V=function(){var t=F(G().mark((function t(e){var r;return G().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,e.tokenize();case 3:if("OK"!==(r=t.sent).status){t.next=6;break}return t.abrupt("return",r);case 6:t.next=11;break;case 8:return t.prev=8,t.t0=t.catch(0),t.abrupt("return",!1);case 11:return t.abrupt("return",!1);case 12:case"end":return t.stop()}}),t,null,[[0,8]])})));return function(e){return t.apply(this,arguments)}}();function Z(t){return Z="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Z(t)}function Y(){Y=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),c=new P(n||[]);return o(a,"_invoke",{value:C(t,r,c)}),a}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var h="suspendedStart",p="suspendedYield",y="executing",d="completed",v={};function m(){}function g(){}function w(){}var b={};l(b,a,(function(){return this}));var x=Object.getPrototypeOf,L=x&&x(x(T([])));L&&L!==r&&n.call(L,a)&&(b=L);var E=w.prototype=m.prototype=Object.create(b);function _(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function S(t,e){function r(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==Z(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function C(e,r,n){var o=h;return function(i,a){if(o===y)throw Error("Generator is already running");if(o===d){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=k(c,n);if(u){if(u===v)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=d,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(e,r,n);if("normal"===l.type){if(o=n.done?d:p,l.arg===v)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=d,n.method="throw",n.arg=l.arg)}}}function k(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,k(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),v;var i=f(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,v;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,v):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,v)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function j(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function T(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(Z(e)+" is not iterable")}return g.prototype=w,o(E,"constructor",{value:w,configurable:!0}),o(w,"constructor",{value:g,configurable:!0}),g.displayName=l(w,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===g||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,l(t,u,"GeneratorFunction")),t.prototype=Object.create(E),t},e.awrap=function(t){return{__await:t}},_(S.prototype),l(S.prototype,c,(function(){return this})),e.AsyncIterator=S,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new S(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},_(E),l(E,u,"Generator"),l(E,a,(function(){return this})),l(E,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=T,P.prototype={constructor:P,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(j),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,v):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),v},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),j(r),v}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:T(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),v}},e}function B(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,c=[],u=!0,l=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(c.push(n.value),c.length!==e);u=!0);}catch(t){l=!0,o=t}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return c}}(t,e)||function(t,e){if(t){if("string"==typeof t)return U(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?U(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function U(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}function z(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function $(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){z(i,n,o,a,c,"next",t)}function c(t){z(i,n,o,a,c,"throw",t)}a(void 0)}))}}function J(t){return J="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},J(t)}function K(){K=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),c=new P(n||[]);return o(a,"_invoke",{value:C(t,r,c)}),a}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var h="suspendedStart",p="suspendedYield",y="executing",d="completed",v={};function m(){}function g(){}function w(){}var b={};l(b,a,(function(){return this}));var x=Object.getPrototypeOf,L=x&&x(x(T([])));L&&L!==r&&n.call(L,a)&&(b=L);var E=w.prototype=m.prototype=Object.create(b);function _(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function S(t,e){function r(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==J(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function C(e,r,n){var o=h;return function(i,a){if(o===y)throw Error("Generator is already running");if(o===d){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=k(c,n);if(u){if(u===v)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=d,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(e,r,n);if("normal"===l.type){if(o=n.done?d:p,l.arg===v)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=d,n.method="throw",n.arg=l.arg)}}}function k(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,k(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),v;var i=f(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,v;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,v):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,v)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function j(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function T(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(J(e)+" is not iterable")}return g.prototype=w,o(E,"constructor",{value:w,configurable:!0}),o(w,"constructor",{value:g,configurable:!0}),g.displayName=l(w,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===g||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,l(t,u,"GeneratorFunction")),t.prototype=Object.create(E),t},e.awrap=function(t){return{__await:t}},_(S.prototype),l(S.prototype,c,(function(){return this})),e.AsyncIterator=S,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new S(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},_(E),l(E,u,"Generator"),l(E,a,(function(){return this})),l(E,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=T,P.prototype={constructor:P,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(j),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,v):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),v},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),j(r),v}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:T(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),v}},e}function W(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function Q(t,e,r){return(e=function(t){var e=function(t,e){if("object"!=J(t)||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var n=r.call(t,"string");if("object"!=J(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==J(e)?e:e+""}(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function X(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,c=[],u=!0,l=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(c.push(n.value),c.length!==e);u=!0);}catch(t){l=!0,o=t}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return c}}(t,e)||function(t,e){if(t){if("string"==typeof t)return tt(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?tt(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function tt(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}var et=function(){return wp.element.createElement("svg",{width:"343",height:"50",viewBox:"0 0 343 50",fill:"none",xmlns:"http://www.w3.org/2000/svg"},wp.element.createElement("rect",{width:"343",height:"50",rx:"4",fill:"black"}),wp.element.createElement("path",{d:"M97.6482 17.68H103.048C103.622 17.68 104.162 17.78 104.668 17.98C105.188 18.1667 105.642 18.4333 106.028 18.78C106.428 19.1133 106.742 19.5133 106.968 19.98C107.195 20.4467 107.308 20.9533 107.308 21.5C107.308 22.2333 107.122 22.86 106.748 23.38C106.388 23.8867 105.928 24.2667 105.368 24.52V24.64C106.088 24.8933 106.668 25.3067 107.108 25.88C107.562 26.4533 107.788 27.1467 107.788 27.96C107.788 28.5733 107.668 29.1267 107.428 29.62C107.188 30.1133 106.862 30.54 106.448 30.9C106.035 31.2467 105.555 31.52 105.008 31.72C104.475 31.9067 103.902 32 103.288 32H97.6482V17.68ZM102.968 23.66C103.302 23.66 103.602 23.6067 103.868 23.5C104.135 23.38 104.355 23.2333 104.528 23.06C104.715 22.8733 104.855 22.6667 104.948 22.44C105.042 22.2 105.088 21.96 105.088 21.72C105.088 21.48 105.042 21.2467 104.948 21.02C104.855 20.78 104.722 20.5733 104.548 20.4C104.375 20.2133 104.162 20.0667 103.908 19.96C103.655 19.84 103.368 19.78 103.048 19.78H99.9082V23.66H102.968ZM103.288 29.9C103.648 29.9 103.968 29.84 104.248 29.72C104.528 29.6 104.762 29.44 104.948 29.24C105.135 29.04 105.275 28.8133 105.368 28.56C105.475 28.3067 105.528 28.0467 105.528 27.78C105.528 27.5133 105.475 27.26 105.368 27.02C105.275 26.7667 105.128 26.5467 104.928 26.36C104.728 26.16 104.482 26 104.188 25.88C103.908 25.76 103.582 25.7 103.208 25.7H99.9082V29.9H103.288ZM116.875 30.68H116.755C116.461 31.1467 116.041 31.54 115.495 31.86C114.961 32.1667 114.355 32.32 113.675 32.32C112.435 32.32 111.508 31.9533 110.895 31.22C110.281 30.4733 109.975 29.4867 109.975 28.26V22.2H112.195V27.96C112.195 28.8133 112.388 29.4133 112.775 29.76C113.175 30.0933 113.695 30.26 114.335 30.26C114.708 30.26 115.041 30.18 115.335 30.02C115.641 29.86 115.901 29.6467 116.115 29.38C116.328 29.1 116.488 28.7867 116.595 28.44C116.701 28.08 116.755 27.7067 116.755 27.32V22.2H118.975V32H116.875V30.68ZM124.747 31.44L120.667 22.2H123.147L125.847 28.7H125.947L128.567 22.2H131.027L124.887 36.32H122.527L124.747 31.44ZM136.589 22.2H139.009L140.909 28.98H140.989L143.189 22.2H145.489L147.669 28.98H147.749L149.629 22.2H152.009L148.869 32H146.529L144.309 25.14H144.229L142.069 32H139.729L136.589 22.2ZM154.995 20.46C154.568 20.46 154.208 20.3133 153.915 20.02C153.635 19.7267 153.495 19.3733 153.495 18.96C153.495 18.5467 153.635 18.1933 153.915 17.9C154.208 17.6067 154.568 17.46 154.995 17.46C155.408 17.46 155.755 17.6067 156.035 17.9C156.328 18.1933 156.475 18.5467 156.475 18.96C156.475 19.3733 156.328 19.7267 156.035 20.02C155.755 20.3133 155.408 20.46 154.995 20.46ZM153.875 32V22.2H156.095V32H153.875ZM159.982 24.16H158.262V22.2H159.982V19.2H162.202V22.2H164.622V24.16H162.202V28.52C162.202 28.76 162.229 28.98 162.282 29.18C162.336 29.38 162.416 29.5467 162.522 29.68C162.749 29.9333 163.036 30.06 163.382 30.06C163.596 30.06 163.762 30.0467 163.882 30.02C164.002 29.98 164.129 29.9267 164.262 29.86L164.942 31.82C164.662 31.9267 164.369 32.0067 164.062 32.06C163.756 32.1267 163.409 32.16 163.022 32.16C162.556 32.16 162.142 32.0867 161.782 31.94C161.422 31.7933 161.109 31.5933 160.842 31.34C160.269 30.7667 159.982 29.9867 159.982 29V24.16ZM167.059 17.68H169.279V21.94L169.159 23.52H169.279C169.559 23.0533 169.972 22.6667 170.519 22.36C171.065 22.04 171.672 21.88 172.339 21.88C172.979 21.88 173.532 21.98 173.999 22.18C174.465 22.3667 174.852 22.64 175.159 23C175.465 23.36 175.692 23.7933 175.839 24.3C175.985 24.7933 176.059 25.34 176.059 25.94V32H173.839V26.24C173.839 25.4267 173.639 24.84 173.239 24.48C172.852 24.12 172.359 23.94 171.759 23.94C171.372 23.94 171.025 24.0267 170.719 24.2C170.425 24.36 170.165 24.58 169.939 24.86C169.725 25.14 169.559 25.46 169.439 25.82C169.332 26.18 169.279 26.5533 169.279 26.94V32H167.059V17.68Z",fill:"white"}),wp.element.createElement("path",{d:"M213.951 24.6725V31.7485H211.69V14.2748H217.684C219.203 14.2748 220.498 14.7778 221.558 15.7836C222.641 16.7895 223.183 18.0175 223.183 19.4678C223.183 20.9532 222.641 22.1813 221.558 23.1754C220.51 24.1696 219.215 24.6608 217.684 24.6608H213.951V24.6725ZM213.951 16.4269V22.5204H217.731C218.626 22.5204 219.379 22.2164 219.968 21.6199C220.569 21.0234 220.875 20.2982 220.875 19.4795C220.875 18.6725 220.569 17.9591 219.968 17.3626C219.379 16.7427 218.638 16.4386 217.731 16.4386H213.951V16.4269Z",fill:"white"}),wp.element.createElement("path",{d:"M229.094 19.3976C230.766 19.3976 232.085 19.8421 233.05 20.731C234.016 21.6199 234.499 22.8362 234.499 24.3801V31.7485H232.344V30.0877H232.25C231.319 31.4561 230.071 32.1345 228.517 32.1345C227.186 32.1345 226.079 31.7485 225.185 30.9649C224.29 30.1813 223.842 29.2105 223.842 28.0409C223.842 26.8011 224.313 25.8187 225.255 25.0935C226.197 24.3567 227.457 23.9941 229.023 23.9941C230.366 23.9941 231.472 24.2397 232.332 24.731V24.2164C232.332 23.4327 232.026 22.7778 231.402 22.228C230.778 21.6783 230.048 21.4093 229.212 21.4093C227.952 21.4093 226.951 21.9357 226.221 23L224.231 21.7602C225.326 20.1813 226.951 19.3976 229.094 19.3976ZM226.174 28.076C226.174 28.6608 226.421 29.152 226.927 29.538C227.422 29.9239 228.011 30.1228 228.682 30.1228C229.636 30.1228 230.483 29.7719 231.225 29.0701C231.967 28.3684 232.344 27.5497 232.344 26.6023C231.637 26.0526 230.66 25.7719 229.4 25.7719C228.482 25.7719 227.716 25.9941 227.104 26.4269C226.48 26.883 226.174 27.4327 226.174 28.076Z",fill:"white"}),wp.element.createElement("path",{d:"M246.792 19.7836L239.256 37H236.924L239.727 30.9766L234.758 19.7836H237.219L240.798 28.3684H240.845L244.331 19.7836H246.792Z",fill:"white"}),wp.element.createElement("path",{d:"M204.959 23.2456C204.959 22.5134 204.893 21.8128 204.77 21.1392H195.294V24.9988L200.751 25C200.53 26.2842 199.818 27.3789 198.726 28.1087V30.6128H201.975C203.872 28.869 204.959 26.2912 204.959 23.2456Z",fill:"#4285F4"}),wp.element.createElement("path",{d:"M198.727 28.1088C197.823 28.7146 196.658 29.069 195.296 29.069C192.664 29.069 190.432 27.3076 189.632 24.9333H186.281V27.5158C187.941 30.7883 191.354 33.0339 195.296 33.0339C198.021 33.0339 200.31 32.1439 201.976 30.6117L198.727 28.1088Z",fill:"#34A853"}),wp.element.createElement("path",{d:"M189.317 23.0175C189.317 22.3509 189.428 21.7064 189.632 21.1006V18.5181H186.281C185.594 19.8713 185.208 21.3988 185.208 23.0175C185.208 24.6362 185.596 26.1637 186.281 27.5169L189.632 24.9345C189.428 24.3286 189.317 23.6842 189.317 23.0175Z",fill:"#FABB05"}),wp.element.createElement("path",{d:"M195.296 16.9649C196.783 16.9649 198.115 17.4737 199.166 18.4678L202.045 15.6105C200.297 13.993 198.017 13 195.296 13C191.355 13 187.941 15.2456 186.281 18.5181L189.632 21.1006C190.432 18.7263 192.664 16.9649 195.296 16.9649Z",fill:"#E94235"}))},rt=function(){return wp.element.createElement("svg",{width:"343",height:"50",viewBox:"0 0 343 50",fill:"none",xmlns:"http://www.w3.org/2000/svg"},wp.element.createElement("rect",{width:"343",height:"50",rx:"8",fill:"black"}),wp.element.createElement("path",{d:"M155.748 19.8275C154.411 19.8275 153.333 20.636 152.637 20.636C151.907 20.636 150.93 19.8724 149.773 19.8724C147.572 19.8724 145.337 21.7029 145.337 25.1282C145.337 27.2733 146.168 29.5306 147.19 31.0018C148.055 32.2259 148.83 33.2366 149.93 33.2366C151.02 33.2366 151.503 32.5179 152.862 32.5179C154.232 32.5179 154.546 33.2142 155.748 33.2142C156.95 33.2142 157.747 32.1248 158.499 31.0467C159.33 29.8001 159.69 28.5872 159.701 28.5311C159.634 28.5086 157.343 27.5765 157.343 24.9485C157.343 22.68 159.139 21.6693 159.241 21.5906C158.061 19.8724 156.253 19.8275 155.748 19.8275ZM155.13 18.3787C155.669 17.7161 156.051 16.8177 156.051 15.908C156.051 15.7845 156.04 15.6609 156.017 15.5599C155.141 15.5936 154.063 16.1439 153.423 16.8963C152.929 17.4691 152.457 18.3787 152.457 19.2884C152.457 19.4232 152.48 19.5692 152.491 19.6141C152.547 19.6253 152.637 19.6365 152.727 19.6365C153.524 19.6365 154.535 19.0975 155.13 18.3787ZM164.115 16.8289V33.0345H167.013V27.7225H170.528C173.807 27.7225 176.098 25.5213 176.098 22.3094C176.098 19.0413 173.886 16.8289 170.652 16.8289H164.115ZM167.013 19.2547H169.888C171.977 19.2547 173.156 20.3216 173.156 22.3094C173.156 24.241 171.943 25.3192 169.877 25.3192H167.013V19.2547ZM181.535 31.0467C180.3 31.0467 179.412 30.429 179.412 29.3958C179.412 28.3963 180.142 27.8348 181.703 27.7337L184.477 27.554V28.5311C184.477 29.9573 183.219 31.0467 181.535 31.0467ZM180.715 33.2366C182.321 33.2366 183.669 32.5403 184.354 31.3499H184.545V33.0345H187.229V24.6453C187.229 22.0399 185.454 20.5013 182.299 20.5013C179.379 20.5013 177.346 21.8826 177.121 24.0501H179.749C180.008 23.2191 180.884 22.7698 182.164 22.7698C183.669 22.7698 184.477 23.4437 184.477 24.6453V25.6785L181.31 25.8694C178.323 26.0491 176.65 27.3294 176.65 29.553C176.65 31.7991 178.345 33.2366 180.715 33.2366ZM190.329 37.493C193.081 37.493 194.395 36.4822 195.439 33.4276L199.875 20.7484H196.933L194.069 30.3392H193.878L191.003 20.7484H187.948L192.34 33.0906L192.194 33.6297C191.834 34.764 191.172 35.2132 189.992 35.2132C189.801 35.2132 189.386 35.202 189.229 35.1683V37.4481C189.408 37.4818 190.161 37.493 190.329 37.493Z",fill:"white"}),wp.element.createElement("rect",{width:"343",height:"50",rx:"8",stroke:"black"}))};const nt={name:"squaresync_credit_wallet",paymentMethodId:"squaresync_credit",content:wp.element.createElement((function(e){var n=e.billing,o=e.shippingData,i=e.onClick,a=e.onClose,c=e.onSubmit,u=e.setExpressPaymentError,l=e.emitResponse,s=e.eventRegistration,f=s.onPaymentSetup,h=s.onCheckoutFail,p=X((0,t.useState)(!1),2),y=p[0],d=p[1],v=o.needsShipping,m=X((0,t.useState)(!1),2),g=m[0],w=m[1],b=X((0,t.useState)(null),2),x=b[0],L=b[1],E=X((0,t.useState)(0),2),_=(E[0],E[1]),S=X((0,t.useState)(!1),2),C=S[0],k=S[1];(0,t.useEffect)((function(){var t=(0,I.subscribe)((function(){wp.data.select("wc/store/cart").isApplyingCoupon()||d((function(t){return!t}))}));return function(){t()}}),[]);var O=function(){var e=B((0,t.useState)(null),2),n=e[0],o=e[1],i=B((0,t.useState)(!1),2),a=i[0],c=i[1];return(0,t.useEffect)((function(){if(!n&&!a){var t=function(){var t=$(Y().mark((function t(){var e,n,i,a,u;return Y().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(e=r().applicationId,n=r().locationId,e&&n){t.next=4;break}return t.abrupt("return");case 4:c(!0),i=0,a=function(){var t=$(Y().mark((function t(){var r;return Y().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!window.Square){t.next=15;break}return t.prev=1,t.next=4,Square.payments(e,n);case 4:return r=t.sent,o(r),t.abrupt("return",!0);case 9:return t.prev=9,t.t0=t.catch(1),t.abrupt("return",!1);case 12:return t.prev=12,c(!1),t.finish(12);case 15:return t.abrupt("return",!1);case 16:case"end":return t.stop()}}),t,null,[[1,9,12,15]])})));return function(){return t.apply(this,arguments)}}(),u=function(){var t=$(Y().mark((function t(){return Y().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!(i<20)){t.next=11;break}return t.next=3,a();case 3:if(!t.sent){t.next=6;break}return t.abrupt("break",11);case 6:return i++,t.next=9,new Promise((function(t){return setTimeout(t,500)}));case 9:t.next=0;break;case 11:i>=20&&c(!1);case 12:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}(),u();case 10:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}();t()}}),[n,a]),n}(),j=function(e,n,o){var i=(0,t.useRef)(null),a=B((0,t.useState)(null),2),c=a[0],u=a[1],l=(0,t.useRef)(null),s=B((0,t.useState)(!1),2),f=s[0],h=s[1];return(0,t.useEffect)((function(){if(e&&!f){var t=function(){var t=$(Y().mark((function t(){var a,c,s,f,p,y;return Y().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(t.prev=0,a="".concat(n,"-").concat(o,"-").concat(Date.now()),!i.current||l.current!==a){t.next=4;break}return t.abrupt("return");case 4:return h(!0),t.next=7,new Promise((function(t,e){var n={context:r().context,security:r().paymentRequestNonce,is_pay_for_order_page:!1};jQuery.post(H("get_payment_request"),n,(function(r){return r.success?t(r.data):e(r.data)}))}));case 7:c=t.sent,(s=JSON.parse(c))&&(Array.isArray(s.lineItems)&&(-1!==(f=s.lineItems.findIndex((function(t){var e;return null===(e=t.label)||void 0===e?void 0:e.toLowerCase().includes("shipping")})))&&s.lineItems.splice(f,1),-1!==(p=s.lineItems.findIndex((function(t){var e;return null===(e=t.label)||void 0===e?void 0:e.toLowerCase().includes("discount")})))&&s.lineItems.splice(p,1)),s.requestBillingContact=!0,n&&(s.requestShippingAddress=!0,s.requestShippingContact=!0)),i.current?(i.current.update(s),l.current=a):(y=e.paymentRequest(s),i.current=y,u(y),l.current=a),t.next=15;break;case 13:t.prev=13,t.t0=t.catch(0);case 15:return t.prev=15,h(!1),t.finish(15);case 18:case"end":return t.stop()}}),t,null,[[0,13,15,18]])})));return function(){return t.apply(this,arguments)}}();t()}}),[e,n,o]),c}(O,v,y),P=function(e,n){var o=B((0,t.useState)(null),2),i=o[0],a=o[1],c=(0,t.useRef)(null),u=B((0,t.useState)(!1),2),l=u[0],s=u[1];return(0,t.useEffect)((function(){if(e&&n){var t=!0;return $(Y().mark((function o(){var i,u;return Y().wrap((function(o){for(;;)switch(o.prev=o.next){case 0:return o.prev=0,o.next=3,e.googlePay(n);case 3:i=o.sent,t&&(a(i),u=function(){var t=$(Y().mark((function t(){return Y().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!c.current||l){t.next=14;break}if(t.prev=1,!c.current.querySelector("#gpay-button-online-api-id")){t.next=5;break}return s(!0),t.abrupt("return");case 5:return t.next=7,i.attach(c.current,{buttonColor:r().googlePayColor||"default",buttonSizeMode:"fill",buttonType:"long"});case 7:s(!0),t.next=12;break;case 10:t.prev=10,t.t0=t.catch(1);case 12:t.next=15;break;case 14:c.current||setTimeout(u,100);case 15:case"end":return t.stop()}}),t,null,[[1,10]])})));return function(){return t.apply(this,arguments)}}(),u()),o.next=10;break;case 7:o.prev=7,o.t0=o.catch(0),o.t0.message&&o.t0.message.includes("not supported");case 10:case"end":return o.stop()}}),o,null,[[0,7]])})))(),function(){if(t=!1,i&&"function"==typeof i.destroy)try{i.destroy(),s(!1)}catch(t){}}}}),[e,n]),[i,c]}(O,j),T=X(P,2),N=T[0],A=T[1],G=function(e,n){var o=B((0,t.useState)(null),2),i=o[0],a=o[1],c=(0,t.useRef)(null);return(0,t.useEffect)((function(){if(e&&n){var t=!0;return $(Y().mark((function r(){var o;return Y().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return r.prev=0,r.next=3,e.applePay(n);case 3:o=r.sent,t&&a(o),r.next=10;break;case 7:r.prev=7,r.t0=r.catch(0),r.t0.message&&r.t0.message.includes("not registered")||r.t0.message&&r.t0.message.includes("not supported");case 10:case"end":return r.stop()}}),r,null,[[0,7]])})))(),function(){t=!1}}}),[e,n]),(0,t.useEffect)((function(){if(null!=c&&c.current&&i){var t=r().applePayColor,e=r().applePayType;"plain"!==e&&(c.current.querySelector(".text").innerText="".concat(e.charAt(0).toUpperCase()).concat(e.slice(1)," with"),c.current.classList.add("wc-square-wallet-button-with-text")),c.current.style.cssText+="-apple-pay-button-type: ".concat(e,";"),c.current.style.cssText+="-apple-pay-button-style: ".concat(t,";"),c.current.style.display="block",c.current.classList.add("wc-square-wallet-button-".concat(t))}}),[i,c]),[i,c]}(O,j),R=X(G,2),F=R[0],M=R[1],Z=function(e,r){var n=B((0,t.useState)(null),2),o=n[0],i=n[1],a=(0,t.useRef)(null),c=B((0,t.useState)(!1),2),u=c[0],l=c[1];return(0,t.useEffect)((function(){if(e&&r){var t=!0;return $(Y().mark((function n(){var o,c;return Y().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.prev=0,n.next=3,e.afterpayClearpay(r);case 3:o=n.sent,t&&(i(o),c=function(){var t=$(Y().mark((function t(){return Y().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!a.current||u){t.next=14;break}if(t.prev=1,!a.current.querySelector(".sq-ap__button")){t.next=5;break}return l(!0),t.abrupt("return");case 5:return t.next=7,o.attach(a.current,{buttonColor:"black",buttonSizeMode:"fill"});case 7:l(!0),t.next=12;break;case 10:t.prev=10,t.t0=t.catch(1);case 12:t.next=15;break;case 14:a.current||setTimeout(c,100);case 15:case"end":return t.stop()}}),t,null,[[1,10]])})));return function(){return t.apply(this,arguments)}}(),c()),n.next=10;break;case 7:n.prev=7,n.t0=n.catch(0),n.t0.message&&n.t0.message.includes("already been attached")||n.t0.message&&n.t0.message.includes("not available");case 10:case"end":return n.stop()}}),n,null,[[0,7]])})))(),function(){if(t=!1,o&&"function"==typeof o.destroy)try{o.destroy(),l(!1)}catch(t){}}}}),[e,r]),[o,a]}(O,j),U=X(Z,2),z=U[0],J=U[1];(0,t.useEffect)((function(){if(O&&j){var t=setTimeout((function(){var t=0;!et&&N&&t++,!rt&&F&&t++,!nt&&z&&t++,_(t),k(!0)}),2e3);return function(){return clearTimeout(t)}}}),[O,j,N,F,z,et,rt,nt]),function(e){(0,t.useEffect)((function(){null==e||e.addEventListener("shippingcontactchanged",(function(t){return D(t)})),null==e||e.addEventListener("afterpay_shippingaddresschanged",(function(t){return D(t)}))}),[e])}(j),function(e){(0,t.useEffect)((function(){null==e||e.addEventListener("shippingoptionchanged",(function(t){return q(t)})),null==e||e.addEventListener("afterpay_shippingoptionchanged",(function(t){return q(t)}))}),[e])}(j);var tt=function(t){var e=t||g;if(!e||!e.token)return{type:l.responseTypes.ERROR,message:"Payment token is missing. Please try again."};var r=e.details,o=e.token,i=r||{},a=i.method,c=void 0===a?"":a,u=i.card,s=void 0===u?{}:u,f=i.billing,h=void 0===f?{}:f,p=i.shipping,y=(((void 0===p?{}:p)||{}).contact,{intent:"CHARGE",amount:(n.cartTotal.value/100).toString(),currencyCode:n.currency.code,billingContact:{familyName:h.familyName||n.billingData.last_name||"",givenName:h.givenName||n.billingData.first_name||"",email:h.email||n.billingData.email||"",country:h.countryCode||n.billingData.country||"",region:h.state||n.billingData.state||"",city:h.city||n.billingData.city||"",postalCode:h.postalCode||n.billingData.postcode||"",phone:h.phone||n.billingData.phone||"",addressLines:h.addressLines||[n.billingData.address_1,n.billingData.address_2].filter(Boolean)}});return O.verifyBuyer(o,y).then((function(t){var e,r,n="wc-squaresync_credit";return{type:l.responseTypes.SUCCESS,meta:{paymentMethodData:Q(Q(Q(Q(Q(Q(Q({},"".concat(n,"-card-type"),c||""),"".concat(n,"-last-four"),(null==s?void 0:s.last4)||""),"".concat(n,"-exp-month"),(null==s||null===(e=s.expMonth)||void 0===e?void 0:e.toString())||""),"".concat(n,"-exp-year"),(null==s||null===(r=s.expYear)||void 0===r?void 0:r.toString())||""),"".concat(n,"-payment-postcode"),(null==s?void 0:s.postalCode)||""),"".concat(n,"-payment-nonce"),o||""),"".concat(n,"-buyer-verification-token"),(null==t?void 0:t.token)||"")}}})).catch((function(t){return{type:l.responseTypes.ERROR,message:t.message||"Payment processing failed"}}))};(0,t.useEffect)((function(){return function(){x&&x()}}),[x]),(0,t.useEffect)((function(){return h((function(){return x&&(x(),L(null)),a(),!0}))}),[h,x]);var et=r().googlePay.includes("no"),rt=r().applePay.includes("no"),nt=r().afterPay.includes("no");function ot(t){var e;t&&(u(""),i(),(e=K().mark((function e(){var r,n,o,i,u,l,s,h;return K().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,V(t);case 2:if(r=e.sent){e.next=7;break}a(),e.next=31;break;case 7:if(!r||!r.token){e.next=24;break}return i=(null==r||null===(n=r.details)||void 0===n?void 0:n.billing)||{},u=(null==r||null===(o=r.details)||void 0===o||null===(o=o.shipping)||void 0===o?void 0:o.contact)||{},l={email:i.email||"",first_name:i.givenName||u.givenName||"",last_name:i.familyName||u.familyName||"",company:"",address_1:i.addressLines&&i.addressLines[0]||u.addressLines&&u.addressLines[0]||"",address_2:i.addressLines&&i.addressLines[1]||u.addressLines&&u.addressLines[1]||"",city:i.city||u.city||"",state:i.state||i.region||u.region||u.state||"",postcode:i.postalCode||u.postalCode||"",country:i.countryCode||i.country||u.country||u.countryCode||"",phone:i.phone||u.phone||""},s={first_name:u.givenName||i.givenName||"",last_name:u.familyName||i.familyName||"",company:"",address_1:u.addressLines&&u.addressLines[0]||i.addressLines&&i.addressLines[0]||"",address_2:u.addressLines&&u.addressLines[1]||i.addressLines&&i.addressLines[1]||"",city:u.city||i.city||"",state:u.state||u.region||i.state||i.region||"",postcode:u.postalCode||i.postalCode||"",country:u.countryCode||u.country||i.countryCode||i.country||"",phone:u.phone||i.phone||""},e.prev=12,e.next=15,wp.data.dispatch("wc/store/cart").setBillingAddress(l);case 15:if(!v){e.next=18;break}return e.next=18,wp.data.dispatch("wc/store/cart").setShippingAddress(s);case 18:return e.next=20,new Promise((function(t){return setTimeout(t,100)}));case 20:e.next=24;break;case 22:e.prev=22,e.t0=e.catch(12);case 24:return w(r),x&&x(),h=f((function(){return tt(r)})),L((function(){return h})),e.next=30,new Promise((function(t){return setTimeout(t,50)}));case 30:c();case 31:case"end":return e.stop()}}),e,null,[[12,22]])})),function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(t){W(i,n,o,a,c,"next",t)}function c(t){W(i,n,o,a,c,"throw",t)}a(void 0)}))})())}var it=!et&&N&&wp.element.createElement("div",{tabIndex:0,role:"button",ref:A,onClick:function(){return ot(N)},className:"sws-gpay-btn sws-wallet-btn"}),at=!nt&&z&&wp.element.createElement("div",{tabIndex:0,role:"button",ref:J,onClick:function(){return ot(z)},className:"sws-afterpay-btn sws-wallet-btn"}),ct=!rt&&F&&wp.element.createElement("div",{tabIndex:0,role:"button",ref:M,onClick:function(){return ot(F)},className:"sws-applepay-btn sws-wallet-btn"},wp.element.createElement("span",{className:"text"}),wp.element.createElement("span",{className:"logo"})),ut=!et&&N||!rt&&F||!nt&&z;return C&&!ut?null:wp.element.createElement("div",{className:"sws-wallets-container ".concat(ut?"has-wallets":"")},ct,it,at)}),null),edit:wp.element.createElement((function(){return wp.element.createElement(React.Fragment,null,wp.element.createElement(et,null),wp.element.createElement(rt,null))}),null),canMakePayment:function(){var t=!(!r().applicationId||!r().locationId),e=r().isDigitalWalletsEnabled;return t&&e},supports:{features:r().supports}};function ot(t){return ot="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ot(t)}function it(){it=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),c=new P(n||[]);return o(a,"_invoke",{value:C(t,r,c)}),a}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var h="suspendedStart",p="suspendedYield",y="executing",d="completed",v={};function m(){}function g(){}function w(){}var b={};l(b,a,(function(){return this}));var x=Object.getPrototypeOf,L=x&&x(x(T([])));L&&L!==r&&n.call(L,a)&&(b=L);var E=w.prototype=m.prototype=Object.create(b);function _(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function S(t,e){function r(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==ot(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function C(e,r,n){var o=h;return function(i,a){if(o===y)throw Error("Generator is already running");if(o===d){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=k(c,n);if(u){if(u===v)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=d,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(e,r,n);if("normal"===l.type){if(o=n.done?d:p,l.arg===v)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=d,n.method="throw",n.arg=l.arg)}}}function k(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,k(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),v;var i=f(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,v;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,v):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,v)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function j(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function T(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(ot(e)+" is not iterable")}return g.prototype=w,o(E,"constructor",{value:w,configurable:!0}),o(w,"constructor",{value:g,configurable:!0}),g.displayName=l(w,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===g||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,l(t,u,"GeneratorFunction")),t.prototype=Object.create(E),t},e.awrap=function(t){return{__await:t}},_(S.prototype),l(S.prototype,c,(function(){return this})),e.AsyncIterator=S,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new S(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},_(E),l(E,u,"Generator"),l(E,a,(function(){return this})),l(E,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=T,P.prototype={constructor:P,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(j),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,v):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),v},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),j(r),v}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:T(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),v}},e}function at(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function ct(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){at(i,n,o,a,c,"next",t)}function c(t){at(i,n,o,a,c,"throw",t)}a(void 0)}))}}var ut=function(){var t=ct(it().mark((function t(e,r,n){var o;return it().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,e.verifyBuyer(r,n);case 3:return o=t.sent,t.abrupt("return",o);case 7:throw t.prev=7,t.t0=t.catch(0),console.error("Error during buyer verification:",t.t0),t.t0;case 11:case"end":return t.stop()}}),t,null,[[0,7]])})));return function(e,r,n){return t.apply(this,arguments)}}(),lt=function(){var t=ct(it().mark((function t(e){var r;return it().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return console.log("[utils.js] tokenize() called with button:",e),t.prev=1,t.next=4,e.tokenize();case 4:if(r=t.sent,console.log("[utils.js] tokenize() => tokenResult:",r),"OK"!==r.status){t.next=9;break}return console.log("[utils.js] tokenize() => status=OK => returning tokenResult"),t.abrupt("return",r);case 9:r.errors&&r.errors.length&&r.errors.forEach((function(t){console.error("Afterpay tokenization error:",t)})),t.next=15;break;case 12:t.prev=12,t.t0=t.catch(1),console.error("[utils.js] Exception during Afterpay tokenization:",t.t0);case 15:return console.error("[utils.js] tokenize() => returning false (tokenization failed)"),t.abrupt("return",!1);case 17:case"end":return t.stop()}}),t,null,[[1,12]])})));return function(e){return t.apply(this,arguments)}}();function st(t){return st="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},st(t)}function ft(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=mt(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var _n=0,n=function(){};return{s:n,n:function(){return _n>=t.length?{done:!0}:{done:!1,value:t[_n++]}},e:function(t){throw t},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,i=!0,a=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return i=t.done,t},e:function(t){a=!0,o=t},f:function(){try{i||null==r.return||r.return()}finally{if(a)throw o}}}}function ht(t,e,r){return(e=function(t){var e=function(t,e){if("object"!=st(t)||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var n=r.call(t,"string");if("object"!=st(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==st(e)?e:e+""}(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function pt(){pt=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),c=new P(n||[]);return o(a,"_invoke",{value:C(t,r,c)}),a}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var h="suspendedStart",p="suspendedYield",y="executing",d="completed",v={};function m(){}function g(){}function w(){}var b={};l(b,a,(function(){return this}));var x=Object.getPrototypeOf,L=x&&x(x(T([])));L&&L!==r&&n.call(L,a)&&(b=L);var E=w.prototype=m.prototype=Object.create(b);function _(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function S(t,e){function r(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==st(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function C(e,r,n){var o=h;return function(i,a){if(o===y)throw Error("Generator is already running");if(o===d){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=k(c,n);if(u){if(u===v)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=d,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(e,r,n);if("normal"===l.type){if(o=n.done?d:p,l.arg===v)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=d,n.method="throw",n.arg=l.arg)}}}function k(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,k(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),v;var i=f(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,v;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,v):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,v)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function j(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function T(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(st(e)+" is not iterable")}return g.prototype=w,o(E,"constructor",{value:w,configurable:!0}),o(w,"constructor",{value:g,configurable:!0}),g.displayName=l(w,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===g||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,l(t,u,"GeneratorFunction")),t.prototype=Object.create(E),t},e.awrap=function(t){return{__await:t}},_(S.prototype),l(S.prototype,c,(function(){return this})),e.AsyncIterator=S,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new S(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},_(E),l(E,u,"Generator"),l(E,a,(function(){return this})),l(E,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=T,P.prototype={constructor:P,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(j),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,v):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),v},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),j(r),v}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:T(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),v}},e}function yt(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function dt(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){yt(i,n,o,a,c,"next",t)}function c(t){yt(i,n,o,a,c,"throw",t)}a(void 0)}))}}function vt(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,c=[],u=!0,l=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(c.push(n.value),c.length!==e);u=!0);}catch(t){l=!0,o=t}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return c}}(t,e)||mt(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function mt(t,e){if(t){if("string"==typeof t)return gt(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?gt(t,e):void 0}}function gt(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}function wt(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return((parseInt(t,10)||0)/Math.pow(10,e)).toFixed(e)}function bt(){return xt.apply(this,arguments)}function xt(){return(xt=dt(pt().mark((function t(){var e,r,n,o,i,a,c,u,l,s,f,h,p,y,d,v,m,g,w;return pt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if((n=(0,I.select)("wc/store/cart").getShippingRates()||[]).length){t.next=3;break}return t.abrupt("return",[]);case 3:if(o=n[0],null!==(e=o.shipping_rates)&&void 0!==e&&e.length){t.next=6;break}return t.abrupt("return",[]);case 6:i=(0,I.select)("wc/store/cart").getCartTotals()||{},a=parseInt(i.currency_minor_unit,10)||2,c=null===(r=o.shipping_rates.find((function(t){return t.is_chosen})))||void 0===r?void 0:r.rate_id,u=[],l=ft(o.shipping_rates),t.prev=11,l.s();case 13:if((s=l.n()).done){t.next=25;break}return d=s.value,(0,I.dispatch)("wc/store/cart").selectShippingRate(d.rate_id,0),t.next=18,new Promise((function(t){return setTimeout(t,300)}));case 18:v=(0,I.select)("wc/store/cart").getCartTotals()||{},m=wt(null!==(f=v.total_price)&&void 0!==f?f:"0",a),g=wt(null!==(h=v.total_tax)&&void 0!==h?h:"0",a),w=wt(null!==(p=d.price)&&void 0!==p?p:"0",a),u.push({id:d.rate_id,label:d.name,amount:w,taxLineItems:[{id:"taxItem1",label:"Taxes",amount:g}],total:{label:null!==(y=v.total_label)&&void 0!==y?y:"Total",amount:m}});case 23:t.next=13;break;case 25:t.next=30;break;case 27:t.prev=27,t.t0=t.catch(11),l.e(t.t0);case 30:return t.prev=30,l.f(),t.finish(30);case 33:if(!c){t.next=37;break}return(0,I.dispatch)("wc/store/cart").selectShippingRate(c,0),t.next=37,new Promise((function(t){return setTimeout(t,300)}));case 37:return t.abrupt("return",u);case 38:case"end":return t.stop()}}),t,null,[[11,27,30,33]])})))).apply(this,arguments)}function Lt(t){return Lt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Lt(t)}function Et(){Et=function(){return e};var t,e={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{l({},"")}catch(t){l=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,a=Object.create(i.prototype),c=new P(n||[]);return o(a,"_invoke",{value:C(t,r,c)}),a}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=s;var h="suspendedStart",p="suspendedYield",y="executing",d="completed",v={};function m(){}function g(){}function w(){}var b={};l(b,a,(function(){return this}));var x=Object.getPrototypeOf,L=x&&x(x(T([])));L&&L!==r&&n.call(L,a)&&(b=L);var E=w.prototype=m.prototype=Object.create(b);function _(t){["next","throw","return"].forEach((function(e){l(t,e,(function(t){return this._invoke(e,t)}))}))}function S(t,e){function r(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,s=l.value;return s&&"object"==Lt(s)&&n.call(s,"__await")?e.resolve(s.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(s).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new e((function(e,o){r(t,n,e,o)}))}return i=i?i.then(o,o):o()}})}function C(e,r,n){var o=h;return function(i,a){if(o===y)throw Error("Generator is already running");if(o===d){if("throw"===i)throw a;return{value:t,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=k(c,n);if(u){if(u===v)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=d,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(e,r,n);if("normal"===l.type){if(o=n.done?d:p,l.arg===v)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=d,n.method="throw",n.arg=l.arg)}}}function k(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,k(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),v;var i=f(o,e.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,v;var a=i.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,v):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,v)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function j(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function T(e){if(e||""===e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o<e.length;)if(n.call(e,o))return r.value=e[o],r.done=!1,r;return r.value=t,r.done=!0,r};return i.next=i}}throw new TypeError(Lt(e)+" is not iterable")}return g.prototype=w,o(E,"constructor",{value:w,configurable:!0}),o(w,"constructor",{value:g,configurable:!0}),g.displayName=l(w,u,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===g||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,l(t,u,"GeneratorFunction")),t.prototype=Object.create(E),t},e.awrap=function(t){return{__await:t}},_(S.prototype),l(S.prototype,c,(function(){return this})),e.AsyncIterator=S,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new S(s(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},_(E),l(E,u,"Generator"),l(E,a,(function(){return this})),l(E,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=T,P.prototype={constructor:P,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(j),!e)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function o(n,o){return c.type="throw",c.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,v):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),v},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),j(r),v}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:T(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),v}},e}function _t(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function St(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var r=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=r){var n,o,i,a,c=[],u=!0,l=!1;try{if(i=(r=r.call(t)).next,0===e){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(c.push(n.value),c.length!==e);u=!0);}catch(t){l=!0,o=t}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return c}}(t,e)||function(t,e){if(t){if("string"==typeof t)return Ct(t,e);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Ct(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Ct(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}wp.element.createElement((function(e){var n,o=e.billing,i=e.shippingData,a=e.onClick,c=e.onClose,u=(e.onSubmit,e.setExpressPaymentError),l=e.emitResponse,s=e.eventRegistration,f=s.onPaymentSetup,h=s.onCheckoutFail,p=St((0,t.useState)(!1),2),y=p[0],d=p[1],v=i.needsShipping;(0,t.useEffect)((function(){var t=(0,I.subscribe)((function(){wp.data.select("wc/store/cart").isApplyingCoupon()||d((function(t){return!t}))}));return function(){t()}}),[]);var m,g=function(){var e=vt((0,t.useState)(null),2),n=e[0],o=e[1];return(0,t.useEffect)((function(){var t=r(),e=t.applicationId,n=t.locationId;if(window.Square)try{var i=Square.payments(e,n);o(i)}catch(t){console.error("[useSquare] Error creating payments:",t)}else console.error("[useSquare] window.Square is not available!")}),[]),n}(),w=function(e,n,o){var i=(0,t.useRef)(null),a=vt((0,t.useState)(null),2),c=a[0],u=a[1];return(0,t.useEffect)((function(){function t(){return(t=dt(pt().mark((function t(){var o,a,c,l,s;return pt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,new Promise((function(t,e){var n,o={context:r().context,security:r().paymentRequestNonce,is_pay_for_order_page:!1};jQuery.post((n="get_payment_request",r().ajaxUrl.replace("%%endpoint%%","square_digital_wallet_".concat(n))),o,(function(r){r.success?t(r.data):e(r.data)}))}));case 3:o=t.sent,a=JSON.parse(o),Array.isArray(a.lineItems)&&(-1!==(c=a.lineItems.findIndex((function(t){var e;return null===(e=t.label)||void 0===e?void 0:e.toLowerCase().includes("shipping")})))&&a.lineItems.splice(c,1),-1!==(l=a.lineItems.findIndex((function(t){var e;return null===(e=t.label)||void 0===e?void 0:e.toLowerCase().includes("discount")})))&&a.lineItems.splice(l,1)),n&&(a.requestShippingAddress=!0),i.current?i.current.update(a):(s=e.paymentRequest(a),i.current=s,u(s)),t.next=13;break;case 10:t.prev=10,t.t0=t.catch(0),console.error("Failed to create/update PaymentRequest:",t.t0);case 13:case"end":return t.stop()}}),t,null,[[0,10]])})))).apply(this,arguments)}e&&function(){t.apply(this,arguments)}()}),[e,n,o]),[c]}(g,v,y),b=St(w,1)[0],x=function(e,r){var n=vt((0,t.useState)(null),2),o=n[0],i=n[1],a=(0,t.useRef)(null);return(0,t.useEffect)((function(){e&&r?dt(pt().mark((function t(){var n;return pt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return console.log(r),t.prev=1,t.next=4,e.afterpayClearpay(r);case 4:return n=t.sent,console.log(n),t.next=8,n.attach(a.current,{buttonColor:"black",buttonSizeMode:"fill"});case 8:i(n),t.next=13;break;case 11:t.prev=11,t.t0=t.catch(1);case 13:case"end":return t.stop()}}),t,null,[[1,11]])})))():console.log("no payment")}),[e,r]),[o,a]}(g,b),L=St(x,2),E=L[0],_=L[1],S=St((0,t.useState)(!1),2),C=S[0],k=S[1];return m=b,(0,t.useRef)(!1),(0,t.useEffect)((function(){if(m&&"function"==typeof m.addEventListener){var t=function(){var t=dt(pt().mark((function t(e){var r,n,o;return pt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,e.givenName,e.familyName,null===(r=e.addressLines)||void 0===r||r[0],null===(n=e.addressLines)||void 0===n||n[1],e.city,e.state,e.postalCode,e.countryCode,e.phone,t.next=4,new Promise((function(t){return setTimeout(t,300)}));case 4:return t.next=6,bt();case 6:if((o=t.sent).length){t.next=9;break}return t.abrupt("return");case 9:return t.abrupt("return",{shippingOptions:o});case 12:t.prev=12,t.t0=t.catch(0),console.error("Error in onAfterpayShippingAddressChanged:",t.t0);case 15:case"end":return t.stop()}}),t,null,[[0,12]])})));return function(_x){return t.apply(this,arguments)}}();return m.addEventListener("afterpay_shippingaddresschanged",t),function(){"function"==typeof m.removeEventListener&&m.removeEventListener("afterpay_shippingaddresschanged",t)}}}),[m]),function(e,r,n,o,i){console.log(n);var a=function(t){var e={familyName:t.billingData.last_name||"",givenName:t.billingData.first_name||"",email:t.billingData.email||"",country:t.billingData.country||"",region:t.billingData.state||"",city:t.billingData.city||"",postalCode:t.billingData.postcode||""};t.billingData.phone&&(e.phone=t.billingData.phone);var r=[t.billingData.address_1,t.billingData.address_2].filter(Boolean);return r.length&&(e.addressLines=r),{intent:"CHARGE",amount:(t.cartTotal.value/100).toString(),currencyCode:t.currency.code,billingContact:e}}(r);(0,t.useEffect)((function(){if(n)return i((function(){function t(){return(t=dt(pt().mark((function t(){var r,i,c,u,l,s,f,h,p,y,d,v,m,g,w,b,x,L,E,_,S,C,k,O,j,P,T,N,I,A,G,R,F,H,M,q,D,V,Z,Y;return pt().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(console.log(n.token),O={type:o.responseTypes.SUCCESS},n){t.next=6;break}return console.error("[usePaymentProcessing] tokenResult is null/undefined!"),O={type:o.responseTypes.FAILURE},t.abrupt("return",O);case 6:return j=n.details,P=j.card,T=j.method,N=n.token,t.next=9,ut(e,N,a);case 9:if(I=t.sent,console.log(I),A=I.token,G="wc-squaresync_credit",R=(null==n||null===(r=n.details)||void 0===r?void 0:r.billing)||{},F=(null==n||null===(i=n.details)||void 0===i?void 0:i.shipping)||{},H=F.contact,M=void 0===H?{}:H,q=F.option,D=void 0===q?{}:q,V=null!==(c=null!==(u=null==R?void 0:R.email)&&void 0!==u?u:null==M?void 0:M.email)&&void 0!==c?c:"",Z=null!==(l=null!==(s=null==R?void 0:R.phone)&&void 0!==s?s:null==M?void 0:M.phone)&&void 0!==l?l:"",Y=null!==(f=null!==(h=null==M?void 0:M.phone)&&void 0!==h?h:null==R?void 0:R.phone)&&void 0!==f?f:"",O.meta={paymentMethodData:ht(ht(ht(ht(ht(ht(ht(ht({},"".concat(G,"-card-type"),T||""),"".concat(G,"-last-four"),(null==P?void 0:P.last4)||""),"".concat(G,"-exp-month"),(null==P||null===(p=P.expMonth)||void 0===p?void 0:p.toString())||""),"".concat(G,"-exp-year"),(null==P||null===(y=P.expYear)||void 0===y?void 0:y.toString())||""),"".concat(G,"-payment-postcode"),(null==P?void 0:P.postalCode)||""),"".concat(G,"-payment-nonce"),N||""),"".concat(G,"-buyer-verification-token"),A||""),"shipping_method",null!==(d=D.id)&&void 0!==d&&d),billingAddress:{email:V,first_name:null!==(v=R.givenName)&&void 0!==v?v:"",last_name:null!==(m=R.familyName)&&void 0!==m?m:"",company:"",address_1:R.addressLines?R.addressLines[0]:"",address_2:R.addressLines?R.addressLines[1]:"",city:null!==(g=R.city)&&void 0!==g?g:"",state:null!==(w=R.state)&&void 0!==w?w:"",postcode:null!==(b=R.postalCode)&&void 0!==b?b:"",country:null!==(x=R.countryCode)&&void 0!==x?x:"",phone:Z},shippingAddress:{first_name:null!==(L=M.givenName)&&void 0!==L?L:"",last_name:null!==(E=M.familyName)&&void 0!==E?E:"",company:"",address_1:M.addressLines?M.addressLines[0]:"",address_2:M.addressLines?M.addressLines[1]:"",city:null!==(_=M.city)&&void 0!==_?_:"",state:null!==(S=M.state)&&void 0!==S?S:"",postcode:null!==(C=M.postalCode)&&void 0!==C?C:"",country:null!==(k=M.countryCode)&&void 0!==k?k:"",phone:Y}},!wp.data.select("wc/store/cart").getNeedsShipping()){t.next=27;break}if(wp.data.select("wc/store/cart").getShippingRates().some((function(t){return t.shipping_rates.length}))){t.next=27;break}return console.error("[usePaymentProcessing] No shipping rates available => FAILURE"),O.type=o.responseTypes.FAILURE,console.log(O),t.abrupt("return",O);case 27:return console.log(O),t.abrupt("return",O);case 29:case"end":return t.stop()}}),t)})))).apply(this,arguments)}return function(){return t.apply(this,arguments)}()}));console.log("[usePaymentProcessing] no tokenResult yet, doing nothing.")}),[n])}(g,o,C,l,f),(0,t.useEffect)((function(){return h((function(){return c(),!0}))}),[h]),null===(n=r())||void 0===n||null===(n=n.afterpay)||void 0===n||n.includes("no"),wp.element.createElement(React.Fragment,null,wp.element.createElement("div",{ref:_,role:"button",tabIndex:0,className:"afterpay-button wc-square-wallet-buttons",onClick:function(){var t,e;(t=E)?(u(""),a(),(e=Et().mark((function e(){var r;return Et().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,lt(t);case 2:(r=e.sent)?k(r):(console.error("Tokenization failed in onClickHandler"),c());case 4:case"end":return e.stop()}}),e)})),function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(t){_t(i,n,o,a,c,"next",t)}function c(t){_t(i,n,o,a,c,"throw",t)}a(void 0)}))})()):console.error("Button instance is null or undefined")}}))}),null),wp.element.createElement((function(){return wp.element.createElement(React.Fragment,null,wp.element.createElement("div",null,"afterpay"))}),null),r().supports;var kt=window.wc.wcBlocksRegistry,Ot=kt.registerPaymentMethod;(0,kt.registerExpressPaymentMethod)(nt),Ot(N)})();
  • squarewoosync/trunk/build/index.asset.php

    r3428055 r3431463  
    1 <?php return array('dependencies' => array('lodash', 'moment', 'react', 'react-dom', 'wp-api-fetch', 'wp-element'), 'version' => '98d33e7bc69f5848414e');
     1<?php return array('dependencies' => array('lodash', 'moment', 'react', 'react-dom', 'wp-api-fetch', 'wp-element'), 'version' => '8da185fa53da57f908f6');
  • squarewoosync/trunk/build/index.css

    r3360355 r3431463  
    11551155  visibility: hidden;
    11561156}
     1157.static {
     1158  position: static;
     1159}
    11571160.fixed {
    11581161  position: fixed;
  • squarewoosync/trunk/includes/Payments/Blocks/WC_SquareSync_Gateway_Blocks_Support.php

    r3310892 r3431463  
    8484        : 'sq0idp-HD7Og08_uCPjxkaEgoG40Q';
    8585
    86       // Additional location sgitettings
     86      // Additional location settings
    8787      $settings = get_option('square-woo-sync_settings', []);
    8888      $locationId = isset($settings['location']) ? $settings['location'] : '';
     
    114114        'enable_apple_pay' => $this->gateway->get_option('enable_apple_pay'),
    115115        'enable_after_pay' => $this->gateway->get_option('enable_after_pay'),
     116        'enable_cash_app_pay' => $this->gateway->get_option('enable_cash_app_pay'),
    116117        'general_error'            => __('An error occurred, please try again or try an alternate form of payment.', 'woocommerce-square'),
    117118        'ajax_url'                 => \WC_AJAX::get_endpoint('%%endpoint%%'),
  • squarewoosync/trunk/includes/Payments/WC_SquareSync_Gateway.php

    r3377796 r3431463  
    33namespace Pixeldev\SquareWooSync\Payments;
    44
     5use Pixeldev\SquareWooSync\Loyalty\LoyaltyProgram;
     6use Pixeldev\SquareWooSync\Loyalty\LoyaltyRedeeming;
    57use Pixeldev\SquareWooSync\Payments\Blocks\WC_SquareSync_Gateway_Blocks_Support;
     8use Pixeldev\SquareWooSync\REST\OrdersController;
     9use Pixeldev\SquareWooSync\Security\SquareTokenManager;
    610use Pixeldev\SquareWooSync\Square\SquareHelper;
    7 use Pixeldev\SquareWooSync\REST\OrdersController;
     11use WC_Payment_Gateway_CC;  // Changed to extend WC_Payment_Gateway_CC
     12use WC_Payment_Tokens;
    813use WP_Error;
    9 use WC_Payment_Gateway_CC; // Changed to extend WC_Payment_Gateway_CC
    10 use WC_Payment_Tokens;
    1114
    1215require_once plugin_dir_path(__FILE__) . '../../vendor/autoload.php';
     
    2326  private $square_op_mode;
    2427  private $location_id;
    25 
    2628  public $page = null;
    2729  public $total_label_suffix;
     
    3739    $this->method_description = $paymentDescription ?? 'Accept payments online using Square. Credit card, Apple Pay, and Google Pay supported';
    3840
    39     // Added 'tokenization' to supports array
     41    // Added 'tokenization' and 'refunds' to supports array
    4042    $this->supports = [
    4143      'products',
     44      'refunds',
    4245      'tokenization',
    4346      // Add subscription support
     
    5962    $this->location_id = $settings['location'] ?? '';
    6063
    61     $this->square_application_id = isset($settings['environment']) && $settings['environment'] == 'sandbox'
    62       ? 'sandbox-sq0idb-LMyDEf_itd9_DZukD9RGCQ'
    63       : 'sq0idp-HD7Og08_uCPjxkaEgoG40Q';
     64    $hasStoredToken = (bool) SquareTokenManager::get();  // returns false if none
     65
     66    $isSandbox = isset($settings['environment']) && $settings['environment'] === 'sandbox';
     67
     68    if ($hasStoredToken) {
     69      // 1⃣  Use the fixed IDs when a token exists
     70      $this->square_application_id = $isSandbox
     71        ? 'sandbox-sq0idb-LMyDEf_itd9_DZukD9RGCQ'
     72        : 'sq0idp-HD7Og08_uCPjxkaEgoG40Q';
     73    } else {
     74      // 2⃣  Otherwise fall back to the user-supplied settings
     75      $this->square_application_id = $isSandbox
     76        ? $this->get_option('square_application_id_sandbox')
     77        : $this->get_option('square_application_id_live');
     78    }
     79
    6480    $this->square_op_mode = $settings['environment'] ?? 'live';
    6581
    66     $total_label_suffix       = apply_filters('woocommerce_square_payment_request_total_label_suffix', __('via WooCommerce', 'woocommerce-square'));
     82    $total_label_suffix = apply_filters('woocommerce_square_payment_request_total_label_suffix', __('via WooCommerce', 'squarewoosync-pro'));
    6783    $this->total_label_suffix = $total_label_suffix ? " ($total_label_suffix)" : '';
    6884
     
    114130    try {
    115131      // 1. Get user and saved tokens
    116       $user_id   = $renewal_order->get_user_id();
     132      $user_id = $renewal_order->get_user_id();
    117133      // Get the subscription from the renewal order
    118134      $subscriptions = wcs_get_subscriptions_for_renewal_order($renewal_order->get_id());
     
    127143      $token_id = $subscription->get_meta('_payment_method_token');
    128144
    129       if (! $token_id) {
     145      if (!$token_id) {
    130146        throw new \Exception('No valid saved token found for subscription renewal.');
    131147      }
     
    139155
    140156      // 2. Get the Square card ID from the token & the Square customer ID from user meta
    141       $square_card_id       = $payment_token->get_token();
    142       $square_customer_id   = get_user_meta($user_id, 'square_customer_id', true);
     157      $square_card_id = $payment_token->get_token();
     158      $square_customer_id = get_user_meta($user_id, 'square_customer_id', true);
    143159
    144160      // 3. Convert $amount_to_charge to the smallest currency unit (e.g. cents)
    145161      $ordersController = new OrdersController();
    146       $multiplier       = $ordersController->get_currency_multiplier();
    147       $total_amount     = intval(round($amount_to_charge * $multiplier));
    148       $currency         = $renewal_order->get_currency();
    149 
    150       $settings = get_option('square-woo-sync_settings', []);
    151       $locationId = $settings['location'];
    152       if (
    153         ! empty($settings['orders']['orderable'])
    154         && class_exists('Orderable_Location_Single_Pro')
    155         && class_exists('Orderable_Location')
    156         && method_exists('Orderable_Location', 'get_selected_location')
    157       ) {
    158         // 2) Get the ID of the selected Orderable location for this order (if set)
    159         $selected_orderable_location_id = \Orderable_Location::get_selected_location();
    160 
    161         if ($selected_orderable_location_id) {
    162           // 3) Load the Orderable location object
    163           $orderable_location_obj = new \Orderable_Location_Single_Pro($selected_orderable_location_id);
    164 
    165           // 4) The data includes location_id (the database ID from wp_orderable_locations)
    166           $orderable_db_id = $orderable_location_obj->location_data['location_id'] ?? null;
    167 
    168           // 5) See if your settings have a mapping for that Orderable location → Square location
    169           $orderable_mapping = $settings['orders']['orderable_location_mapping'] ?? [];
    170 
    171           if (! empty($orderable_db_id) && isset($orderable_mapping[$orderable_db_id])) {
    172             // Mapped Square ID
    173             $squareMappedId = $orderable_mapping[$orderable_db_id];
    174 
    175             if (! empty($squareMappedId)) {
    176               $locationId = $squareMappedId;
    177             }
    178           }
    179         }
    180       }
    181 
     162      $currency = $renewal_order->get_currency();
     163      $multiplier = $ordersController->get_currency_multiplier($currency);
     164      $total_amount = intval(round($amount_to_charge * $multiplier));
     165
     166      $ordersController = new OrdersController();
     167      $locationId = $ordersController->getLocationId($renewal_order);
    182168      // 4. Prepare the body for the Square charge request
    183169      // (Similar to your process_payment logic)
    184170      $payment_data = [
    185171        'idempotency_key' => wp_generate_uuid4(),
    186         'source_id'       => $square_card_id, // previously saved card ID
    187         'amount_money'    => [
    188           'amount'   => $total_amount,
     172        'source_id' => $square_card_id, // previously saved card ID
     173        'amount_money' => [
     174          'amount' => $total_amount,
    189175          'currency' => $currency,
    190176        ],
    191         'location_id'     => $locationId,
    192         'customer_id'     => $square_customer_id,
    193         'autocomplete'    => true,
    194         'reference_id'    => 'Subscription Renewal ' . $renewal_order->get_order_number(),
     177        'location_id' => $locationId,
     178        'customer_id' => $square_customer_id,
     179        'autocomplete' => true,
     180        'reference_id' => 'Subscription Renewal ' . $renewal_order->get_order_number(),
    195181      ];
    196182
    197183      // 5. Send the charge request to Square
    198       $squareHelper    = new SquareHelper();
     184      $squareHelper = new SquareHelper();
    199185      $charge_response = $squareHelper->square_api_request('/payments', 'POST', $payment_data, null, false);
    200186
     
    208194      $renewal_order->payment_complete($payment_id);
    209195      $renewal_order->add_order_note(sprintf(
    210         __('Subscription renewal of %1$s via Square succeeded. Transaction ID: %2$s', 'squarewoosync'),
     196        // translators: 1: formatted renewal amount; 2: Square transaction ID.
     197        __('Subscription renewal of %1$s via Square succeeded. Transaction ID: %2$s', 'squarewoosync-pro'),
    211198        wc_price($amount_to_charge),
    212199        $payment_id
     
    215202      // If something failed, mark the order as failed & add a note
    216203      $renewal_order->update_status('failed', sprintf(
    217         __('Square renewal failed: %s', 'squarewoosync'),
     204        // translators: %s is the error message returned by the exception.
     205        __('Square renewal failed: %s', 'squarewoosync-pro'),
    218206        $e->getMessage()
    219207      ));
     
    324312        'default' => 'Pay securely using your credit card.',
    325313      ],
    326 
    327314      'accepted_credit_cards' => [
    328         'title'       => 'Accepted Credit Cards',
    329         'type'        => 'multiselect',
    330         'options'     => [
    331           'visa'       => 'Visa',
     315        'title' => 'Accepted Credit Cards',
     316        'type' => 'multiselect',
     317        'options' => [
     318          'visa' => 'Visa',
    332319          'mastercard' => 'MasterCard',
    333           'amex'       => 'American Express',
    334           'discover'   => 'Discover',
    335           'jcb'        => 'JCB',
    336           'diners'     => 'Diners Club',
    337           'union'     => 'UnionPay',
     320          'amex' => 'American Express',
     321          'discover' => 'Discover',
     322          'jcb' => 'JCB',
     323          'diners' => 'Diners Club',
     324          'union' => 'UnionPay',
    338325        ],
    339         'default'     => ['visa', 'mastercard', 'amex', 'discover', 'jcb', 'diners', 'union'],
     326        'default' => ['visa', 'mastercard', 'amex', 'discover', 'jcb', 'diners', 'union'],
    340327        'description' => 'Hold control and click to select multiple',
    341 
    342328      ],
    343 
    344       'square_mode' => [
    345         'title'       => 'Environment Mode',
    346         'type'        => 'select',
    347         'description' => 'Choose the environment mode. You must also change your Square access token and location via SquareSync plugin settings <a href="/wp-admin/admin.php?page=squarewoosync#/settings/general">here</a>',
    348         'default'     =>  $settings['environment'] ?? 'live',
    349         'options'     => ['sandbox' => 'Sandbox', 'live' => 'Live'],
    350       ],
    351 
    352      
    353 
    354329      // Digital Wallets Section
    355330      'digital_wallets' => [
    356         'title'       => '<legend><h2>Digital Wallets</h2></legend>',
    357         'type'        => 'title',
     331        'title' => '<legend><h2>Digital Wallets</h2></legend>',
     332        'type' => 'title',
    358333      ],
    359334      'enable_google_pay' => [
    360         'title'       => 'Enable Google Pay',
    361         'type'        => 'checkbox',
    362         'label'       => 'Enable Google Pay as a payment method',
    363         'default'     => 'no',
     335        'title' => 'Enable Google Pay',
     336        'type' => 'checkbox',
     337        'label' => 'Enable Google Pay as a payment method',
     338        'default' => 'no',
    364339      ],
    365340      'enable_apple_pay' => [
    366         'title'       => 'Enable Apple Pay',
    367         'type'        => 'checkbox',
    368         'label'       => 'Enable Apple Pay as a payment method',
    369         'default'     => 'no',
     341        'title' => 'Enable Apple Pay',
     342        'type' => 'checkbox',
     343        'label' => 'Enable Apple Pay as a payment method',
     344        'default' => 'no',
    370345        'description' => 'Apple Pay requires domain authentication. To authorize your domain follow <a href="">this guide.</a>',
    371346      ],
    372347      'enable_after_pay' => [
    373         'title'       => 'Enable Afterpay / Clearpay',
    374         'type'        => 'checkbox',
    375         'label'       => 'Enable Afterpay / Clearpay as a payment method',
    376         'default'     => 'no',
     348        'title' => 'Enable Afterpay / Clearpay',
     349        'type' => 'checkbox',
     350        'label' => 'Enable Afterpay / Clearpay as a payment method',
     351        'default' => 'no',
    377352        'description' => 'Ensure your Square account has afterpay enabled. <a href="https://squareup.com/help/us/en/article/7770-accept-in-person-payments-with-afterpay-and-square"> Read guide here</a>',
    378353      ],
     354      // Square Gift Cards Section
     355      'square_gift_cards' => [
     356        'title' => '<legend><h2>Square Gift Cards (PRO ONLY)</h2></legend>',
     357        'type' => 'title',
     358      ],
    379359    ];
    380360  }
     
    382362  public function enqueue_scripts()
    383363  {
    384     // Bail if not cart, checkout, or account page
    385     if (! is_cart() && ! is_checkout() && ! is_account_page()) {
    386       return;
    387     }
    388 
    389364    // Always load your shared styles or scripts here
    390365    if ($this->square_op_mode === 'sandbox') {
     
    424399    }
    425400
    426     if (! $is_block_checkout) {
    427       // Enqueue your “classic”/legacy checkout scripts
    428       wp_register_script('utils-js', SQUAREWOOSYNC_URL . '/assets/js/utils.js', array('jquery'), null, true);
    429       wp_register_script('credit-card-js', SQUAREWOOSYNC_URL . '/assets/js/credit-card.js', array('jquery'), null, true);
    430       wp_register_script('wallets-js', SQUAREWOOSYNC_URL . '/assets/js/wallets.js', array('jquery'), null, true);
     401    if (!$is_block_checkout) {
     402      // Enqueue your "classic"/legacy checkout scripts
     403      // Use plugin version + filemtime for cache busting to ensure users get latest fixes
     404      $script_version = SQUAREWOOSYNC_VERSION . '.' . filemtime(SQUAREWOOSYNC_PATH . '/assets/js/utils.js');
     405
     406      wp_register_script('utils-js', SQUAREWOOSYNC_URL . '/assets/js/utils.js', array('jquery'), $script_version, true);
     407      wp_register_script('credit-card-js', SQUAREWOOSYNC_URL . '/assets/js/credit-card.js', array('jquery'), $script_version, true);
     408      // wallets-js depends on utils-js for handler functions (handleShippingOptionChanged, etc.)
     409      wp_register_script('wallets-js', SQUAREWOOSYNC_URL . '/assets/js/wallets.js', array('jquery', 'utils-js'), $script_version, true);
    431410
    432411      wp_enqueue_script('utils-js');
     
    438417        SQUAREWOOSYNC_URL . '/assets/js/square-gateway.js',
    439418        null,
    440         null,
     419        $script_version,
    441420        true
    442421      );
     
    444423      // Localize script with WooCommerce parameters
    445424      $params = array(
    446         'applicationId'       => $this->square_application_id,
    447         'locationId'          => $this->location_id,
    448         'applePayEnabled'     => $this->get_option('enable_apple_pay'),
    449         'googlePayEnabled'    => $this->get_option('enable_google_pay'),
    450         'afterPayEnabled'     => $this->get_option('enable_after_pay'),
    451         'availableCardTypes'  => $this->get_option('accepted_credit_cards'),
    452         'total'               => 0,
    453         'currency'            => get_woocommerce_currency(),
     425        'applicationId' => $this->square_application_id,
     426        'locationId' => $this->location_id,
     427        'applePayEnabled' => $this->get_option('enable_apple_pay'),
     428        'googlePayEnabled' => $this->get_option('enable_google_pay'),
     429        'afterPayEnabled' => $this->get_option('enable_after_pay'),
     430        'cashAppPayEnabled' => $this->get_option('enable_cash_app_pay'),
     431        'availableCardTypes' => $this->get_option('accepted_credit_cards'),
     432        'total' => 0,
     433        'currency' => get_woocommerce_currency(),
    454434        'paymentRequestNonce' => wp_create_nonce('wc-square-get-payment-request'),
    455         'recalculate_totals_nonce'   => wp_create_nonce('wc-square-recalculate-totals-legacy'),
    456         'context'             => $this->get_current_page(),
    457         'countryCode'         => 'AUD',
    458         'ajax_url'            => admin_url('admin-ajax.php'),
    459         'wc_ajax_url'         => \WC_AJAX::get_endpoint('%%endpoint%%'),
     435        'recalculate_totals_nonce' => wp_create_nonce('wc-square-recalculate-totals-legacy'),
     436        'context' => $this->get_current_page(),
     437        'countryCode' => 'AUD',
     438        'ajax_url' => admin_url('admin-ajax.php'),
     439        'wc_ajax_url' => \WC_AJAX::get_endpoint('%%endpoint%%'),
    460440      );
     441
     442      // Add billing data for pay-for-order pages
     443      if (is_wc_endpoint_url('order-pay')) {
     444        $order_id = absint(get_query_var('order-pay'));
     445        $order = wc_get_order($order_id);
     446        if ($order) {
     447          $params['orderBillingData'] = array(
     448            'familyName' => $order->get_billing_last_name(),
     449            'givenName' => $order->get_billing_first_name(),
     450            'email' => $order->get_billing_email(),
     451            'phone' => $order->get_billing_phone(),
     452            'country' => $order->get_billing_country(),
     453            'region' => $order->get_billing_state(),
     454            'city' => $order->get_billing_city(),
     455            'postalCode' => $order->get_billing_postcode(),
     456            'addressLines' => array_filter(array(
     457              $order->get_billing_address_1(),
     458              $order->get_billing_address_2(),
     459            )),
     460          );
     461        }
     462      }
    461463
    462464      wp_localize_script('utils-js', 'SquareConfig', $params);
     
    464466    }
    465467  }
    466 
    467468
    468469  /**
     
    477478  {
    478479    if (null === $this->page) {
    479       $is_cart    = is_cart() && ! WC()->cart->is_empty();
     480      $is_cart = is_cart() && !WC()->cart->is_empty();
    480481      $is_product = is_product() || wc_post_content_has_shortcode('product_page');
    481482      $this->page = null;
     
    507508
    508509    // 2) If it's invalid, we fallback to the legacy nonce (normal check).
    509     if (! wp_verify_nonce($_REQUEST['security'] ?? '', 'wc-square-recalculate-totals')) {
     510    if (!wp_verify_nonce($_REQUEST['security'] ?? '', 'wc-square-recalculate-totals')) {
    510511      // This call will kill the request if the legacy nonce is also invalid
    511512      check_ajax_referer('wc-square-recalculate-totals-legacy', 'security');
    512513    }
    513514
    514     if (! WC()->cart) {
    515       wp_send_json_error(__('Cart not available.', 'woocommerce-square'));
     515    if (!WC()->cart) {
     516      wp_send_json_error(__('Cart not available.', 'squarewoosync-pro'));
    516517      return;
    517518    }
    518519
    519     $chosen_methods    = WC()->session->get('chosen_shipping_methods', array());
    520     $shipping_address  = array();
    521     $payment_request   = array();
     520    $chosen_methods = WC()->session->get('chosen_shipping_methods', array());
     521    $shipping_address = array();
     522    $payment_request = array();
    522523
    523524    $is_pay_for_order_page = isset($_POST['is_pay_for_order_page'])
     
    532533    if (WC()->cart->needs_shipping() || $is_pay_for_order_page) {
    533534      // 1) Possibly parse shipping_contact and recalc shipping.
    534       if (! empty($_POST['shipping_contact'])) {
     535      if (!empty($_POST['shipping_contact'])) {
    535536        $shipping_contact = wc_clean(wp_unslash($_POST['shipping_contact']));
    536537        $shipping_address = wp_parse_args(
     
    538539          array(
    539540            'countryCode' => '',
    540             'state'       => '',
    541             'city'        => '',
    542             'postalCode'  => '',
    543             'address'     => '',
    544             'address_2'   => '',
     541            'state' => '',
     542            'city' => '',
     543            'postalCode' => '',
     544            'address' => '',
     545            'address_2' => '',
    545546          )
    546547        );
    547548
    548549        // Convert full state name to code if necessary.
    549         if (! empty($shipping_address['countryCode']) && ! empty($shipping_address['state'])) {
     550        if (!empty($shipping_address['countryCode']) && !empty($shipping_address['state'])) {
    550551          $shipping_address['state'] = self::get_state_code_by_name(
    551552            $shipping_address['countryCode'],
     
    556557        // Recalc shipping using that address.
    557558        $this->calculate_shipping($shipping_address);
    558         error_log('WooSquare: Recalculated shipping with address: ' . print_r($shipping_address, true));
    559559      }
    560560
    561561      // 2) Possibly parse shipping_option and set chosen shipping method.
    562       if (! empty($_POST['shipping_option'])) {
     562      if (!empty($_POST['shipping_option'])) {
    563563        $selected_option = wc_clean(wp_unslash($_POST['shipping_option']));
    564         $chosen_methods  = array($selected_option);
     564        $chosen_methods = array($selected_option);
    565565        $this->update_shipping_method($chosen_methods);
    566         error_log('WooSquare: Chosen shipping method updated to: ' . $selected_option);
    567566      }
    568567
    569568      // 3) Gather all shipping packages/rates.
    570569      $packages = WC()->shipping->get_packages();
    571       $packages = array_values($packages); // re-index if needed.
     570      $packages = array_values($packages);  // re-index if needed.
    572571
    573572      // We want to build an array of shippingOptions.
    574573      $payment_request['shippingOptions'] = array();
    575574
    576       if (! empty($packages)) {
     575      if (!empty($packages)) {
    577576        // Store the user's originally chosen methods & totals so we can restore after the loop.
    578577        $original_chosen_methods = $chosen_methods;
    579         $original_totals         = WC()->cart->get_totals();
     578        $original_totals = WC()->cart->get_totals();
    580579
    581580        foreach ($packages as $index => $package) {
    582581          if (empty($package['rates'])) {
    583             error_log('WooSquare: No shipping rates found for package index ' . $index);
    584582            continue;
    585583          }
     
    588586            // We want shipping cost + shipping tax for this rate.
    589587            $shipping_cost = (float) $method->cost;
    590             $shipping_tax  = ! empty($method->taxes) ? array_sum($method->taxes) : 0.0;
     588            $shipping_tax = !empty($method->taxes) ? array_sum($method->taxes) : 0.0;
    591589
    592590            // Temporarily choose THIS method, recalc totals to see the entire cart total.
     
    601599            // Build shipping option structure:
    602600            $payment_request['shippingOptions'][] = array(
    603               'id'     => $method->id,           // e.g., "flat_rate:5"
    604               'label'  => $method->get_label(),  // e.g., "Flat Rate"
    605               'amount' => number_format($shipping_cost, 2, '.', ''), // Shipping-only cost
    606 
     601              'id' => $method->id,  // e.g., "flat_rate:5"
     602              'label' => $method->get_label(),  // e.g., "Flat Rate"
     603              'amount' => number_format($shipping_cost, 2, '.', ''),  // Shipping-only cost
    607604              // Optional shipping tax breakdown
    608605              'taxLineItems' => array(
    609606                array(
    610                   'id'    => 'taxItem1',
     607                  'id' => 'taxItem1',
    611608                  'label' => 'Taxes',
    612609                  'amount' => number_format($shipping_tax, 2, '.', ''),
     
    615612              // The full cart total IF this method is chosen
    616613              'total' => array(
    617                 'label'  => 'Total',
     614                'label' => 'Total',
    618615                'amount' => number_format($cart_total_for_method, 2, '.', ''),
    619616              ),
     
    627624
    628625        // Reorder so the currently chosen method is first
    629         $chosen_method_id = ! empty($original_chosen_methods[0]) ? $original_chosen_methods[0] : '';
     626        $chosen_method_id = !empty($original_chosen_methods[0]) ? $original_chosen_methods[0] : '';
    630627        if ($chosen_method_id) {
    631628          usort($payment_request['shippingOptions'], function ($a, $b) use ($chosen_method_id) {
     
    641638
    642639        // The first shipping option is now the chosen method, store that in session again.
    643         if (! empty($payment_request['shippingOptions'])) {
     640        if (!empty($payment_request['shippingOptions'])) {
    644641          $first_id = $payment_request['shippingOptions'][0]['id'];
    645642          $this->update_shipping_method(array($first_id));
    646643          WC()->cart->calculate_totals();
    647644        }
    648 
    649         error_log('WooSquare: Final shippingOptions: ' . print_r($payment_request['shippingOptions'], true));
    650       } else {
    651         error_log('WooSquare: $packages array is empty - no shipping packages found.');
    652645      }
    653646    } else {
    654       // Cart doesn't need shipping or not pay-for-order page => no shippingOptions
    655       error_log('WooSquare: Cart does not need shipping or is not pay_for_order_page. shippingOptions = []');
    656647      $payment_request['shippingOptions'] = array();
    657648    }
    658649
    659650    // 4) Recalculate totals if not pay_for_order_page.
    660     if (! $is_pay_for_order_page) {
     651    if (!$is_pay_for_order_page) {
    661652      WC()->cart->calculate_totals();
    662653    }
     
    670661        'discount' => $order->get_discount_total(),
    671662        'shipping' => $order->get_shipping_total(),
    672         'fees'     => $order->get_total_fees(),
    673         'taxes'    => $order->get_total_tax(),
     663        'fees' => $order->get_total_fees(),
     664        'taxes' => $order->get_total_tax(),
    674665      );
    675666    }
     
    681672      $total_amount = (float) wc_get_order($order_id)->get_total();
    682673    } else {
    683       $total_amount = (float) WC()->cart->total; // or get_totals()['total']
     674      $total_amount = (float) WC()->cart->total;  // or get_totals()['total']
    684675    }
    685676
    686677    $payment_request['total'] = array(
    687       'label'  => get_bloginfo('name', 'display') . esc_html($this->total_label_suffix),
     678      'label' => get_bloginfo('name', 'display') . esc_html($this->total_label_suffix),
    688679      'amount' => number_format($total_amount, 2, '.', ''),
    689680      'pending' => false,
     
    692683    wp_send_json_success($payment_request);
    693684  }
    694 
    695 
    696 
    697685
    698686  /**
     
    766754    WC()->customer->save();
    767755
    768     $packages                                = array();
    769     $packages[0]['contents']                 = WC()->cart->get_cart();
    770     $packages[0]['contents_cost']            = 0;
    771     $packages[0]['applied_coupons']          = WC()->cart->applied_coupons;
    772     $packages[0]['user']['ID']               = get_current_user_id();
    773     $packages[0]['destination']['country']   = $address['countryCode'];
    774     $packages[0]['destination']['state']     = $address['state'];
    775     $packages[0]['destination']['postcode']  = $address['postalCode'];
    776     $packages[0]['destination']['city']      = $address['city'];
    777     $packages[0]['destination']['address']   = $address['address'];
     756    $packages = array();
     757    $packages[0]['contents'] = WC()->cart->get_cart();
     758    $packages[0]['contents_cost'] = 0;
     759    $packages[0]['applied_coupons'] = WC()->cart->applied_coupons;
     760    $packages[0]['user']['ID'] = get_current_user_id();
     761    $packages[0]['destination']['country'] = $address['countryCode'];
     762    $packages[0]['destination']['state'] = $address['state'];
     763    $packages[0]['destination']['postcode'] = $address['postalCode'];
     764    $packages[0]['destination']['city'] = $address['city'];
     765    $packages[0]['destination']['address'] = $address['address'];
    778766    $packages[0]['destination']['address_2'] = $address['address_2'];
    779767
     
    828816
    829817    $payment_request = array();
    830     $context         = ! empty($_POST['context']) ? wc_clean(wp_unslash($_POST['context'])) : '';
    831 
     818    $context = !empty($_POST['context']) ? wc_clean(wp_unslash($_POST['context'])) : '';
    832819
    833820    try {
    834821      if ('product' === $context) {
    835         $product_id = ! empty($_POST['product_id']) ? wc_clean(wp_unslash($_POST['product_id'])) : 0;
    836         $quantity   = ! empty($_POST['quantity']) ? wc_clean(wp_unslash($_POST['quantity'])) : 1;
    837         $attributes = ! empty($_POST['attributes']) ? wc_clean(wp_unslash($_POST['attributes'])) : array();
     822        $product_id = !empty($_POST['product_id']) ? wc_clean(wp_unslash($_POST['product_id'])) : 0;
     823        $quantity = !empty($_POST['quantity']) ? wc_clean(wp_unslash($_POST['quantity'])) : 1;
     824        $attributes = !empty($_POST['attributes']) ? wc_clean(wp_unslash($_POST['attributes'])) : array();
    838825
    839826        try {
     
    846833      }
    847834
    848 
    849835      if (empty($payment_request)) {
    850836        /* translators: Context (product, cart, checkout or page) */
    851         throw new \Exception(sprintf(esc_html__('Empty payment request data for %s.', 'woocommerce-square'), ! empty($context) ? $context : 'page'));
     837        throw new \Exception(sprintf(esc_html__('Empty payment request data for %s.', 'squarewoosync-pro'), !empty($context) ? $context : 'page'));
    852838      }
    853839    } catch (\Exception $e) {
     
    871857  {
    872858    // Ignoring nonce verification checks as it is already handled in the parent function.
    873     $payment_request       = array();
    874 
    875     $is_pay_for_order_page = isset($_POST['is_pay_for_order_page']) ? 'true' === sanitize_text_field(wp_unslash($_POST['is_pay_for_order_page'])) : is_wc_endpoint_url('order-pay'); // phpcs:ignore WordPress.Security.NonceVerification.Missing
    876     $order_id              = isset($_POST['order_id']) ? (int) sanitize_text_field(wp_unslash($_POST['order_id'])) : absint(get_query_var('order-pay')); // phpcs:ignore WordPress.Security.NonceVerification.Missing
     859    $payment_request = array();
     860
     861    $is_pay_for_order_page = isset($_POST['is_pay_for_order_page']) ? 'true' === sanitize_text_field(wp_unslash($_POST['is_pay_for_order_page'])) : is_wc_endpoint_url('order-pay');  // phpcs:ignore WordPress.Security.NonceVerification.Missing
     862    $order_id = isset($_POST['order_id']) ? (int) sanitize_text_field(wp_unslash($_POST['order_id'])) : absint(get_query_var('order-pay')); // phpcs:ignore WordPress.Security.NonceVerification.Missing
    877863
    878864    switch ($context) {
     
    888874      case 'checkout':
    889875        if (is_wc_endpoint_url('order-pay') || $is_pay_for_order_page) {
    890           $order           = wc_get_order($order_id);
     876          $order = wc_get_order($order_id);
    891877          $payment_request = $this->build_payment_request(
    892878            $order->get_total(),
    893879            array(
    894               'order_id'              => $order_id,
     880              'order_id' => $order_id,
    895881              'is_pay_for_order_page' => $is_pay_for_order_page,
    896882            )
     
    916902          $payment_request = $this->build_payment_request(0.01, array('billing_info' => $billing_info, 'context' => 'account'));
    917903        } else {
    918           throw new \Exception(__('Unable to retrieve customer billing information.', 'woocommerce-square'));
     904          throw new \Exception(__('Unable to retrieve customer billing information.', 'squarewoosync-pro'));
    919905        }
    920906        break;
     
    946932      $_product = apply_filters('woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key);
    947933
    948       if (! in_array($_product->get_type(), $this->supported_product_types(), true)) {
     934      if (!in_array($_product->get_type(), $this->supported_product_types(), true)) {
    949935        return false;
    950936      }
     
    1004990  public function get_product_payment_request($product_id = 0, $quantity = 1, $attributes = array(), $add_to_cart = false)
    1005991  {
    1006     $data         = array();
    1007     $items        = array();
    1008     $product_id   = ! empty($product_id) ? $product_id : get_the_ID();
    1009     $product      = wc_get_product($product_id);
     992    $data = array();
     993    $items = array();
     994    $product_id = !empty($product_id) ? $product_id : get_the_ID();
     995    $product = wc_get_product($product_id);
    1010996    $variation_id = 0;
    1011997
    1012     if (! is_a($product, 'WC_Product')) {
     998    if (!is_a($product, 'WC_Product')) {
    1013999      /* translators: product ID */
    1014       throw new \Exception(sprintf(esc_html__('Product with the ID (%d) cannot be found.', 'woocommerce-square'), absint($product_id)));
     1000      throw new \Exception(sprintf(esc_html__('Product with the ID (%d) cannot be found.', 'squarewoosync-pro'), absint($product_id)));
    10151001    }
    10161002
    10171003    $quantity = $product->is_sold_individually() ? 1 : $quantity;
    10181004
    1019     if ('variable' === $product->get_type() && ! empty($attributes)) {
    1020       $data_store   = \WC_Data_Store::load('product');
     1005    if ('variable' === $product->get_type() && !empty($attributes)) {
     1006      $data_store = \WC_Data_Store::load('product');
    10211007      $variation_id = $data_store->find_matching_product_variation($product, $attributes);
    10221008
    1023       if (! empty($variation_id)) {
     1009      if (!empty($variation_id)) {
    10241010        $product = wc_get_product($variation_id);
    10251011      }
    10261012    }
    10271013
    1028     if (! $product->has_enough_stock($quantity)) {
     1014    if (!$product->has_enough_stock($quantity)) {
    10291015      /* translators: 1: product name 2: quantity in stock */
    1030       throw new \Exception(sprintf(esc_html__('You cannot add that amount of "%1$s"; to the cart because there is not enough stock (%2$s remaining).', 'woocommerce-square'), esc_html($product->get_name()), esc_html(wc_format_stock_quantity_for_display($product->get_stock_quantity(), $product))));
    1031     }
    1032 
    1033     if (! $product->is_purchasable()) {
     1016      throw new \Exception(sprintf(esc_html__('You cannot add that amount of "%1$s"; to the cart because there is not enough stock (%2$s remaining).', 'squarewoosync-pro'), esc_html($product->get_name()), esc_html(wc_format_stock_quantity_for_display($product->get_stock_quantity(), $product))));
     1017    }
     1018
     1019    if (!$product->is_purchasable()) {
    10341020      /* translators: 1: product name */
    1035       throw new \Exception(sprintf(esc_html__('You cannot purchase "%1$s" because it is currently not available.', 'woocommerce-square'), esc_html($product->get_name())));
     1021      throw new \Exception(sprintf(esc_html__('You cannot purchase "%1$s" because it is currently not available.', 'squarewoosync-pro'), esc_html($product->get_name())));
    10361022    }
    10371023
     
    10441030    }
    10451031
    1046     $amount         = number_format($quantity * $product->get_price(), 2, '.', '');
     1032    $amount = number_format($quantity * $product->get_price(), 2, '.', '');
    10471033    $quantity_label = 1 < $quantity ? ' x ' . $quantity : '';
    10481034
    10491035    $items[] = array(
    1050       'label'   => $product->get_name() . $quantity_label,
    1051       'amount'  => $amount,
     1036      'label' => $product->get_name() . $quantity_label,
     1037      'amount' => $amount,
    10521038      'pending' => false,
    10531039    );
     
    10551041    if (wc_tax_enabled()) {
    10561042      $items[] = array(
    1057         'label'   => __('Tax', 'woocommerce-square'),
    1058         'amount'  => '0.00',
     1043        'label' => __('Tax', 'squarewoosync-pro'),
     1044        'amount' => '0.00',
    10591045        'pending' => false,
    10601046      );
     
    10621048
    10631049    $data['requestShippingContact'] = $product->needs_shipping();
    1064     $data['lineItems']              = $items;
     1050    $data['lineItems'] = $items;
    10651051
    10661052    return $this->build_payment_request($amount, $data);
     
    10761062  public function build_payment_request($data = [])
    10771063  {
    1078     if (! WC()->cart) {
     1064    if (!WC()->cart) {
    10791065      throw new \Exception('Cart not available.');
    10801066    }
    10811067
    1082     $is_pay_for_order_page = ! empty($data['is_pay_for_order_page']) ? $data['is_pay_for_order_page'] : false;
    1083     $order_id              = ! empty($data['order_id']) ? $data['order_id'] : 0;
     1068    $is_pay_for_order_page = !empty($data['is_pay_for_order_page']) ? $data['is_pay_for_order_page'] : false;
     1069    $order_id = !empty($data['order_id']) ? $data['order_id'] : 0;
    10841070
    10851071    // Check if shipping is needed.
    10861072    $request_shipping_address = false;
    1087     if (! $is_pay_for_order_page) {
     1073    if (!$is_pay_for_order_page) {
    10881074      $request_shipping_address = WC()->cart->needs_shipping();
    10891075    }
     
    10911077    // Base country & currency
    10921078    $default_country = get_option('woocommerce_default_country', 'AU');
    1093     $country_bits    = explode(':', $default_country);
    1094     $country_only    = strtoupper($country_bits[0]);
    1095     $currency_code   = get_woocommerce_currency() ?: 'AUD';
     1079    $country_bits = explode(':', $default_country);
     1080    $country_only = strtoupper($country_bits[0]);
     1081    $currency_code = get_woocommerce_currency() ?: 'AUD';
    10961082
    10971083    // Merge defaults.
     
    11021088        'requestShippingAddress' => $request_shipping_address,
    11031089        'requestShippingContact' => $request_shipping_address,
    1104         'requestEmailAddress'    => true,
    1105         'requestBillingContact'  => true,
    1106         'countryCode'            => $country_only,
    1107         'currencyCode'           => $currency_code,
     1090        'requestEmailAddress' => true,
     1091        'requestBillingContact' => true,
     1092        'countryCode' => $country_only,
     1093        'currencyCode' => $currency_code,
    11081094      ]
    11091095    );
     
    11171103      // Store original shipping method selection & totals so we can restore it
    11181104      $original_chosen_methods = WC()->session->get('chosen_shipping_methods');
    1119       $original_cart_totals    = WC()->cart->get_totals();
     1105      $original_cart_totals = WC()->cart->get_totals();
    11201106
    11211107      $packages = WC()->shipping->get_packages();
    11221108
    1123       if (! empty($packages[0]['rates'])) {
     1109      if (!empty($packages[0]['rates'])) {
    11241110        foreach ($packages[0]['rates'] as $method) {
    11251111          // Shipping cost & taxes for this method
    11261112          $shipping_cost = (float) $method->cost;
    1127           $shipping_tax  = ! empty($method->taxes) ? array_sum($method->taxes) : 0;
     1113          $shipping_tax = !empty($method->taxes) ? array_sum($method->taxes) : 0;
    11281114
    11291115          // Temporarily set this shipping method, then force WooCommerce
     
    11331119
    11341120          // Grab the newly computed total
    1135           $recalc_totals        = WC()->cart->get_totals();
     1121          $recalc_totals = WC()->cart->get_totals();
    11361122          $cart_total_for_method = isset($recalc_totals['total']) ? (float) $recalc_totals['total'] : 0.0;
    11371123
    11381124          // Build the shipping option array
    11391125          $shipping_options[] = [
    1140             'id'     => $method->id,  // e.g. "flat_rate:1"
    1141             'label'  => $method->get_label(),
    1142             'amount' => number_format($shipping_cost, 2, '.', ''), // shipping-only cost
    1143 
     1126            'id' => $method->id,  // e.g. "flat_rate:1"
     1127            'label' => $method->get_label(),
     1128            'amount' => number_format($shipping_cost, 2, '.', ''),  // shipping-only cost
    11441129            // Optionally show shipping tax:
    11451130            'taxLineItems' => [
    11461131              [
    1147                 'id'    => 'taxItem1',
     1132                'id' => 'taxItem1',
    11481133                'label' => 'Taxes',
    11491134                'amount' => number_format($shipping_tax, 2, '.', ''),
     
    11521137            // Show the total cart price if this shipping method is selected
    11531138            'total' => [
    1154               'label'  => 'Total',
     1139              'label' => 'Total',
    11551140              'amount' => number_format($cart_total_for_method, 2, '.', ''),
    11561141            ],
     
    11641149
    11651150      // Sort chosen shipping method to the top if you wish
    1166       if (! empty($original_chosen_methods[0])) {
     1151      if (!empty($original_chosen_methods[0])) {
    11671152        usort($shipping_options, function ($a, $b) use ($original_chosen_methods) {
    11681153          return ($a['id'] === $original_chosen_methods[0]) ? -1 : 1;
     
    11751160    // Now that we've restored the original method, get the final cart total
    11761161    // which includes items, shipping, taxes, fees, discounts, etc.
    1177     $restored_totals   = WC()->cart->get_totals();
    1178     $final_cart_total  = isset($restored_totals['total']) ? (float) $restored_totals['total'] : 0.0;
     1162    $restored_totals = WC()->cart->get_totals();
     1163    $final_cart_total = isset($restored_totals['total']) ? (float) $restored_totals['total'] : 0.0;
    11791164
    11801165    // Build the top-level PaymentRequest total
    11811166    $data['total'] = [
    11821167      // E.g. "Your Site — Total"
    1183       'label'   => get_bloginfo('name', 'display') . $this->total_label_suffix,
    1184       'amount'  => number_format($final_cart_total, 2, '.', ''),
     1168      'label' => get_bloginfo('name', 'display') . $this->total_label_suffix,
     1169      'amount' => number_format($final_cart_total, 2, '.', ''),
    11851170      'pending' => false,
    11861171    ];
     
    11911176    return $data;
    11921177  }
    1193 
    1194 
    11951178
    11961179  /**
     
    12031186  public function get_cart_totals()
    12041187  {
    1205     if (! isset(WC()->cart)) {
     1188    if (!isset(WC()->cart)) {
    12061189      throw new \Exception('Cart data cannot be found.');
    12071190    }
     
    12111194      'discount' => WC()->cart->get_cart_discount_total(),
    12121195      'shipping' => WC()->cart->shipping_total,
    1213       'fees'     => WC()->cart->fee_total,
    1214       'taxes'    => WC()->cart->tax_total + WC()->cart->shipping_tax_total,
     1196      'fees' => WC()->cart->fee_total,
     1197      'taxes' => WC()->cart->tax_total + WC()->cart->shipping_tax_total,
    12151198    );
    12161199  }
     
    12191202  {
    12201203    // If no totals are provided, get them from the cart.
    1221     $totals     = empty($totals) ? $this->get_cart_totals() : $totals;
     1204    $totals = empty($totals) ? $this->get_cart_totals() : $totals;
    12221205    $line_items = array();
    1223     $order_id   = isset($_POST['order_id']) ? (int) sanitize_text_field(wp_unslash($_POST['order_id'])) : absint(get_query_var('order-pay')); // phpcs:ignore WordPress.Security.NonceVerification.Missing
     1206    $order_id = isset($_POST['order_id']) ? (int) sanitize_text_field(wp_unslash($_POST['order_id'])) : absint(get_query_var('order-pay')); // phpcs:ignore WordPress.Security.NonceVerification.Missing
    12241207
    12251208    // Determine whether we are working with an order or the current cart
    12261209    if ($order_id) {
    1227       $order    = wc_get_order($order_id);
     1210      $order = wc_get_order($order_id);
    12281211      $iterable = $order->get_items();
    12291212    } else {
     
    12381221      // Add a line item for each product
    12391222      $line_items[] = array(
    1240         'label'   => $order_id ? $item->get_name() : $item['data']->get_name(),
    1241         'amount'  => number_format($amount, 2, '.', ''),
     1223        'label' => $order_id ? $item->get_name() : $item['data']->get_name(),
     1224        'amount' => number_format($amount, 2, '.', ''),
    12421225        'pending' => false,
    12431226      );
     
    12471230    if (isset($totals['shipping'])) {
    12481231      $line_items[] = array(
    1249         'label'   => __('Shipping', 'woocommerce-square'),
    1250         'amount'  => number_format($totals['shipping'], 2, '.', ''),
     1232        'label' => __('Shipping', 'squarewoosync-pro'),
     1233        'amount' => number_format($totals['shipping'], 2, '.', ''),
    12511234        'pending' => false,
    12521235      );
     
    12561239    if (isset($totals['taxes']) && $totals['taxes'] > 0) {
    12571240      $line_items[] = array(
    1258         'label'   => __('Tax', 'woocommerce-square'),
    1259         'amount'  => number_format($totals['taxes'], 2, '.', ''),
     1241        'label' => __('Tax', 'squarewoosync-pro'),
     1242        'amount' => number_format($totals['taxes'], 2, '.', ''),
    12601243        'pending' => false,
    12611244      );
     
    12651248    if (isset($totals['discount']) && $totals['discount'] > 0) {
    12661249      $line_items[] = array(
    1267         'label'   => __('Discount', 'woocommerce-square'),
    1268         'amount'  => '-' . number_format(abs($totals['discount']), 2, '.', ''), // Ensure discount is negative
     1250        'label' => __('Discount', 'squarewoosync-pro'),
     1251        'amount' => '-' . number_format(abs($totals['discount']), 2, '.', ''), // Ensure discount is negative
    12691252        'pending' => false,
    12701253      );
     
    12741257    if (isset($totals['fees']) && $totals['fees'] > 0) {
    12751258      $line_items[] = array(
    1276         'label'   => __('Fees', 'woocommerce-square'),
    1277         'amount'  => number_format($totals['fees'], 2, '.', ''),
     1259        'label' => __('Fees', 'squarewoosync-pro'),
     1260        'amount' => number_format($totals['fees'], 2, '.', ''),
    12781261        'pending' => false,
    12791262      );
     
    12921275    $nonce = isset($_GET['nonce']) ? sanitize_text_field(wp_unslash($_GET['nonce'])) : false;
    12931276
    1294     if (! wp_verify_nonce($nonce, 'payment_token_nonce')) {
    1295       wp_send_json_error(esc_html__('Nonce verification failed.', 'woocommerce-square'));
     1277    if (!wp_verify_nonce($nonce, 'payment_token_nonce')) {
     1278      wp_send_json_error(esc_html__('Nonce verification failed.', 'squarewoosync-pro'));
    12961279    }
    12971280
    12981281    $token_id = isset($_GET['token_id']) ? absint(wp_unslash($_GET['token_id'])) : false;
    12991282
    1300     if (! $token_id) {
    1301       wp_send_json_error(esc_html__('Token ID missing.', 'woocommerce-square'));
     1283    if (!$token_id) {
     1284      wp_send_json_error(esc_html__('Token ID missing.', 'squarewoosync-pro'));
    13021285    }
    13031286
     
    13051288
    13061289    if (is_null($token_obj)) {
    1307       wp_send_json_error(esc_html__('No payment token exists for this ID.', 'woocommerce-square'));
     1290      wp_send_json_error(esc_html__('No payment token exists for this ID.', 'squarewoosync-pro'));
    13081291    }
    13091292
     
    13331316      // Display the 'Save payment method' checkbox only on Checkout page
    13341317      if (
    1335         ! class_exists('WC_Subscriptions_Cart') ||
    1336         ! \WC_Subscriptions_Cart::cart_contains_subscription()
     1318        !class_exists('WC_Subscriptions_Cart') ||
     1319        !\WC_Subscriptions_Cart::cart_contains_subscription()
    13371320      ) {
    13381321        if ($this->supports('tokenization') && is_user_logged_in()) {
     
    13421325    }
    13431326  }
    1344 
    1345 
    1346 
    13471327
    13481328  /**
     
    13571337      <input type="hidden" name="nonce_sec" value="<?php echo esc_attr($nonce_sec); ?>">
    13581338      <div id="square-credit-card-fields">
    1359         <div class="wallets-container" style="display: flex; column-gap: 1rem; margin-bottom: 1rem; flex-wrap: wrap;">
    1360           <div id="google-pay-button"></div>
    1361           <div id="apple-pay-button" class="apple-pay-button squaresync-wallet-buttons" role="button" style="height: 40px; width: 240px; display: none;">
     1339        <div class="sws-legacy-wallets" style="display: none;">
     1340          <div id="sws-gpay-legacy" style="display: none;"></div>
     1341          <div id="sws-applepay-legacy" class="sws-applepay-btn sws-wallet-btn" role="button" style="height: 40px; display: none;">
    13621342            <span class="text"></span>
    13631343            <span class="logo"></span>
    13641344          </div>
     1345          <div id="sws-cashapp-legacy" style="display: none;"></div>
    13651346        </div>
    13661347
     
    13831364  ?>
    13841365    <form id="payment-form">
    1385 
    1386       <div class="wallets-container" style="display: flex; column-gap: 1rem; margin-bottom: 1rem; flex-wrap: wrap;">
    1387         <div id="afterpay-button"></div>
    1388         <div id="google-pay-button"></div>
    1389         <div id="apple-pay-button" class="apple-pay-button squaresync-wallet-buttons" role="button" style="height: 40px; width: 240px; display: none;">
     1366      <div id="gift-card-container"></div>
     1367      <input type="hidden" id="squaresync_gift_card_nonce" name="squaresync_gift_card_nonce" value="">
     1368
     1369
     1370      <div class="sws-legacy-wallets" style="display: none;">
     1371        <div id="sws-afterpay-legacy" style="display: none;"></div>
     1372        <div id="sws-gpay-legacy" style="display: none;"></div>
     1373        <div id="sws-applepay-legacy" class="sws-applepay-btn sws-wallet-btn" role="button" style="height: 40px; display: none;">
    13901374          <span class="text"></span>
    13911375          <span class="logo"></span>
    13921376        </div>
     1377        <div id="sws-cashapp-legacy" style="display: none;"></div>
    13931378      </div>
    13941379
     
    14021387  }
    14031388
    1404 
    14051389  public function process_payment($order_id)
    14061390  {
     1391    error_log("[SquareSync Gateway] Starting payment processing for Order #{$order_id}");
     1392
    14071393    try {
    1408       $order             = wc_get_order($order_id);
    1409       $settings          = get_option('square-woo-sync_settings', []);
    1410       $squareHelper      = new SquareHelper();
    1411       $ordersController  = new OrdersController();
    1412       $multiplier        = $ordersController->get_currency_multiplier();
    1413       $user_id           = $order->get_user_id();
     1394      $order = wc_get_order($order_id);
     1395      $settings = get_option('square-woo-sync_settings', []);
     1396
     1397      error_log("[SquareSync Gateway] Order #{$order_id}: Order object retrieved, total: " . $order->get_total());
     1398
     1399      // Validate pickup date/time if required
     1400      $order_settings = $settings['orders'] ?? [];
     1401      if (
     1402        isset($order_settings['enablePickupDateTime']) &&
     1403        $order_settings['enablePickupDateTime'] === true &&
     1404        isset($order_settings['requirePickupDateTime']) &&
     1405        $order_settings['requirePickupDateTime'] === true
     1406      ) {
     1407        // Check if this is a pickup order
     1408        $shipping_methods = $order->get_shipping_methods();
     1409        $pickup_methods = $order_settings['pickupMethod'] ?? [];
     1410
     1411        // Ensure pickup_methods is an array
     1412        if (!is_array($pickup_methods)) {
     1413          $pickup_methods = !empty($pickup_methods) ? [$pickup_methods] : [];
     1414        }
     1415
     1416        foreach ($shipping_methods as $shipping_method) {
     1417          $method_id = $shipping_method->get_method_id();
     1418
     1419          // Check if this shipping method is a pickup method
     1420          $is_pickup = false;
     1421          foreach ($pickup_methods as $pickup_method) {
     1422            $pickup_method_id = explode(':', $pickup_method)[0];
     1423            if ($method_id === $pickup_method_id) {
     1424              $is_pickup = true;
     1425              break;
     1426            }
     1427          }
     1428
     1429          if ($is_pickup) {
     1430            // This is a pickup order - validate that date/time are set
     1431            $pickup_date = WC()->session->get('pickup_date', '');
     1432            $pickup_time = WC()->session->get('pickup_time', '');
     1433
     1434            if (empty($pickup_date) || empty($pickup_time)) {
     1435              wc_add_notice(
     1436                __('Please select a pickup date and time before completing your order.', 'squarewoosync-pro'),
     1437                'error'
     1438              );
     1439              return [
     1440                'result' => 'failure',
     1441                'redirect' => ''
     1442              ];
     1443            }
     1444
     1445            // Date and time are valid, proceed
     1446            break;
     1447          }
     1448        }
     1449      }
     1450
     1451      $squareHelper = new SquareHelper();
     1452      $ordersController = new OrdersController();
     1453      $multiplier = $ordersController->get_currency_multiplier($order->get_currency());
     1454      $user_id = $order->get_user_id();
     1455      $locationId = $ordersController->getLocationId($order);
     1456
     1457      // 1) Check for an existing Gift Card in session
     1458      $gift_card_id = WC()->session->get('applied_gift_card_id', '');
     1459      $gift_card_amount = (float) WC()->session->get('applied_gift_card_amount', 0);
     1460      $gift_card_amount_cents = intval(round($gift_card_amount * $multiplier));
    14141461
    14151462      // 2) Payment token from POST if using a saved card or new token
     
    14171464        ? wc_clean($_POST['wc-' . $this->id . '-payment-token'])
    14181465        : '';
    1419 
    14201466
    14211467      /**
     
    14251471       */
    14261472      if (
    1427         class_exists('WC_Subscriptions')
    1428         && wcs_order_contains_subscription($order) // If the order has a subscription
     1473        class_exists('WC_Subscriptions') &&
     1474        wcs_order_contains_subscription($order) // If the order has a subscription
    14291475      ) {
    14301476        // If they're NOT using an existing saved token (i.e. $token_id = '' or 'new'),
     
    14321478        if (empty($token_id) || 'new' === $token_id) {
    14331479          $_POST['wc-' . $this->id . '-new-payment-method'] = 'true';
    1434           $_POST['wc-squaresync_credit-new-payment-method']  = '1';
     1480          $_POST['wc-squaresync_credit-new-payment-method'] = '1';
    14351481        }
    14361482      }
     
    14461492      );
    14471493
     1494      // Debug logs removed - wallet payment processing
     1495
    14481496      // We'll keep a reference to the WC_Payment_Token_CC object if it exists
    14491497      $payment_token = null;
    1450       $square_token  = '';
     1498      $square_token = '';
    14511499
    14521500      // 3) Determine if order total is > 0
    14531501      $total_amount = intval(round($order->get_total() * $multiplier));
    1454       $currency     = $order->get_currency();
     1502      $currency = $order->get_currency();
    14551503
    14561504      // If user chose an existing saved token, load it
     
    14591507
    14601508        if (!$payment_token || $payment_token->get_user_id() !== get_current_user_id()) {
    1461           wc_add_notice(__('Invalid payment method. Please try again.', 'squarewoosync'), 'error');
     1509          wc_add_notice(__('Invalid payment method. Please try again.', 'squarewoosync-pro'), 'error');
    14621510          return;
    14631511        }
     
    14741522
    14751523      // 4) Retrieve or create the Square customer ID
     1524      error_log("[SquareSync Gateway] Order #{$order_id}: Retrieving or creating Square customer");
    14761525      $square_customer_id = $ordersController->getOrCreateSquareCustomer($order, $squareHelper);
    14771526      if (!$square_customer_id) {
    1478         error_log("Warning: Square customer ID not available for Order ID: $order_id.");
     1527        error_log("[SquareSync Gateway] WARNING: Square customer ID not available for Order #{$order_id}");
     1528      } else {
     1529        error_log("[SquareSync Gateway] Order #{$order_id}: Square customer ID: {$square_customer_id}");
    14791530      }
    14801531      if ($user_id) {
     
    14821533      }
    14831534
    1484       // 5) Create a Square order for record-keeping or loyalty
    1485       $square_order_response = $this->attempt_create_square_order(
    1486         $ordersController,
    1487         $order,
    1488         $square_customer_id,
    1489         $squareHelper,
    1490         $order_id
    1491       );
    1492       if (!$square_order_response) {
    1493         error_log("Warning: Square order could not be created for Order ID: $order_id.");
    1494       }
    1495 
    1496       // Possibly do rounding adjustment
    1497       $square_order_net_amount_due = isset($square_order_response['data']['order']['net_amount_due_money']['amount'])
    1498         ? intval($square_order_response['data']['order']['net_amount_due_money']['amount'])
    1499         : 0;
    1500 
    1501       if ($square_order_net_amount_due !== $total_amount) {
    1502         $rounding_adjustment = $square_order_net_amount_due - $total_amount;
    1503         $service_charge = [
    1504           'name'              => 'Rounding Adjustment',
    1505           'calculation_phase' => 'TOTAL_PHASE',
    1506           'amount_money'      => [
    1507             'amount'   => $rounding_adjustment * $multiplier,
    1508             'currency' => $currency,
    1509           ],
    1510           'taxable'  => false,
    1511           'scope'    => 'ORDER',
    1512         ];
    1513 
    1514         $settings = get_option('square-woo-sync_settings', []);
    1515         $locationId = $settings['location'];
    1516 
     1535      // 5) Check if order splitting is enabled and applicable
     1536      $split_orders_enabled = !empty($settings['orders']['splitByProductLocations']);
     1537
     1538      // Check if this is a local pickup order - if so, disable splitting
     1539      $is_pickup_order = false;
     1540      if ($split_orders_enabled) {
     1541        $shipping_methods = $order->get_shipping_methods();
     1542        $pickup_methods = $settings['orders']['pickupMethod'] ?? [];
     1543
     1544        // Ensure pickup_methods is an array
     1545        if (!is_array($pickup_methods)) {
     1546          $pickup_methods = !empty($pickup_methods) ? [$pickup_methods] : [];
     1547        }
     1548
     1549        foreach ($shipping_methods as $shipping_method) {
     1550          $method_id = $shipping_method->get_method_id();
     1551
     1552          // Check if this shipping method is a pickup method
     1553          foreach ($pickup_methods as $pickup_method) {
     1554            $pickup_method_id = explode(':', $pickup_method)[0];
     1555            if ($method_id === $pickup_method_id) {
     1556              $is_pickup_order = true;
     1557              break 2; // Break out of both loops
     1558            }
     1559          }
     1560        }
     1561
     1562        // Disable splitting for pickup orders
     1563        if ($is_pickup_order) {
     1564          $split_orders_enabled = false;
     1565          error_log("Order #{$order_id}: Local pickup detected. Disabling order splitting.");
     1566        }
     1567      }
     1568
     1569      $square_order_response = null;
     1570
     1571      if ($split_orders_enabled) {
     1572        // SPLIT ORDER MODE: Take payment first, then queue background job
     1573        // This allows checkout to complete quickly without waiting for inventory checks
     1574        error_log("[SquareSync Gateway] Order #{$order_id}: SPLIT ORDER MODE enabled");
     1575
     1576        // Store pending payment metadata for background job
     1577        $order->update_meta_data('_square_payment_id_pending', 'PENDING');
     1578        $order->update_meta_data('_square_order_pending_split', true);
     1579        $order->save();
     1580
     1581        // Skip creating Square order here - will be done in background
     1582        error_log("[SquareSync Gateway] Order #{$order_id}: Square order creation deferred to background job");
     1583      } else {
     1584        // NORMAL MODE: Create Square order immediately
     1585        error_log("[SquareSync Gateway] Order #{$order_id}: NORMAL MODE - Creating Square order immediately");
     1586        $square_order_response = $this->attempt_create_square_order(
     1587          $ordersController,
     1588          $order,
     1589          $square_customer_id,
     1590          $squareHelper,
     1591          $order_id,
     1592          $locationId
     1593        );
     1594        if (!$square_order_response) {
     1595          error_log("[SquareSync Gateway] WARNING: Square order could not be created for Order #{$order_id}");
     1596        } else {
     1597          error_log("[SquareSync Gateway] Order #{$order_id}: Square order created successfully");
     1598        }
     1599      }
     1600
     1601      /**
     1602       * ----------------
     1603       * LOYALTY logic
     1604       * ----------------
     1605       */
     1606      $loyalty_enabled = isset($settings['loyalty']['enabled']) ? $settings['loyalty']['enabled'] : false;
     1607      $loyalty_account_id = WC()->session->get('loyalty_account_id');
     1608      $reward_tier_id = WC()->session->get('reward_tier_id');
     1609      $cart_fees = WC()->cart->get_fees();
     1610      $redeeming_rewards = false;
     1611
     1612      foreach ($cart_fees as $fee) {
     1613        if (isset($fee->name) && $fee->name === 'Loyalty Discount') {
     1614          $redeeming_rewards = true;
     1615          break;
     1616        }
     1617      }
     1618
     1619      // Only process loyalty if the class exists (feature may not be available)
     1620      if (!class_exists('Pixeldev\\SquareWooSync\\Loyalty\\LoyaltyRedeeming')) {
     1621        $redeeming_rewards = false;
     1622      }
     1623
     1624      // If the loyalty discount fee is applied and we have account + tier
     1625      if ($redeeming_rewards && $loyalty_account_id && $reward_tier_id) {
     1626        $loyaltyRedeeming = new LoyaltyRedeeming();
    15171627        if (isset($square_order_response['data']['order']['id'])) {
     1628          // Redeem loyalty points
     1629          $redeemed = $loyaltyRedeeming->redeem_loyalty_reward(
     1630            $square_order_response['data']['order']['id'],
     1631            $loyalty_account_id,
     1632            $reward_tier_id,
     1633            $order_id
     1634          );
     1635
     1636          if (!isset($redeemed['success']) || $redeemed['success'] === false) {
     1637            return $this->handle_error($order_id, 'Unable to redeem reward, please contact us for help or remove the reward.');
     1638          }
     1639
     1640          // 6) If we have a valid Square order ID, fetch the updated order
     1641          if (isset($square_order_response['data']['order']['id'])) {
     1642            $square_order_response = $squareHelper->square_api_request(
     1643              '/orders/' . $square_order_response['data']['order']['id']
     1644            );
     1645          }
     1646        }
     1647      }
     1648
     1649      /*
     1650       * --------------------------------------------------------------------
     1651       *  RECONCILE  Woo (inc-tax)  ↔  Square net_amount_due (inc-tax)
     1652       * ------------------------------------------------------------------
     1653       */
     1654
     1655      /* 0. Quick exit if we never got a valid $square_order_response */
     1656      if (
     1657        empty($square_order_response['success']) ||
     1658        empty($square_order_response['data']['order']['id'])
     1659      ) {
     1660        // Charge the Woo total (less any gift-card) exactly as-is
     1661        $total_amount = (int) round($total_amount - $gift_card_amount_cents);
     1662      } else {  // ─────────────────────────── Square order does exist ───────────
     1663
     1664        /* 1. Effective tax-factor for this order (e.g. 1.10 for 10 % GST) */
     1665        $woo_tax_total = (float) $order->get_total_tax();
     1666        $woo_total_inc = (float) $order->get_total();
     1667        $tax_factor = ($woo_total_inc > 0 && $woo_tax_total > 0)
     1668          ? 1 + ($woo_tax_total / ($woo_total_inc - $woo_tax_total))
     1669          : 1.0;
     1670
     1671        /* 2. Square's current net_amount_due (inclusive, in cents) */
     1672        $sq_net = (int) $square_order_response['data']['order']['net_amount_due_money']['amount'];
     1673
     1674        /* 3. Woo's amount we expect to collect (inclusive, in cents) */
     1675        // Note: Subtract tip from WooCommerce total since tips are sent separately via tip_money
     1676        $tip_amount_for_delta = $ordersController->extractTipAmount($order);
     1677        $tip_amount_cents_for_delta = (int) round($tip_amount_for_delta * $multiplier);
     1678        $woo_due_inc = (int) round($total_amount - $gift_card_amount_cents - $tip_amount_cents_for_delta);
     1679
     1680        /* 4. Inclusive delta → applied 1-for-1 */
     1681        $delta_inc = $woo_due_inc - $sq_net;  // +ve = Square short
     1682
     1683        if ($delta_inc !== 0) {
     1684          $patch = ($delta_inc > 0)
     1685            ? ['service_charges' => [[
     1686              'uid' => 'rounding-surcharge',
     1687              'name' => 'Rounding Adjustment (+)',
     1688              'scope' => 'ORDER',
     1689              'calculation_phase' => 'TOTAL_PHASE',
     1690              'amount_money' => [
     1691                'amount' => $delta_inc,
     1692                'currency' => $currency,
     1693              ],
     1694              'taxable' => false,
     1695            ]]]
     1696            : ['discounts' => [[
     1697              'uid' => 'rounding-discount',
     1698              'name' => 'Rounding Adjustment (-)',
     1699              'amount_money' => [
     1700                'amount' => abs($delta_inc),
     1701                'currency' => $currency,
     1702              ],
     1703              'scope' => 'ORDER',
     1704            ]]];
     1705
     1706          /* Push the adjustment back to Square */
    15181707          $square_order_response = $squareHelper->square_api_request(
    15191708            '/orders/' . $square_order_response['data']['order']['id'],
     
    15211710            [
    15221711              'idempotency_key' => wp_generate_uuid4(),
    1523               'order' => [
    1524                 'service_charges' => [$service_charge],
    1525                 'location_id'     => $locationId,
    1526                 'version'         => $square_order_response['data']['order']['version'],
     1712              'order' => $patch + [
     1713                'location_id' => $locationId,
     1714                'version' => $square_order_response['data']['order']['version'],
    15271715              ],
    15281716            ]
    15291717          );
    15301718        }
    1531       }
     1719
     1720        /* 5. Fetch the authoritative total from Square */
     1721        $sq_net = (int) ($square_order_response['data']['order']['net_amount_due_money']['amount'] ?? 0);
     1722        $total_amount = max(0, $sq_net - $gift_card_amount_cents);
     1723      }
     1724      /* ───────────────────────────────────────────────────────────────────── */
    15321725
    15331726      $settings = get_option('square-woo-sync_settings', []);
    1534       $locationId = $settings['location'];
    1535 
     1727
     1728      // Extract tip amount from order fees for proper tip reporting
     1729      $tip_amount = $ordersController->extractTipAmount($order);
     1730      $tip_amount_cents = (int) round($tip_amount * $multiplier);
    15361731
    15371732      // SCENARIOS:
    15381733      // If Gift Card is not set, fallback to your old single payment
    1539 
    1540       // Prepare single payment data
    1541       $payment_data = $this->prepare_payment_data(
    1542         $square_token,
    1543         $order_id,
    1544         $total_amount,
    1545         $currency,
    1546         $square_customer_id,
    1547         $locationId,
    1548         $square_order_response
    1549       );
    1550 
    1551       if (!empty($square_verification_token)) {
    1552         $payment_data['verification_token'] = $square_verification_token;
    1553       }
    1554 
    1555       // Charge
    1556       $payment_response = $squareHelper->square_api_request("/payments", 'POST', $payment_data, null, false);
    1557       if (!$this->validate_payment_response($payment_response, $order_id)) {
    1558         // if fail => restore loyalty, handle error
    1559         $error_message = 'Square payment failed.';
    1560         if (isset($payment_response['error'])) {
    1561           $error_message = $payment_response['error'];
    1562         }
    1563         return $this->handle_error($order_id, $error_message);
    1564       }
    1565 
    1566       // success => finalize
    1567       $payment_id = $payment_response['data']['payment']['id'];
    1568       // Save new card if requested
    1569       if (
    1570         (isset($_POST['wc-' . $this->id . '-new-payment-method']) && 'true' === $_POST['wc-' . $this->id . '-new-payment-method'])
    1571         || (isset($_POST['wc-squaresync_credit-new-payment-method']) && '1' === $_POST['wc-squaresync_credit-new-payment-method'])
    1572       ) {
    1573         if (empty($token_id) || $token_id === 'new') {
    1574           $card_response = $this->save_card_on_square($payment_id, $square_customer_id);
    1575           if (!$card_response['success']) {
    1576             wc_add_notice(__('There was a problem saving your payment method.', 'squarewoosync'), 'error');
    1577           } else {
    1578             $card_data = $card_response['data']['card'];
    1579             $payment_token = new \WC_Payment_Token_CC();
    1580             $payment_token->set_token($card_data['id']);
    1581             $payment_token->set_gateway_id($this->id);
    1582             $payment_token->set_card_type(strtolower($card_data['card_brand']));
    1583             $payment_token->set_last4($card_data['last_4']);
    1584             $payment_token->set_expiry_month($card_data['exp_month']);
    1585             $payment_token->set_expiry_year($card_data['exp_year']);
    1586             $payment_token->set_user_id(get_current_user_id());
    1587             $payment_token->save();
    1588             // attach to order
    1589             $order->add_payment_token($payment_token->get_id());
     1734      if (empty($gift_card_id)) {
     1735        error_log("[SquareSync Gateway] Order #{$order_id}: Processing standard payment (no gift card)");
     1736
     1737        // Prepare single payment data
     1738        $payment_data = $this->prepare_payment_data(
     1739          $square_token,
     1740          $order_id,
     1741          $total_amount,
     1742          $currency,
     1743          $square_customer_id,
     1744          $locationId,
     1745          $square_order_response,
     1746          $tip_amount_cents
     1747        );
     1748
     1749        if (!empty($square_verification_token)) {
     1750          $payment_data['verification_token'] = $square_verification_token;
     1751          error_log("[SquareSync Gateway] Order #{$order_id}: Verification token included");
     1752        }
     1753
     1754        // Charge
     1755        error_log("[SquareSync Gateway] Order #{$order_id}: Sending payment request to Square (Amount: {$total_amount} {$currency})");
     1756        $payment_response = $squareHelper->square_api_request('/payments', 'POST', $payment_data, null, false);
     1757        if (!$this->validate_payment_response($payment_response, $order_id)) {
     1758          // if fail => restore loyalty, handle error
     1759          $error_message = 'Square payment failed.';
     1760          if (isset($payment_response['error'])) {
     1761            $error_message = $payment_response['error'];
    15901762          }
    1591         }
    1592       }
    1593 
    1594       // finalize
    1595       $this->finalize_order_payment($order, $payment_response, $square_order_response, $total_amount);
    1596 
     1763
     1764          // Cancel the Square order if it was created to prevent orphaned orders
     1765          if (isset($square_order_response['data']['order']['id'])) {
     1766            $square_order_id = $square_order_response['data']['order']['id'];
     1767
     1768            // Fetch the latest version of the order before cancelling
     1769            // The version may have changed due to loyalty redemption or rounding adjustments
     1770            $latest_order = $squareHelper->square_api_request("/orders/{$square_order_id}", 'GET');
     1771
     1772            if (isset($latest_order['data']['order']['version'])) {
     1773              $current_version = $latest_order['data']['order']['version'];
     1774
     1775              // Cancel all fulfillments first (required by Square before order can be cancelled)
     1776              if (isset($latest_order['data']['order']['fulfillments']) && is_array($latest_order['data']['order']['fulfillments'])) {
     1777                $fulfillments_to_cancel = [];
     1778
     1779                foreach ($latest_order['data']['order']['fulfillments'] as $fulfillment) {
     1780                  if (isset($fulfillment['uid']) && isset($fulfillment['state']) && $fulfillment['state'] !== 'CANCELED') {
     1781                    $fulfillments_to_cancel[] = [
     1782                      'uid' => $fulfillment['uid'],
     1783                      'state' => 'CANCELED'
     1784                    ];
     1785                  }
     1786                }
     1787
     1788                // Cancel all fulfillments in a single request
     1789                if (!empty($fulfillments_to_cancel)) {
     1790                  $fulfillment_cancel_result = $squareHelper->square_api_request(
     1791                    "/orders/{$square_order_id}",
     1792                    'PUT',
     1793                    [
     1794                      'idempotency_key' => wp_generate_uuid4(),
     1795                      'order' => [
     1796                        'version' => $current_version,
     1797                        'location_id' => $locationId,
     1798                        'fulfillments' => $fulfillments_to_cancel
     1799                      ]
     1800                    ]
     1801                  );
     1802
     1803                  // Update version after fulfillment cancellation
     1804                  if (isset($fulfillment_cancel_result['data']['order']['version'])) {
     1805                    $current_version = $fulfillment_cancel_result['data']['order']['version'];
     1806                  }
     1807                }
     1808              }
     1809
     1810              // Now cancel the order itself
     1811              $cancel_result = $squareHelper->square_api_request(
     1812                "/orders/{$square_order_id}",
     1813                'PUT',
     1814                [
     1815                  'order' => [
     1816                    'version' => $current_version,
     1817                    'state' => 'CANCELED',
     1818                    'location_id' => $locationId
     1819                  ]
     1820                ]
     1821              );
     1822            }
     1823          }
     1824
     1825          if ($redeeming_rewards && isset($square_order_response['data']['order'])) {
     1826            $loyaltyRedeeming->restore_loyalty_points(
     1827              $loyalty_account_id,
     1828              $reward_tier_id,
     1829              $order_id,
     1830              $square_order_response['data']['order']
     1831            );
     1832          }
     1833          return $this->handle_error($order_id, $error_message);
     1834        }
     1835
     1836        // success => finalize
     1837        $payment_id = $payment_response['data']['payment']['id'];
     1838        error_log("[SquareSync Gateway] Order #{$order_id}: Payment successful - Square Payment ID: {$payment_id}");
     1839
     1840        // If split orders mode, store payment ID and queue background job
     1841        if ($split_orders_enabled) {
     1842          // Update the pending payment ID with actual payment ID
     1843          $order->update_meta_data('_square_payment_id_pending', $payment_id);
     1844          $order->save();
     1845
     1846          // Queue the split order job
     1847          require_once plugin_dir_path(__FILE__) . '../Jobs/SplitOrderJob.php';
     1848          wp_queue()->push(
     1849            new \Pixeldev\SquareWooSync\Jobs\SplitOrderJob($order_id),
     1850            0 // Execute immediately
     1851          );
     1852
     1853          error_log("[SquareSync Gateway] Order #{$order_id}: Split order job queued with payment ID: {$payment_id}");
     1854        }
     1855
     1856        // Save new card if requested
     1857        if (
     1858          (isset($_POST['wc-' . $this->id . '-new-payment-method']) && 'true' === $_POST['wc-' . $this->id . '-new-payment-method']) ||
     1859          (isset($_POST['wc-squaresync_credit-new-payment-method']) && '1' === $_POST['wc-squaresync_credit-new-payment-method'])
     1860        ) {
     1861          if (empty($token_id) || $token_id === 'new') {
     1862            $card_response = $this->save_card_on_square($payment_id, $square_customer_id);
     1863            if (!$card_response['success']) {
     1864              wc_add_notice(__('There was a problem saving your payment method.', 'squarewoosync-pro'), 'error');
     1865            } else {
     1866              $card_data = $card_response['data']['card'];
     1867              $payment_token = new \WC_Payment_Token_CC();
     1868              $payment_token->set_token($card_data['id']);
     1869              $payment_token->set_gateway_id($this->id);
     1870              $payment_token->set_card_type(strtolower($card_data['card_brand']));
     1871              $payment_token->set_last4($card_data['last_4']);
     1872              $payment_token->set_expiry_month($card_data['exp_month']);
     1873              $payment_token->set_expiry_year($card_data['exp_year']);
     1874              $payment_token->set_user_id(get_current_user_id());
     1875              $payment_token->save();
     1876              // attach to order
     1877              $order->add_payment_token($payment_token->get_id());
     1878            }
     1879          }
     1880        }
     1881
     1882        // finalize
     1883        error_log("[SquareSync Gateway] Order #{$order_id}: Finalizing order payment");
     1884        $this->finalize_order_payment($order, $payment_response, $square_order_response, $total_amount);
     1885      } else {
     1886        // GIFT CARD IS PRESENT
     1887        // We must see if the gift card covers partial or full
     1888        error_log("[SquareSync Gateway] Order #{$order_id}: Processing payment with gift card (ID: {$gift_card_id}, Amount: {$gift_card_amount_cents})");
     1889
     1890        // Partial coverage scenario: Gift card covers part, we also have a card token?
     1891        if (empty($square_token)) {
     1892          // No card token, but not fully covered => error
     1893
     1894          // Cancel the Square order if it was created to prevent orphaned orders
     1895          if (isset($square_order_response['data']['order']['id'])) {
     1896            $square_order_id = $square_order_response['data']['order']['id'];
     1897            error_log("[SquareSync Gateway] Order #{$order_id}: Cancelling Square order {$square_order_id} due to insufficient payment method");
     1898            $cancel_result = $squareHelper->square_api_request(
     1899              "/orders/{$square_order_id}",
     1900              'PUT',
     1901              [
     1902                'order' => [
     1903                  'version' => $square_order_response['data']['order']['version'],
     1904                  'state' => 'CANCELED',
     1905                  'location_id' => $locationId
     1906                ]
     1907              ]
     1908            );
     1909            if (isset($cancel_result['success']) && $cancel_result['success']) {
     1910              error_log("[SquareSync Gateway] Order #{$order_id}: Square order {$square_order_id} cancelled successfully");
     1911            }
     1912          }
     1913
     1914          if ($redeeming_rewards && isset($square_order_response['data']['order'])) {
     1915            $loyaltyRedeeming->restore_loyalty_points(
     1916              $loyalty_account_id,
     1917              $reward_tier_id,
     1918              $order_id,
     1919              $square_order_response['data']['order']
     1920            );
     1921          }
     1922          return $this->handle_error($order_id, 'Gift Card does not fully cover the order, and no other payment method provided.');
     1923        }
     1924
     1925        $settings = get_option('square-woo-sync_settings', []);
     1926
     1927        // 1) Payment #1 with Gift Card (autocomplete=false)
     1928        $partial_giftcard_data = [
     1929          'idempotency_key' => uniqid('gc-part-', true),
     1930          'location_id' => $locationId,
     1931          'source_id' => $gift_card_id,
     1932          'order_id' => $square_order_response['data']['order']['id'] ?? '',
     1933          'amount_money' => [
     1934            'amount' => $gift_card_amount_cents,
     1935            'currency' => $currency,
     1936          ],
     1937          'autocomplete' => false,
     1938          'accept_partial_authorization' => true
     1939        ];
     1940        $gc_payment_resp = $squareHelper->square_api_request('/payments', 'POST', $partial_giftcard_data);
     1941
     1942        if (!empty($gc_payment_resp['error'])) {
     1943          // Cancel the Square order if it was created to prevent orphaned orders
     1944          if (isset($square_order_response['data']['order']['id'])) {
     1945            $square_order_id = $square_order_response['data']['order']['id'];
     1946            error_log("[SquareSync Gateway] Order #{$order_id}: Cancelling Square order {$square_order_id} due to gift card payment failure");
     1947            $cancel_result = $squareHelper->square_api_request(
     1948              "/orders/{$square_order_id}",
     1949              'PUT',
     1950              [
     1951                'order' => [
     1952                  'version' => $square_order_response['data']['order']['version'],
     1953                  'state' => 'CANCELED',
     1954                  'location_id' => $locationId
     1955                ]
     1956              ]
     1957            );
     1958            if (isset($cancel_result['success']) && $cancel_result['success']) {
     1959              error_log("[SquareSync Gateway] Order #{$order_id}: Square order {$square_order_id} cancelled successfully");
     1960            }
     1961          }
     1962
     1963          if ($redeeming_rewards && isset($square_order_response['data']['order'])) {
     1964            $loyaltyRedeeming->restore_loyalty_points(
     1965              $loyalty_account_id,
     1966              $reward_tier_id,
     1967              $order_id,
     1968              $square_order_response['data']['order']
     1969            );
     1970          }
     1971          return $this->handle_error($order_id, 'Error authorizing gift card payment: ' . $gc_payment_resp['error']);
     1972        }
     1973
     1974        $giftcard_payment_id = $gc_payment_resp['data']['payment']['id'] ?? '';
     1975
     1976        // 2) Payment #2 with Card for the remainder
     1977        $payment_data = [
     1978          'idempotency_key' => wp_generate_uuid4(),
     1979          'source_id' => $square_token,
     1980          'reference_id' => "Woo Order #$order_id",
     1981          'autocomplete' => true,
     1982          'amount_money' => ['amount' => $total_amount, 'currency' => $currency],
     1983          'location_id' => $locationId,
     1984          'autocomplete' => false,
     1985          'order_id' => $square_order_response['data']['order']['id'] ?? '',
     1986        ];
     1987
     1988        // Only add customer ID if it's a valid string (not an array with error)
     1989        if (!is_array($square_customer_id) && !empty($square_customer_id)) {
     1990          $payment_data['customer_id'] = $square_customer_id;
     1991        }
     1992
     1993        if (!empty($square_verification_token)) {
     1994          $payment_data['verification_token'] = $square_verification_token;
     1995        }
     1996
     1997        $card_pay_resp = $squareHelper->square_api_request('/payments', 'POST', $payment_data);
     1998
     1999        if (!empty($card_pay_resp['error'])) {
     2000          // Cancel the gift card payment if it succeeded
     2001          if (!empty($giftcard_payment_id)) {
     2002            $squareHelper->square_api_request("/payments/{$giftcard_payment_id}/cancel", 'POST');
     2003          }
     2004
     2005          // Cancel the Square order if it was created to prevent orphaned orders
     2006          if (isset($square_order_response['data']['order']['id'])) {
     2007            $square_order_id = $square_order_response['data']['order']['id'];
     2008            error_log("[SquareSync Gateway] Order #{$order_id}: Cancelling Square order {$square_order_id} due to card payment failure");
     2009            $cancel_result = $squareHelper->square_api_request(
     2010              "/orders/{$square_order_id}",
     2011              'PUT',
     2012              [
     2013                'order' => [
     2014                  'version' => $square_order_response['data']['order']['version'],
     2015                  'state' => 'CANCELED',
     2016                  'location_id' => $locationId
     2017                ]
     2018              ]
     2019            );
     2020            if (isset($cancel_result['success']) && $cancel_result['success']) {
     2021              error_log("[SquareSync Gateway] Order #{$order_id}: Square order {$square_order_id} cancelled successfully");
     2022            }
     2023          }
     2024
     2025          // restore loyalty
     2026          if ($redeeming_rewards && isset($square_order_response['data']['order'])) {
     2027            $loyaltyRedeeming->restore_loyalty_points(
     2028              $loyalty_account_id,
     2029              $reward_tier_id,
     2030              $order_id,
     2031              $square_order_response['data']['order']
     2032            );
     2033          }
     2034          return $this->handle_error($order_id, 'Error authorizing card payment: ' . $card_pay_resp['error']);
     2035        }
     2036        $card_payment_id = $card_pay_resp['data']['payment']['id'] ?? '';
     2037
     2038        // 3) Now "pay order" with the two authorized payments
     2039        if (!empty($giftcard_payment_id) || !empty($card_payment_id)) {
     2040          $payment_ids = [];
     2041          if ($giftcard_payment_id)
     2042            $payment_ids[] = $giftcard_payment_id;
     2043          if ($card_payment_id)
     2044            $payment_ids[] = $card_payment_id;
     2045
     2046          $new_square_order = $squareHelper->square_api_request(
     2047            '/orders/' . $square_order_response['data']['order']['id']
     2048          );
     2049          $square_order = $new_square_order['data']['order'] ?? [];
     2050
     2051          // Pay order
     2052          $payOrderData = [
     2053            'idempotency_key' => uniqid('pay-', true),
     2054            'order_version' => $square_order['version'],
     2055            'payment_ids' => $payment_ids,
     2056          ];
     2057          $pay_resp = $squareHelper->square_api_request(
     2058            '/orders/' . $square_order_response['data']['order']['id'] . '/pay',
     2059            'POST',
     2060            $payOrderData
     2061          );
     2062          if (!empty($pay_resp['error'])) {
     2063            // Cancel both payments
     2064            $squareHelper->square_api_request("/payments/{$giftcard_payment_id}/cancel", 'POST');
     2065            $squareHelper->square_api_request("/payments/{$card_payment_id}/cancel", 'POST');
     2066
     2067            // Cancel the Square order if it was created to prevent orphaned orders
     2068            if (isset($square_order_response['data']['order']['id'])) {
     2069              $square_order_id = $square_order_response['data']['order']['id'];
     2070              error_log("[SquareSync Gateway] Order #{$order_id}: Cancelling Square order {$square_order_id} due to pay order failure");
     2071              $cancel_result = $squareHelper->square_api_request(
     2072                "/orders/{$square_order_id}",
     2073                'PUT',
     2074                [
     2075                  'order' => [
     2076                    'version' => $square_order['version'],
     2077                    'state' => 'CANCELED',
     2078                    'location_id' => $locationId
     2079                  ]
     2080                ]
     2081              );
     2082              if (isset($cancel_result['success']) && $cancel_result['success']) {
     2083                error_log("[SquareSync Gateway] Order #{$order_id}: Square order {$square_order_id} cancelled successfully");
     2084              }
     2085            }
     2086
     2087            if ($redeeming_rewards && isset($square_order_response['data']['order'])) {
     2088              $loyaltyRedeeming->restore_loyalty_points(
     2089                $loyalty_account_id,
     2090                $reward_tier_id,
     2091                $order_id,
     2092                $square_order_response['data']['order']
     2093              );
     2094            }
     2095            return $this->handle_error($order_id, 'Error paying order with multiple payments: ' . $pay_resp['error']);
     2096          }
     2097        }
     2098
     2099        // (Optional) If user wants to save the new card
     2100        if (
     2101          (isset($_POST['wc-' . $this->id . '-new-payment-method']) && 'true' === $_POST['wc-' . $this->id . '-new-payment-method']) ||
     2102          (isset($_POST['wc-squaresync_credit-new-payment-method']) && '1' === $_POST['wc-squaresync_credit-new-payment-method'])
     2103        ) {
     2104          if (empty($token_id) || $token_id === 'new') {
     2105            // We can use the card_payment_id to save the card
     2106            // But only if a card payment was actually made
     2107            if (!empty($card_payment_id)) {
     2108              $card_response = $this->save_card_on_square($card_payment_id, $square_customer_id);
     2109              if (!$card_response['success']) {
     2110                wc_add_notice(__('Problem saving your card with partial coverage.', 'squarewoosync-pro'), 'error');
     2111              } else {
     2112                $card_data = $card_response['data']['card'];
     2113                $new_token = new \WC_Payment_Token_CC();
     2114                $new_token->set_token($card_data['id']);
     2115                $new_token->set_gateway_id($this->id);
     2116                $new_token->set_card_type(strtolower($card_data['card_brand']));
     2117                $new_token->set_last4($card_data['last_4']);
     2118                $new_token->set_expiry_month($card_data['exp_month']);
     2119                $new_token->set_expiry_year($card_data['exp_year']);
     2120                $new_token->set_user_id(get_current_user_id());
     2121                $new_token->save();
     2122                $order->add_payment_token($new_token->get_id());
     2123              }
     2124            }
     2125          }
     2126        }
     2127
     2128        $square_data = ['order' => $square_order_response, 'payment' => $pay_resp];
     2129        $order->update_meta_data('square_data', wp_json_encode($square_data));
     2130        if (isset($square_order_response['data']['order']['id'])) {
     2131          $order->update_meta_data('square_order_id', $square_order_response['data']['order']['id']);
     2132
     2133          do_action(
     2134            'squarewoosync_square_order_created',
     2135            $square_order_response['data']['order']['id'],
     2136            $order->get_id()
     2137          );
     2138        }
     2139
     2140        // Mark order paid in Woo
     2141        $order->payment_complete();
     2142        $order->add_order_note(__('Gift Card + Card partial coverage in Square.', 'squarewoosync-pro'));
     2143      }
    15972144
    15982145      // Handle subscriptions (attach token if available)
     
    16172164      WC()->cart->empty_cart();
    16182165
     2166      // If loyalty is enabled and we are NOT redeeming rewards, schedule point accumulation
     2167      if (
     2168        $loyalty_enabled &&
     2169        !$redeeming_rewards &&
     2170        isset($square_order_response['data']['order']['id']) &&
     2171        isset($square_customer_id) &&
     2172        class_exists('Pixeldev\\SquareWooSync\\Loyalty\\LoyaltyProgram')
     2173      ) {
     2174        $loyaltyProgram = new LoyaltyProgram();
     2175        $loyaltyProgram->schedule_loyalty_points_accumulation($order_id);
     2176      }
     2177      if (WC()->session && is_object(WC()->session)) {
     2178        // Clear session loyalty data
     2179        WC()->session->__unset('applied_reward_name');
     2180        WC()->session->__unset('applied_reward_points');
     2181        WC()->session->__unset('loyalty_account_id');
     2182        WC()->session->__unset('reward_tier_id');
     2183        WC()->session->__unset('store_credit_discount_type');
     2184        WC()->session->__unset('store_credit_discount_amount');
     2185        WC()->session->__unset('applied_gift_card_code');
     2186        WC()->session->__unset('applied_gift_card_amount');
     2187        WC()->session->__unset('applied_gift_card_id');
     2188        WC()->session->__unset('applied_gift_card_balance');
     2189      }
     2190
     2191      error_log("[SquareSync Gateway] Order #{$order_id}: Payment processing completed successfully");
    16192192      return ['result' => 'success', 'redirect' => $this->get_return_url($order)];
    16202193    } catch (\Exception $e) {
    1621 
     2194      error_log("[SquareSync Gateway] Order #{$order_id}: Exception occurred during payment processing - " . $e->getMessage());
     2195      error_log("[SquareSync Gateway] Order #{$order_id}: Stack trace: " . $e->getTraceAsString());
    16222196      return $this->handle_exception($order_id, $e);
    16232197    }
    16242198  }
    1625 
    1626 
    16272199
    16282200  private function check_net_amount_due($square_order_response, $total_amount, $currency, $order_id)
     
    16412213    // Recalculate the cart totals
    16422214    WC()->cart->calculate_totals();
    1643     wc_add_notice(__('Payment error: ', 'squarewoosync') . $message, 'error');
     2215    wc_add_notice(__('Payment error: ', 'squarewoosync-pro') . $message, 'error');
    16442216    return ['result' => 'failure', 'redirect' => wc_get_checkout_url()];
    16452217  }
    16462218
    16472219  // Attempt to create Square order, return false if unsuccessful but do not halt process
    1648   private function attempt_create_square_order($ordersController, $order, $square_customer_id, $squareHelper, $order_id)
    1649   {
    1650     if (is_array($square_customer_id) || empty($square_customer_id)) return false;
    1651 
    1652     $order_data = $ordersController->prepareSquareOrderData($order, $square_customer_id);
     2220  private function attempt_create_square_order($ordersController, $order, $square_customer_id, $squareHelper, $order_id, $location_id)
     2221  {
     2222    error_log("[SquareSync Gateway] Order #{$order_id}: Attempting to create Square order");
     2223    error_log("[SquareSync Gateway] Order #{$order_id}: Location ID: {$location_id}");
     2224
     2225    if (is_array($square_customer_id) || empty($square_customer_id)) {
     2226      error_log("[SquareSync Gateway] Order #{$order_id}: Invalid Square customer ID - cannot create order");
     2227      $order->add_order_note(__('Square order creation failed: Invalid Square customer ID.', 'squarewoosync-pro'));
     2228      return false;
     2229    }
     2230
     2231    error_log("[SquareSync Gateway] Order #{$order_id}: Preparing Square order data");
     2232    $order_data = $ordersController->prepareSquareOrderData($order, $square_customer_id, $location_id);
     2233
     2234    error_log("[SquareSync Gateway] Order #{$order_id}: Sending create order request to Square API");
    16532235    $square_order_response = $ordersController->createOrderInSquare($order_data, $squareHelper);
    16542236
    16552237    if (!isset($square_order_response['success']) || $square_order_response['success'] === false) {
    1656       error_log("Square order error for Order ID: $order_id - " . json_encode($square_order_response['error']));
     2238      $error_msg = json_encode($square_order_response['error'] ?? 'Unknown error');
     2239      error_log("[SquareSync Gateway] Order #{$order_id}: Square order creation FAILED - {$error_msg}");
     2240      error_log("[SquareSync Gateway] Order #{$order_id}: Full Square API response: " . json_encode($square_order_response));
     2241
     2242      // Add order note for visibility in WooCommerce admin
     2243      $error_detail = is_array($square_order_response['error'])
     2244        ? wp_json_encode($square_order_response['error'])
     2245        : ($square_order_response['error'] ?? 'Unknown error');
     2246      $order->add_order_note(
     2247        sprintf(
     2248          __('Square order creation failed: %s', 'squarewoosync-pro'),
     2249          $error_detail
     2250        )
     2251      );
     2252
    16572253      return false;
    16582254    }
     2255
     2256    $square_order_id = $square_order_response['data']['order']['id'] ?? 'N/A';
     2257    error_log("[SquareSync Gateway] Order #{$order_id}: Square order created successfully - Square Order ID: {$square_order_id}");
    16592258    return $square_order_response;
    16602259  }
    16612260
    16622261  // Prepare payment data
    1663   private function prepare_payment_data($token, $order_id, $total_amount, $currency, $square_customer_id, $location_id, $square_order_response)
    1664   {
     2262  private function prepare_payment_data($token, $order_id, $total_amount, $currency, $square_customer_id, $location_id, $square_order_response, $tip_amount_cents = 0)
     2263  {
     2264    // Note: $total_amount passed here is already the Square order's net_amount_due (without tip)
     2265    // because it's calculated from the Square order response after delta adjustments.
     2266    // We do NOT subtract the tip again here - just use $total_amount as-is for the payment.
     2267    $payment_amount = $total_amount;
     2268
    16652269    $payment_data = [
    16662270      'idempotency_key' => wp_generate_uuid4(),
     
    16682272      'reference_id' => "Woo Order #$order_id",
    16692273      'autocomplete' => true,
    1670       'amount_money' => ['amount' => $total_amount, 'currency' => $currency],
     2274      'amount_money' => ['amount' => $payment_amount, 'currency' => $currency],
    16712275      'location_id' => $location_id,
    16722276    ];
     2277
     2278    // Add tip_money if there's a tip amount
     2279    if ($tip_amount_cents > 0) {
     2280      $payment_data['tip_money'] = [
     2281        'amount' => $tip_amount_cents,
     2282        'currency' => $currency,
     2283      ];
     2284      error_log("[SquareSync Gateway] Order #{$order_id}: Adding tip_money to payment - Amount: {$tip_amount_cents} {$currency}");
     2285    }
    16732286
    16742287    // Only add customer ID if it's a valid string (not an array with error)
     
    16772290    }
    16782291
    1679     // Add order ID only if the total amounts match
     2292    // Add order ID if the order was created successfully
     2293    // When tips are involved, we always attach the order_id because the payment amount
     2294    // (without tip) + tip_money will equal the correct total
    16802295    if (isset($square_order_response['data']['order']['id'])) {
    1681       $square_order_net_amount_due = $square_order_response['data']['order']['net_amount_due_money']['amount'] ?? null;
    1682 
    1683       if ($square_order_net_amount_due !== null && $square_order_net_amount_due == $total_amount) {
    1684         $payment_data['order_id'] = $square_order_response['data']['order']['id'];
    1685       } else {
    1686         // Optionally log or handle the discrepancy
    1687         error_log("Discrepancy detected: Square order total ($square_order_net_amount_due) does not match WooCommerce total ($total_amount) for Order #$order_id.");
    1688       }
     2296      $payment_data['order_id'] = $square_order_response['data']['order']['id'];
     2297
     2298      $square_order_net_amount_due = $square_order_response['data']['order']['net_amount_due_money']['amount'] ?? 'N/A';
     2299      error_log("[SquareSync Gateway] Order #{$order_id}: Order ID attached to payment. Square net due: {$square_order_net_amount_due}, Payment: {$payment_amount}, Tip: {$tip_amount_cents}");
    16892300    }
    16902301
     
    16962307  {
    16972308    if (!isset($payment_response['success']) || $payment_response['success'] === false) {
    1698       error_log("Square payment error for Order ID: $order_id - " . json_encode($payment_response['error']));
     2309      $error_detail = json_encode($payment_response['error'] ?? 'Unknown error');
     2310      error_log("[SquareSync Gateway] Order #{$order_id}: Payment validation FAILED - {$error_detail}");
    16992311      return false;
    17002312    }
     2313    error_log("[SquareSync Gateway] Order #{$order_id}: Payment validation successful");
    17012314    return true;
    17022315  }
     
    17052318  private function finalize_order_payment($order, $payment_response, $square_order_response, $total_amount)
    17062319  {
     2320    $order_id = $order->get_id();
     2321    error_log("[SquareSync Gateway] Order #{$order_id}: Finalizing order payment");
    17072322
    17082323    $ordersController = new OrdersController();
    1709     $multiplier = $ordersController->get_currency_multiplier();
    1710     $square_data = ['order' => $square_order_response, 'payment' => $payment_response];
    1711     $order->update_meta_data('square_data', wp_json_encode($square_data));
    1712     if (isset($square_order_response['data']['order']['id'])) {
    1713       $order->update_meta_data('square_order_id',  $square_order_response['data']['order']['id']);
    1714 
    1715       do_action(
    1716         'squarewoosync_square_order_created',
    1717         $square_order_response['data']['order']['id'],
    1718         $order->get_id()
    1719       );
    1720     }
    1721     $order->payment_complete($payment_response['data']['payment']['id']);
     2324    $multiplier = $ordersController->get_currency_multiplier($order->get_currency());
     2325
     2326    // Check if in split order mode
     2327    $is_split_mode = $order->get_meta('_square_order_pending_split');
     2328
     2329    if ($is_split_mode) {
     2330      error_log("[SquareSync Gateway] Order #{$order_id}: Split mode detected - deferring Square order data save to background job");
     2331    }
     2332
     2333    // Only save square order data if not in split mode (split mode will handle this in background)
     2334    if (!$is_split_mode) {
     2335      $square_data = ['order' => $square_order_response, 'payment' => $payment_response];
     2336      $order->update_meta_data('square_data', wp_json_encode($square_data));
     2337      if (isset($square_order_response['data']['order']['id'])) {
     2338        $square_order_id = $square_order_response['data']['order']['id'];
     2339        $order->update_meta_data('square_order_id', $square_order_id);
     2340        error_log("[SquareSync Gateway] Order #{$order_id}: Saved Square order ID: {$square_order_id}");
     2341
     2342        do_action(
     2343          'squarewoosync_square_order_created',
     2344          $square_order_id,
     2345          $order_id
     2346        );
     2347        error_log("[SquareSync Gateway] Order #{$order_id}: Fired squarewoosync_square_order_created action");
     2348      }
     2349    }
     2350
     2351    $payment_id = $payment_response['data']['payment']['id'];
     2352    error_log("[SquareSync Gateway] Order #{$order_id}: Marking order as payment complete with Square Payment ID: {$payment_id}");
     2353    $order->payment_complete($payment_id);
     2354
    17222355    $order->add_order_note(sprintf(
    1723       __('Payment of %1$s via Square successfully completed (Square Transaction ID: %2$s)', 'squarewoosync'),
     2356      // translators: 1: formatted payment amount; 2: Square transaction ID.
     2357      __('Payment of %1$s via Square successfully completed (Square Transaction ID: %2$s)', 'squarewoosync-pro'),
    17242358      wc_price($total_amount / $multiplier),
    17252359      $payment_response['data']['payment']['id']
    17262360    ));
     2361
    17272362  }
    17282363
     
    17302365  private function handle_exception($order_id, $exception)
    17312366  {
    1732     wc_add_notice(__('Payment error: An unexpected error occurred. Please try again.', 'squarewoosync'), 'error');
     2367    if (WC()->session && is_object(WC()->session)) {
     2368      // Clear session loyalty data
     2369      WC()->session->__unset('applied_reward_name');
     2370      WC()->session->__unset('applied_reward_points');
     2371      WC()->session->__unset('loyalty_account_id');
     2372      WC()->session->__unset('reward_tier_id');
     2373      WC()->session->__unset('store_credit_discount_type');
     2374      WC()->session->__unset('store_credit_discount_amount');
     2375      WC()->session->__unset('applied_gift_card_code');
     2376      WC()->session->__unset('applied_gift_card_amount');
     2377      WC()->session->__unset('applied_gift_card_id');
     2378      WC()->session->__unset('applied_gift_card_balance');
     2379    }
     2380
     2381    wc_add_notice(__('Payment error: An unexpected error occurred. Please try again.', 'squarewoosync-pro'), 'error');
    17332382    error_log("Payment processing exception for Order ID: $order_id - " . $exception->getMessage());
    17342383    return ['result' => 'failure', 'redirect' => wc_get_checkout_url()];
     
    17422391    // Verify nonce for security
    17432392    if (!isset($_POST['nonce_sec']) || !wp_verify_nonce($_POST['nonce_sec'], 'sws_add_payment_method')) {
    1744       wc_add_notice(__('Nonce verification failed', 'squarewoosync'), 'error');
     2393      wc_add_notice(__('Nonce verification failed', 'squarewoosync-pro'), 'error');
    17452394      wp_redirect(wc_get_account_endpoint_url('payment-methods'));
    17462395      exit;
     
    17502399
    17512400    if (empty($token)) {
    1752       wc_add_notice(__('Payment token is missing.', 'squarewoosync'), 'error');
     2401      wc_add_notice(__('Payment token is missing.', 'squarewoosync-pro'), 'error');
    17532402      wp_redirect(wc_get_account_endpoint_url('payment-methods'));
    17542403      exit;
     
    17622411
    17632412    if (!$square_customer_id) {
    1764       wc_add_notice(__('Could not retrieve or create Square customer.', 'squarewoosync'), 'error');
     2413      wc_add_notice(__('Could not retrieve or create Square customer.', 'squarewoosync-pro'), 'error');
    17652414      wp_redirect(wc_get_account_endpoint_url('payment-methods'));
    17662415      exit;
     
    17712420
    17722421    if (!$card_response['success']) {
    1773       wc_add_notice(__('There was a problem adding your payment method: Invalid card data.', 'squarewoosync'), 'error');
     2422      wc_add_notice(__('There was a problem adding your payment method: Invalid card data.', 'squarewoosync-pro'), 'error');
    17742423      wp_redirect(wc_get_account_endpoint_url('payment-methods'));
    17752424      exit;
     
    17802429    // Create a new payment token
    17812430    $payment_token = new \WC_Payment_Token_CC();
    1782     $payment_token->set_token($card_data['id']); // The card ID from Square
     2431    $payment_token->set_token($card_data['id']);  // The card ID from Square
    17832432    $payment_token->set_gateway_id($this->id);
    17842433    $payment_token->set_card_type(strtolower($card_data['card_brand']));
     
    17912440    if ($payment_token->get_id()) {
    17922441      // Success
    1793       wc_add_notice(__('Payment method added successfully.', 'squarewoosync'), 'success');
     2442      wc_add_notice(__('Payment method added successfully.', 'squarewoosync-pro'), 'success');
    17942443    } else {
    1795       wc_add_notice(__('There was a problem saving your payment method.', 'squarewoosync'), 'error');
     2444      wc_add_notice(__('There was a problem saving your payment method.', 'squarewoosync-pro'), 'error');
    17962445    }
    17972446
     
    18002449    exit;
    18012450  }
    1802 
    18032451
    18042452  /**
     
    18112459  public function save_card_on_square($payment_id, $square_customer_id)
    18122460  {
    1813 
    18142461    // Generate a unique idempotency key
    18152462    $idempotency_key = uniqid('sq-', true);
     
    18182465    $body = [
    18192466      'idempotency_key' => $idempotency_key,
    1820       'source_id'       => $payment_id, // Use the payment ID as the source_id
    1821       'card'            => [
     2467      'source_id' => $payment_id, // Use the payment ID as the source_id
     2468      'card' => [
    18222469        'customer_id' => $square_customer_id,
    18232470      ],
     
    18332480      return [
    18342481        'success' => false,
    1835         'errors'  => $response['error'],
     2482        'errors' => $response['error'],
    18362483      ];
    18372484    } else {
     
    18392486      return [
    18402487        'success' => true,
    1841         'data'    => $response['data'],
     2488        'data' => $response['data'],
    18422489      ];
    18432490    }
     
    18632510    // Proceed to search for the customer via Square API using the user's email
    18642511    $search_customer_result = $squareHelper->square_api_request('/customers/search', 'POST', [
    1865       'query' => ['filter' => ['email_address' => ["exact" => $user_email]]]
     2512      'query' => ['filter' => ['email_address' => ['exact' => $user_email]]]
    18662513    ]);
    18672514
     
    19002547  }
    19012548
    1902 
    1903   // public function process_refund($order_id, $amount = null, $reason = '')
    1904   // {
    1905   //    if (!$amount || $amount <= 0) {
    1906   //        return new WP_Error('invalid_amount', __('Refund amount must be greater than zero.', 'woocommerce'));
    1907   //    }
    1908 
    1909   //    $order = wc_get_order($order_id);
    1910   //    $token = $this->square_access_token;
    1911   //    $squareHelper = new SquareHelper();
    1912 
    1913   //    $orderMeta = json_decode(get_post_meta($order_id, '_order_success_object', true), true)['order'];
    1914   //    $payment_methods = $orderMeta['tenders'];
    1915 
    1916   //    $payment_id = null;
    1917   //    foreach ($payment_methods as $method) {
    1918   //        if ($method['type'] !== 'SQUARE_GIFT_CARD') {
    1919   //            $payment_id = $method['id'];
    1920   //            break;
    1921   //        }
    1922   //    }
    1923 
    1924   //    if (!$payment_id) {
    1925   //        return new WP_Error('refund_failed', __('Refund failed: Payment method not found.', 'woocommerce'));
    1926   //    }
    1927 
    1928   //    $refund_data = [
    1929   //        "idempotency_key" => wp_generate_uuid4(),
    1930   //        "payment_id" => $payment_id,
    1931   //        "amount_money" => ['amount' => $amount * 100, 'currency' => $order->get_currency()],
    1932   //        "reason" => $reason,
    1933   //    ];
    1934 
    1935   //    $response = $squareHelper->CurlApi($refund_data, $this->square_url . "/refunds", 'POST', $token);
    1936   //    if (is_wp_error($response)) {
    1937   //        return $response;
    1938   //    }
    1939 
    1940   //    $refundResp = json_decode($response[1]);
    1941   //    if (isset($refundResp->refund->status) && in_array($refundResp->refund->status, ['PENDING', 'COMPLETED'])) {
    1942   //        $order->add_order_note(sprintf(__('Refunded %1$s - Reason: %2$s', 'woocommerce'), wc_price($amount), $reason));
    1943   //        return true;
    1944   //    }
    1945 
    1946   //    return new WP_Error('refund_failed', __('Refund failed: Could not complete the refund process.', 'woocommerce'));
    1947   // }
     2549  /**
     2550   * Process a refund through Square API
     2551   *
     2552   * @param int $order_id Order ID
     2553   * @param float $amount Refund amount
     2554   * @param string $reason Refund reason
     2555   * @return bool|WP_Error True on success, WP_Error on failure
     2556   */
     2557  public function process_refund($order_id, $amount = null, $reason = '')
     2558  {
     2559    // Validate refund amount
     2560    if (!$amount || $amount <= 0) {
     2561      return new WP_Error('invalid_amount', __('Refund amount must be greater than zero.', 'squarewoosync-pro'));
     2562    }
     2563
     2564    $order = wc_get_order($order_id);
     2565    if (!$order) {
     2566      return new WP_Error('invalid_order', __('Invalid order ID.', 'squarewoosync-pro'));
     2567    }
     2568
     2569    // Only process refunds for orders paid with this gateway
     2570    if ($order->get_payment_method() !== $this->id) {
     2571      return new WP_Error('invalid_gateway', __('This order was not paid with Square.', 'squarewoosync-pro'));
     2572    }
     2573
     2574    // Get Square payment data from order meta
     2575    $square_data = $order->get_meta('square_data');
     2576    if (!$square_data) {
     2577      return new WP_Error('no_square_data', __('Square payment data not found for this order.', 'squarewoosync-pro'));
     2578    }
     2579
     2580    $square_data = json_decode($square_data, true);
     2581
     2582    // Extract payment information
     2583    $payment_data = $square_data['payment']['data']['payment'] ?? null;
     2584    if (!$payment_data) {
     2585      return new WP_Error('invalid_payment_data', __('Invalid Square payment data structure.', 'squarewoosync-pro'));
     2586    }
     2587
     2588    $payment_id = $payment_data['id'] ?? null;
     2589    $payment_status = $payment_data['status'] ?? null;
     2590    $original_amount = $payment_data['amount_money']['amount'] ?? 0;
     2591    $currency = $payment_data['amount_money']['currency'] ?? $order->get_currency();
     2592    $payment_version_token = $payment_data['version_token'] ?? null;
     2593
     2594    if (!$payment_id) {
     2595      return new WP_Error('missing_payment_id', __('Square payment ID not found.', 'squarewoosync-pro'));
     2596    }
     2597
     2598    // Get the latest payment data from Square to ensure we have the current version token
     2599    $squareHelper = new SquareHelper();
     2600    $payment_response = $squareHelper->square_api_request('/payments/' . $payment_id, 'GET');
     2601
     2602    if (isset($payment_response['data']['payment'])) {
     2603      // Update our payment data with the latest from Square
     2604      $payment_data = $payment_response['data']['payment'];
     2605      $payment_version_token = $payment_data['version_token'] ?? null;
     2606
     2607      // Update the stored square_data with the latest payment data
     2608      $square_data['payment']['data']['payment'] = $payment_data;
     2609      $order->update_meta_data('square_data', json_encode($square_data));
     2610      $order->save();
     2611    }
     2612
     2613    // Validate payment status - can only refund COMPLETED payments
     2614    if ($payment_status !== 'COMPLETED') {
     2615      return new WP_Error(
     2616        'invalid_payment_status',
     2617        sprintf(__('Cannot refund payment with status: %s. Only COMPLETED payments can be refunded.', 'squarewoosync-pro'), $payment_status)
     2618      );
     2619    }
     2620
     2621    // Check payment date (Square only allows refunds within 1 year)
     2622    $payment_date = $payment_data['created_at'] ?? null;
     2623    if ($payment_date) {
     2624      $payment_timestamp = strtotime($payment_date);
     2625      $one_year_ago = strtotime('-1 year');
     2626      if ($payment_timestamp < $one_year_ago) {
     2627        return new WP_Error('payment_too_old', __('Cannot refund payments older than 1 year.', 'squarewoosync-pro'));
     2628      }
     2629    }
     2630
     2631    // Validate refund amount doesn't exceed original payment
     2632    $decimals           = wc_get_price_decimals();           // 0 for JPY, 2 for AUD, 3 for KWD …
     2633    $factor             = (int) pow(10, $decimals);          // 1, 100, 1000 …
     2634    $refund_amount_unit = (int) round($amount * $factor);    // integer for Square
     2635    $original_amount_units = (int) round($original_amount * $factor);    // integer for Square
     2636
     2637    if ($refund_amount_unit > $original_amount_units) {
     2638      return new WP_Error('refund_too_large', __('Refund amount cannot exceed the original payment amount.', 'squarewoosync-pro'));
     2639    }
     2640
     2641    // Initialize Square Helper
     2642    $squareHelper = new SquareHelper();
     2643
     2644    // Prepare refund data
     2645    $refund_data = [
     2646      'idempotency_key' => wp_generate_uuid4(),
     2647      'payment_id' => $payment_id,
     2648      'amount_money' => [
     2649        'amount' => $refund_amount_unit,
     2650        'currency' => $currency
     2651      ]
     2652    ];
     2653
     2654    // Add reason if provided
     2655    if (!empty($reason)) {
     2656      $refund_data['reason'] = $reason;
     2657    }
     2658
     2659    // Add payment version token for optimistic concurrency if available
     2660    if ($payment_version_token) {
     2661      $refund_data['payment_version_token'] = $payment_version_token;
     2662    }
     2663
     2664    // Make refund API request
     2665    $response = $squareHelper->square_api_request('/refunds', 'POST', $refund_data);
     2666
     2667    if (isset($response['error'])) {
     2668      $error_message = is_array($response['error'])
     2669        ? (isset($response['error']['detail']) ? $response['error']['detail'] : json_encode($response['error']))
     2670        : $response['error'];
     2671
     2672      return new WP_Error(
     2673        'refund_api_error',
     2674        sprintf(__('Square refund failed: %s', 'squarewoosync-pro'), $error_message)
     2675      );
     2676    }
     2677
     2678    $refund_response = $response['data']['refund'] ?? null;
     2679    if (!$refund_response) {
     2680      return new WP_Error('invalid_refund_response', __('Invalid refund response from Square.', 'squarewoosync-pro'));
     2681    }
     2682
     2683    $refund_status = $refund_response['status'] ?? null;
     2684    $refund_id = $refund_response['id'] ?? null;
     2685
     2686    // Check if refund was successful
     2687    if (in_array($refund_status, ['PENDING', 'COMPLETED'])) {
     2688      // Store refund information in order meta
     2689      $existing_refunds = get_post_meta($order_id, 'square_refunds', true);
     2690      if (!is_array($existing_refunds)) {
     2691        $existing_refunds = [];
     2692      }
     2693
     2694      $existing_refunds[] = [
     2695        'refund_id' => $refund_id,
     2696        'amount' => $amount,
     2697        'currency' => $currency,
     2698        'status' => $refund_status,
     2699        'reason' => $reason,
     2700        'created_at' => current_time('mysql'),
     2701        'square_response' => $refund_response
     2702      ];
     2703
     2704      update_post_meta($order_id, 'square_refunds', $existing_refunds);
     2705
     2706      // Add order note
     2707      $order->add_order_note(
     2708        sprintf(
     2709          __('Square refund processed successfully. Amount: %1$s, Status: %2$s, Refund ID: %3$s%4$s', 'squarewoosync-pro'),
     2710          wc_price($amount),
     2711          $refund_status,
     2712          $refund_id,
     2713          !empty($reason) ? ', Reason: ' . $reason : ''
     2714        )
     2715      );
     2716
     2717      // Handle inventory restocking if enabled
     2718      $this->handle_refund_inventory_restock($order, $amount, $refund_id);
     2719
     2720      return true;
     2721    } else {
     2722      return new WP_Error(
     2723        'refund_failed',
     2724        sprintf(__('Square refund failed with status: %s', 'squarewoosync-pro'), $refund_status)
     2725      );
     2726    }
     2727  }
     2728
     2729  /**
     2730   * Handle inventory restocking after a successful refund
     2731   *
     2732   * @param WC_Order $order The WooCommerce order
     2733   * @param float $refund_amount The refund amount
     2734   * @param string $refund_id Square refund ID
     2735   * @return void
     2736   */
     2737  private function handle_refund_inventory_restock($order, $refund_amount, $refund_id)
     2738  {
     2739    try {
     2740      // Check if restock was requested in the refund
     2741      $restock_refunded_items = isset($_REQUEST['restock_refunded_items']) &&
     2742        $_REQUEST['restock_refunded_items'] === 'true';
     2743
     2744      if (!$restock_refunded_items) {
     2745        // Add debug log
     2746        $order->add_order_note(
     2747          __('Square inventory restock skipped: "Restock refunded items" was not selected.', 'squarewoosync-pro')
     2748        );
     2749        return;
     2750      }
     2751
     2752      // Get line items - prioritize refund data if available, otherwise use order data
     2753      $refunded_line_items = [];
     2754      // First, try to get refund data line items
     2755      $refunds = $order->get_refunds();
     2756      $latest_refund = !empty($refunds) ? current($refunds) : null;
     2757
     2758      if ($latest_refund && !empty($latest_refund->get_items())) {
     2759        foreach ($latest_refund->get_items() as $item) {
     2760          $quantity = abs($item->get_quantity());  // Get absolute value since refund quantities are negative
     2761          if ($quantity <= 0)
     2762            continue;
     2763
     2764          $refunded_line_items[] = [
     2765            'product_id' => $item->get_product_id(),
     2766            'variation_id' => $item->get_variation_id(),
     2767            'quantity' => $quantity
     2768          ];
     2769        }
     2770      } else {
     2771        // Fallback to order data if no refund line items exist
     2772        $order_items = $order->get_items();
     2773
     2774        foreach ($order_items as $item) {
     2775          $quantity = $item->get_quantity();
     2776          if ($quantity <= 0)
     2777            continue;
     2778
     2779          $refunded_line_items[] = [
     2780            'product_id' => $item->get_product_id(),
     2781            'variation_id' => $item->get_variation_id(),
     2782            'quantity' => $quantity
     2783          ];
     2784        }
     2785      }
     2786
     2787      // Add order note with restock details
     2788      if (!empty($refunded_line_items)) {
     2789        $order->add_order_note(
     2790          sprintf(
     2791            __('Square restock: Preparing to restock %d items', 'squarewoosync-pro'),
     2792            count($refunded_line_items)
     2793          )
     2794        );
     2795      }
     2796
     2797      if (empty($refunded_line_items)) {
     2798        return;  // No items to restock
     2799      }
     2800
     2801      // Prepare inventory data for Square
     2802      $inventory_data = $this->prepare_inventory_restock_data($refunded_line_items);
     2803
     2804      if (empty($inventory_data)) {
     2805        $order->add_order_note(__('Square inventory restock skipped: No valid Square catalog items found.', 'squarewoosync-pro'));
     2806        return;
     2807      }
     2808
     2809      // Initialize Square Helper and update inventory
     2810      $squareHelper = new SquareHelper();
     2811      $inventory_result = $squareHelper->update_inventory($inventory_data);
     2812
     2813      if ($inventory_result['success']) {
     2814        $order->add_order_note(
     2815          sprintf(
     2816            __('Square inventory restocked successfully for refund %1$s. Updated %2$d items.', 'squarewoosync-pro'),
     2817            $refund_id,
     2818            count($inventory_data)
     2819          )
     2820        );
     2821
     2822        // Store inventory restock information in order meta
     2823        $existing_restocks = get_post_meta($order->get_id(), 'square_inventory_restocks', true);
     2824        if (!is_array($existing_restocks)) {
     2825          $existing_restocks = [];
     2826        }
     2827
     2828        $existing_restocks[] = [
     2829          'refund_id' => $refund_id,
     2830          'items_restocked' => count($inventory_data),
     2831          'created_at' => current_time('mysql'),
     2832          'inventory_data' => $inventory_data
     2833        ];
     2834
     2835        update_post_meta($order->get_id(), 'square_inventory_restocks', $existing_restocks);
     2836      } else {
     2837        $error_message = isset($inventory_result['error']) ? $inventory_result['error'] : 'Unknown error';
     2838        $order->add_order_note(
     2839          sprintf(
     2840            __('Square inventory restock failed for refund %1$s: %2$s', 'squarewoosync-pro'),
     2841            $refund_id,
     2842            $error_message
     2843          )
     2844        );
     2845      }
     2846    } catch (Exception $e) {
     2847      $order->add_order_note(
     2848        sprintf(
     2849          __('Square inventory restock error for refund %1$s: %2$s', 'squarewoosync-pro'),
     2850          $refund_id,
     2851          $e->getMessage()
     2852        )
     2853      );
     2854    }
     2855  }
     2856
     2857  /**
     2858   * Prepare inventory data for Square restocking
     2859   *
     2860   * @param array $refunded_items Array of refunded items with product_id, variation_id, quantity
     2861   * @return array Formatted inventory data for Square API
     2862   */
     2863  private function prepare_inventory_restock_data($refunded_items)
     2864  {
     2865    $inventory_data = [];
     2866    $settings = get_option('square-woo-sync_settings', []);
     2867    $location_id = $settings['location'] ?? '';
     2868
     2869    if (empty($location_id)) {
     2870      return $inventory_data;  // No location configured
     2871    }
     2872
     2873    foreach ($refunded_items as $item) {
     2874      $product_id = $item['variation_id'] > 0 ? $item['variation_id'] : $item['product_id'];
     2875      $product = wc_get_product($product_id);
     2876
     2877      if (!$product) {
     2878        continue;
     2879      }
     2880
     2881      // Get Square catalog object ID from product meta
     2882      // For simple products (variation_id = 0), use square_variation_id
     2883      // For variations (variation_id > 0), use square_product_id
     2884      if ($item['variation_id'] > 0) {
     2885        $catalog_object_id = get_post_meta($product_id, 'square_product_id', true);
     2886      } else {
     2887        $catalog_object_id = get_post_meta($product_id, 'square_variation_id', true);
     2888      }
     2889
     2890      if (empty($catalog_object_id)) {
     2891        continue;  // No Square catalog ID found
     2892      }
     2893
     2894      // Get current WooCommerce stock level
     2895      $current_stock = $product->get_stock_quantity();
     2896      if ($current_stock === null || $current_stock === '') {
     2897        $current_stock = 0;  // Default to 0 if stock management is disabled
     2898      }
     2899
     2900      // Calculate total stock after restocking (current + refunded quantity)
     2901      $total_stock_after_restock = $current_stock + $item['quantity'];
     2902
     2903      // Format inventory data according to SquareHelper::update_inventory expectations
     2904      // Square requires the TOTAL stock quantity, not the delta
     2905      $inventory_data[] = [
     2906        'catalog_object_id' => $catalog_object_id,
     2907        'location_id' => $location_id,
     2908        'quantity' => $total_stock_after_restock,  // Total stock quantity after restock
     2909        'state' => 'IN_STOCK'
     2910      ];
     2911    }
     2912
     2913    return $inventory_data;
     2914  }
    19482915}
  • squarewoosync/trunk/includes/REST/OrdersController.php

    r3377796 r3431463  
    288288    $taxes_enabled = get_option('woocommerce_calc_taxes') === 'yes';
    289289    $is_tax_inclusive = get_option('woocommerce_prices_include_tax') === 'yes';
    290     $has_taxes = false;
     290    $tax_uids = [];
    291291
    292292    // Apply tax as additive, Square will calculate based on this.
     
    298298        $tax_percentage = rtrim($tax_percentage_string, '%'); // Strip the "%" symbol, keep it as a string
    299299
     300        // Create unique tax UID using rate ID to avoid duplicates
     301        $tax_uid = 'order-tax-' . $tax_rate_id;
     302
    300303        // Apply tax data to the order
    301304        $order_data['order']['taxes'][] = [
    302           'uid' => 'order-tax', // Unique Tax ID from the order
     305          'uid' => $tax_uid,
    303306          'name' => $item->get_label(),
    304307          'percentage' => $tax_percentage, // Tax percentage
     
    306309          'inclusion_type' => $is_tax_inclusive ? 'INCLUSIVE' : 'ADDITIVE', // Set inclusion type based on WooCommerce setting
    307310        ];
    308         $has_taxes = true;
     311        $tax_uids[] = $tax_uid;
    309312      }
    310313    }
    311314
    312315    // Fetch line items with updated tax handling
    313     $line_items = $this->getOrderLineItems($order, $has_taxes);
     316    $line_items = $this->getOrderLineItems($order, $tax_uids);
    314317    $order_data['order']['line_items'] = $line_items;
    315318
     
    357360  }
    358361
     362  /**
     363   * Get the Square location ID for an order.
     364   * Can be filtered to allow custom location logic based on order properties.
     365   *
     366   * @param \WC_Order $order The WooCommerce order object.
     367   * @return string The Square location ID.
     368   */
     369  public function getLocationId($order)
     370  {
     371    $settings = get_option('square-woo-sync_settings', []);
     372    $location_id = $settings['location'] ?? '';
     373
     374    /**
     375     * Filter the Square location ID for an order.
     376     *
     377     * Allows customization of which Square location to use based on order properties
     378     * such as shipping address, product categories, or custom meta data.
     379     *
     380     * @param string $location_id The default location ID from settings.
     381     * @param \WC_Order $order The WooCommerce order object.
     382     * @return string The filtered location ID.
     383     */
     384    return apply_filters('square_woo_sync_order_location_id', $location_id, $order);
     385  }
    359386
    360387  public function addOrderFeesAsServiceCharges($order): array
     
    530557  }
    531558
    532   public function getOrderLineItems($order, $has_taxes = false): array
     559  public function getOrderLineItems($order, $tax_uids = []): array
    533560  {
    534561    $line_items = [];
     
    586613      ];
    587614
    588       if ($has_taxes) {
    589         $line_item['applied_taxes'] = [
    590           [
    591             'tax_uid' => 'order-tax',
    592           ]
    593         ];
     615      if (!empty($tax_uids)) {
     616        $line_item['applied_taxes'] = array_map(function($uid) {
     617          return ['tax_uid' => $uid];
     618        }, $tax_uids);
    594619      }
    595620
     
    10831108    ], 200);
    10841109  }
     1110
     1111  /**
     1112   * Extract tip amount from order.
     1113   * Free version doesn't support tips, so always returns 0.
     1114   * Premium version would extract tip from order meta.
     1115   *
     1116   * @param \WC_Order $order The WooCommerce order object.
     1117   * @return float The tip amount (always 0 in free version).
     1118   */
     1119  public function extractTipAmount($order)
     1120  {
     1121    // Free version doesn't support tips
     1122    return 0.0;
     1123  }
    10851124}
  • squarewoosync/trunk/includes/Woo/SyncProduct.php

    r3315018 r3431463  
    951951    }
    952952
    953     if ($order->get_payment_method() === 'squaresync_credit') {
     953    // Don't auto-create Square orders for Square payment gateways (they create their own orders)
     954    $square_payment_methods = ['squaresync_credit', 'squaresync_cashapp'];
     955    if (in_array($order->get_payment_method(), $square_payment_methods)) {
    954956      return;
    955957    }
  • squarewoosync/trunk/languages/square-woo-sync.pot

    r3428055 r3431463  
    22msgid ""
    33msgstr ""
    4 "Project-Id-Version: Square Sync for WooCommerce 6.0.6\n"
     4"Project-Id-Version: Square Sync for WooCommerce 6.0.7\n"
    55"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/square-woo-sync\n"
    66"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
     
    99"Content-Type: text/plain; charset=UTF-8\n"
    1010"Content-Transfer-Encoding: 8bit\n"
    11 "POT-Creation-Date: 2025-12-27T03:26:29+00:00\n"
     11"POT-Creation-Date: 2026-01-03T06:23:42+00:00\n"
    1212"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
    1313"X-Generator: WP-CLI 2.12.0\n"
  • squarewoosync/trunk/readme.txt

    r3428055 r3431463  
    66Tested up to: 6.8
    77Requires PHP: 7.4
    8 Stable tag: 6.0.6
     8Stable tag: 6.0.7
    99License: GPLv2 or later
    1010License URI: http://www.gnu.org/licenses/gpl-2.0.html
    1111
    12 Sync WooCommerce and Square in real-time. Easy payments, inventory sync, orders, customer details, and loyalty rewards with SquareSync for Woo.
     12Sync WooCommerce and Square in real-time. Easy payments with Cash App Pay, Google Pay, Apple Pay, Afterpay. Sync inventory, orders, customer details, and loyalty rewards.
    1313
    1414== Description ==
    15 Square for WooCommerce makes your WooCommerce Square integration effortless. Connect WooCommerce directly with Square to automatically sync products, inventory, orders, and customer data. No more manual updates or inventory mismatches. Offer versatile payment options like Google Pay, Apple Pay, Afterpay, and standard credit cards, and keep your store running smoothly with real-time syncing available in the Pro version.
     15Square for WooCommerce makes your WooCommerce Square integration effortless. Connect WooCommerce directly with Square to automatically sync products, inventory, orders, and customer data. No more manual updates or inventory mismatches. Offer versatile payment options like Cash App Pay, Google Pay, Apple Pay, Afterpay, and standard credit cards, and keep your store running smoothly with real-time syncing available in the Pro version.
    1616
    1717### Pro Plugin Demo:
     
    2020## Why Choose SquareSync for Your WooCommerce Square Integration?
    2121
    22 - **More Ways to Pay:** Easily accept Google Pay, Apple Pay, Afterpay, and credit cards at checkout.
     22- **More Ways to Pay:** Easily accept Cash App Pay, Google Pay, Apple Pay, Afterpay, and credit cards at checkout.
    2323-   **Smooth Product Management:** Import and sync products directly from Square to WooCommerce.
    2424-   **Seamless Order & Inventory Updates:** Keep inventory accurate and orders in sync—real-time.
     
    2828## Free Features:
    2929
    30 -   **Flexible Payment Methods:** Add Google Pay, Apple Pay, Afterpay / Clearpay and credit cards.
     30-   **Flexible Payment Methods:** Add Cash App Pay, Google Pay, Apple Pay, Afterpay / Clearpay and credit cards.
    3131-   **WooCommerce Subscriptions Support:** Process re-occuring payments with WooCommerce Subscriptions
    3232-   **WooCommerce Block Checkout Support:** Fully compatible with the latest WooCommerce checkout blocks.
     
    110110
    111111== Changelog ==
     112= 6.0.7 =
     113* Added Cash App Pay payment gateway support
     114* Supports both WooCommerce Blocks and classic checkout
     115* Full integration with Square Payments API
     116
    112117= 6.0.6 =
    113118* Update proxy endpoint.
  • squarewoosync/trunk/squarewoosync.php

    r3428055 r3431463  
    1212 * License URI:     http://www.gnu.org/licenses/gpl-2.0.html
    1313 * Domain Path:     /languages
    14  * Version:         6.0.6
     14 * Version:         6.0.7
    1515 * Requires at least: 5.4
    1616 * Requires PHP:      7.4
     
    3131final class SquareWooSync
    3232{
    33   const VERSION = '6.0.6';
     33  const VERSION = '6.0.7';
    3434  const SLUG = 'squarewoosync';
    3535
     
    190190    if (!in_array($this->container['gateway'], $gateways, true)) {
    191191      $gateways[] = $this->container['gateway'];
     192    }
     193
     194    // Add Cash App Pay gateway if enabled
     195    $gateway_settings = get_option('woocommerce_squaresync_credit_settings', array());
     196    $cashapp_enabled = isset($gateway_settings['enable_cash_app_pay']) && $gateway_settings['enable_cash_app_pay'] === 'yes';
     197
     198    if ($cashapp_enabled) {
     199      if (empty($this->container['cashapp_gateway'])) {
     200        $this->container['cashapp_gateway'] = new \Pixeldev\SquareWooSync\Payments\WC_SquareSync_CashApp_Gateway();
     201      }
     202
     203      if (!in_array($this->container['cashapp_gateway'], $gateways, true)) {
     204        $gateways[] = $this->container['cashapp_gateway'];
     205      }
    192206    }
    193207
     
    249263  {
    250264    if (class_exists('\Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType')) {
     265      // Register main Square gateway blocks support
    251266      $blocks = new WC_SquareSync_Gateway_Blocks_Support;
    252267      $payment_method_registry->register($blocks);
     268
     269      // Register Cash App Pay blocks support if enabled
     270      $gateway_settings = get_option('woocommerce_squaresync_credit_settings', array());
     271      $cashapp_enabled = isset($gateway_settings['enable_cash_app_pay']) && $gateway_settings['enable_cash_app_pay'] === 'yes';
     272
     273      if ($cashapp_enabled) {
     274        $cashapp_blocks = new \Pixeldev\SquareWooSync\Payments\Blocks\WC_SquareSync_CashApp_Gateway_Blocks_Support;
     275        $payment_method_registry->register($cashapp_blocks);
     276      }
    253277    }
    254278  }
  • squarewoosync/trunk/vendor/composer/installed.php

    r3428055 r3431463  
    44        'pretty_version' => 'dev-main',
    55        'version' => 'dev-main',
    6         'reference' => '899b8ab57fa0cf29fd3c03f933aa88a656255b4d',
     6        'reference' => '514bb55f50e8328b14cb0e4ec7ef576abd3d320c',
    77        'type' => 'project',
    88        'install_path' => __DIR__ . '/../../',
     
    1414            'pretty_version' => 'dev-main',
    1515            'version' => 'dev-main',
    16             'reference' => '899b8ab57fa0cf29fd3c03f933aa88a656255b4d',
     16            'reference' => '514bb55f50e8328b14cb0e4ec7ef576abd3d320c',
    1717            'type' => 'project',
    1818            'install_path' => __DIR__ . '/../../',
Note: See TracChangeset for help on using the changeset viewer.