Plugin Directory

Changeset 3193406


Ignore:
Timestamp:
11/20/2024 06:15:56 PM (17 months ago)
Author:
echeckpointplugin
Message:

Completed 2.0.0 release: updated trunk and created tag 2.0.0.

Location:
echeckpoint
Files:
43 added
4 deleted
5 edited
7 copied

Legend:

Unmodified
Added
Removed
  • echeckpoint/tags/2.0.0/ReleaseNotes.txt

    r3184600 r3193406  
     1= 2.00 - 2024.11.14 =
     2* Updated the plugin for compatibility with WooCommerce Block Checkout.
     3
    14= 1.5.1 - 2024.10.29 =
    25* Enhanced error handling for compatibility with WordPress 6.7.
  • echeckpoint/tags/2.0.0/echeckpoint.php

    r3184600 r3193406  
    11<?php
    22/**
    3  * Plugin Name: eCheckpoint
    4  * Description: Robust compliance checks for firearms eCommerce. Verifies whether your customers can purchase products based on federal, state, and local sales laws.
    5  * Version: 1.5.1
    6  * Author: eCheckpoint
    7  * License: GPLv2 or later
    8  * License URI: https://www.gnu.org/licenses/gpl-2.0.html
     3 * Plugin Name:     eCheckpoint
     4 * Description:     Robust compliance checks for firearms eCommerce. Verifies whether your customers can purchase products based on federal, state, and local sales laws.
     5 * Requires at least: 6.6
     6 * Requires PHP:      7.2
     7 * Version:           2.0.0
     8 * Author:          eCheckpoint
     9 * License:         GPL-2.0-or-later
     10 * License URI:     https://www.gnu.org/licenses/gpl-2.0.html
     11 * Text Domain:     echeckpoint
     12 *
     13 * @package         create-block
    914 */
    1015
    11 ///////////////////////////////////////////
    12 // CONTROLLER
    13 // echeckpoint.php
    14 ///////////////////////////////////////////
    15 if (!defined('ABSPATH')) {
    16     exit; // Exit if accessed directly
     16  // Include other parts of the plugin
     17  require_once plugin_dir_path(__FILE__) . 'echeckpoint_settings.php';
     18  require_once plugin_dir_path(__FILE__) . 'echeckpoint_pre-order-check.php';
     19  require_once plugin_dir_path(__FILE__) . 'echeckpoint_post-order-check.php';
     20  require plugin_dir_path(__FILE__) . 'echeckpoint_compliance-fee.php';
     21
     22
     23add_action('woocommerce_blocks_loaded', function() {
     24    require_once __DIR__ . '/echeckpoint-blocks-integration.php';
     25    add_action(
     26        'woocommerce_blocks_cart_block_registration',
     27        function( $integration_registry ) {
     28            $integration_registry->register( new echeckpoint_Blocks_Integration() );
     29        }
     30    );
     31    add_action(
     32        'woocommerce_blocks_checkout_block_registration',
     33        function( $integration_registry ) {
     34            $integration_registry->register( new echeckpoint_Blocks_Integration() );
     35        }
     36    );
     37
     38    add_action( 'init', 'create_block_echeckpoint_block_init' );
     39});
     40
     41add_action( 'before_woocommerce_init', function() {
     42    if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
     43        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', __FILE__, true );
     44    }
     45} );
     46
     47function create_block_echeckpoint_block_init() {
     48    register_block_type( __DIR__ . '/build' );
    1749}
    18 
    19 // Include other parts of the plugin
    20 require_once plugin_dir_path(__FILE__) . 'echeckpoint_settings.php';
    21 require_once plugin_dir_path(__FILE__) . 'echeckpoint_pre-order-check.php';
    22 require_once plugin_dir_path(__FILE__) . 'echeckpoint_post-order-check.php';
    23 require plugin_dir_path(__FILE__) . 'echeckpoint_compliance-fee.php';
    24 
    2550
    2651if (!class_exists('eCheckpoint')) {
     
    4469                'eCheckpoint_Settings_Page',
    4570                ['eCheckpoint_Settings', 'settings_page'],
    46                 plugins_url('images/eCheckpointIcon24x24.png', __FILE__), // Ensure this URL is correct
     71                plugins_url('src/images/eCheckpointIcon24x24.png', __FILE__), // Ensure this URL is correct
    4772                57
    4873            );
     
    5075
    5176        public function enqueue_admin_styles() {
    52             wp_enqueue_style('echeckpoint-admin-styles', plugins_url('css/echeckpoint-admin-styles.css', __FILE__), [], '1.2.2');
     77            wp_enqueue_style('echeckpoint-admin-styles', plugins_url('src/css/echeckpoint-admin-styles.css', __FILE__), [], '1.2.2');
    5378        }
    5479
     
    6994        }
    7095    }
    71 
    7296    new eCheckpoint();
    7397}
  • echeckpoint/tags/2.0.0/echeckpoint_compliance-fee.php

    r3169594 r3193406  
    8484            // Add the fee to the cart if it's greater than 0
    8585            if ($total_fee > 0) {
    86                 WC()->cart->add_fee(esc_html($compliance_fee_message), $total_fee);
    87                
     86                WC()->cart->add_fee(esc_html($compliance_fee_message), $total_fee, false, 'standard');
     87                return $total_fee;   
     88            } else {
     89                return;
    8890            }
    8991        }
  • echeckpoint/tags/2.0.0/echeckpoint_post-order-check.php

    r3169594 r3193406  
    203203                $result = $item['response']['result'];
    204204                $description = isset($item['response']['description']) ? $item['response']['description'] : '';
    205                 $productName = $item['product']['name'];
    206                 $productSKU = $item['product']['sku'];
    207205
    208206                $noteContent = "eCheckpoint: ";
  • echeckpoint/tags/2.0.0/echeckpoint_pre-order-check.php

    r3184600 r3193406  
    1515    {
    1616
     17        public static $clientMessage = [];
     18        public static $total_fee = 0;
    1719        public static function init()
    1820        {
     
    3436            // Hook into WooCommerce thank you page to clear session data
    3537            add_action('woocommerce_thankyou', [__CLASS__, 'clear_wc_session_data_after_order']);
     38
     39            // WooCommerce Blocks specific hooks
     40
     41            //Fires when checkout is updated.
     42            add_action('woocommerce_store_api_cart_update_customer_from_request', [__CLASS__, 'handle_blocks_customer_update'], 10, 2);
     43
     44            add_action('woocommerce_blocks_enqueue_checkout_block_scripts_before', [__CLASS__, 'add_fee'], 10);
     45
     46            add_action('woocommerce_store_api_checkout_order_processed', [__CLASS__, 'verify_fee_added_at_checkout'], 10);
     47
     48        }
     49
     50        public static function verify_fee_added_at_checkout($order)
     51        {
     52            try {
     53                // Check if the client_message cookie is set
     54                if (!isset($_COOKIE['client_message'])) {
     55                    return; // Return immediately to process the order as normal
     56                }
     57
     58                // Sanitize the raw input from the cookie
     59                $raw_client_message = sanitize_text_field(wp_unslash($_COOKIE['client_message']));
     60
     61                // Decode the JSON from the sanitized input
     62                $client_message = json_decode($raw_client_message, true);
     63
     64                // Optionally, log and sanitize the client_message data if it's an array
     65                if (is_array($client_message)) {
     66                    // Sanitize each value in the array for further use
     67                    $client_message = array_map('sanitize_text_field', $client_message);
     68                }
     69
     70                // Check if total_fee is available and valid in the decoded message
     71                if (isset($client_message['total_fee']) && $client_message['total_fee'] > 0) {
     72                    $total_fee = floatval($client_message['total_fee']);
     73
     74                    // Check if the fee with the name '50-State Compliance Fee' already exists in the order
     75                    $existing_fees = $order->get_items('fee');
     76                    foreach ($existing_fees as $existing_fee) {
     77                        if ($existing_fee->get_name() === '50-State Compliance Fee') {
     78                            return; // Fee already exists, do not add a duplicate
     79                        }
     80                    }
     81
     82                    // Add the fee to the order if it does not already exist
     83                    $fee = new WC_Order_Item_Fee();
     84                    $compliance_fee_message = get_option('eCheckpoint_compliance_fee_message', '50-State Compliance Fee');
     85                    $fee->set_name($compliance_fee_message); // Set the fee name
     86                    $fee->set_amount($total_fee); // Set the fee amount
     87                    $fee->set_total($total_fee); // Set the total fee
     88
     89                    // Add the fee to the order
     90                    $order->add_item($fee);
     91
     92                    // Save the order to ensure the fee is included
     93                    $order->calculate_totals();
     94                    $order->save();
     95                } else {
     96                    return; // Return immediately to process the order as normal
     97                }
     98
     99            } catch (Exception $e) {
     100                return; // Return immediately to process the order as normal
     101            }
     102
     103            $order->save(); // Ensure the order updates are saved.
    36104        }
    37105
     
    88156            if (class_exists('WooCommerce') && is_checkout()) {
    89157                $version = time(); // or use a static version number if preferred
    90                 wp_enqueue_script('echeckpoint_pre-order-check', plugin_dir_url(__FILE__) . 'js/echeckpoint_pre-order-check.js', array('jquery'), $version, true);
     158                wp_enqueue_script('echeckpoint_pre-order-check', plugin_dir_url(__FILE__) . 'src/js/echeckpoint_pre-order-check.js', array('jquery'), $version, true);
    91159                // Enqueue CSS (use wp_enqueue_style for CSS files)
    92                 wp_enqueue_style('echeckpoint-admin-styles', plugin_dir_url(__FILE__) . 'css/echeckpoint-admin-styles.css', array(), $version);
     160                wp_enqueue_style('echeckpoint-admin-styles', plugin_dir_url(__FILE__) . 'src/css/echeckpoint-admin-styles.css', array(), $version);
    93161                // Localize the script with parameters, including the nonce
    94162                wp_localize_script('echeckpoint_pre-order-check', 'eCheckpointParams', array(
     
    102170        {
    103171
     172
     173            if (!self::is_checkout_block()) {
     174                setcookie('checkout_block', 'false', time() + 3600, COOKIEPATH, COOKIE_DOMAIN); // 1 hour expiration
     175            }
     176
     177
     178            // Proceed with compliance check on normal request or place order action
    104179            // Use filter_input to safely get the post_data from the POST request
    105180            // Use FILTER_SANITIZE_STRING to properly sanitize the data instead of FILTER_DEFAULT
     
    130205            if (!wp_verify_nonce($nonce, 'echeckpoint_nonce')) {
    131206                wp_die('Invalid nonce.');
    132             } 
     207            }
    133208
    134209            // Check if $post_data is an array or a string, and handle accordingly
     
    240315        {
    241316
    242             $checkbox_checked = isset($checkout_data['ship_to_different_address']) ? (bool) $checkout_data['ship_to_different_address'] : false;
     317            if (self::is_checkout_block()) {
     318                $checkbox_checked = true;
     319            } else {
     320                $checkbox_checked = isset($checkout_data['ship_to_different_address']) ? (bool) $checkout_data['ship_to_different_address'] : false;
     321            }
     322
     323            // Check if billing fields are completed
     324            $billing_complete = self::is_billing_complete($checkout_data);
     325
     326            // Check if shipping fields are completed
     327            $shipping_complete = !$checkbox_checked || self::is_shipping_complete($checkout_data);
    243328
    244329            // Check if billing fields are completed
     
    298383                }
    299384            } catch (Exception $e) {
     385
    300386            }
    301387        }
     
    335421            $show_conditional_fail = isset($options['conditional_fail_checkbox']) && $options['conditional_fail_checkbox'] === 'on';
    336422            $regulatedProducts = [];
     423            $isCheckoutBlock = self::is_checkout_block();
     424            $isECheckpointPassWithoutConditions = true;
    337425            $response = self::api_call_during_checkout($checkout_data);
     426
    338427            if (!$response) {
    339                 wc_add_notice(__('Error: Could not perform compliance check. Please contact Customer Service.', 'echeckpoint'), 'error');
     428                if ($isCheckoutBlock) {
     429                    // Create the client message as a variable
     430                    $client_message_content = __('Error: Could not perform compliance check. Please contact Customer Service.', 'echeckpoint');
     431                    $client_message_type = 'error';
     432
     433                    // Set the client message
     434                    self::$clientMessage = [
     435                        $client_message_content,
     436                        $client_message_type
     437                    ];
     438
     439                    // Set the cookie with the client message
     440                    setcookie(
     441                        'client_message',
     442                        wp_json_encode([
     443                            'message' => $client_message_content,
     444                            'type' => $client_message_type
     445                        ]),
     446                        time() + 1200,  // Cookie expires in 20 minutes
     447                        COOKIEPATH,
     448                        COOKIE_DOMAIN,
     449                        is_ssl(),  // Secure cookie if using HTTPS
     450                        false      // Not HTTPOnly to allow JavaScript access
     451                    );
     452                    $isECheckpointPassWithoutConditions = false;
     453                } else {
     454                    wc_add_notice(__('Error: Could not perform compliance check. Please contact Customer Service.', 'echeckpoint'), 'error');
     455                }
     456
    340457                return;
    341458            }
     
    362479                    $failed_product_list = "<ul><li>" . implode('</li><li>', $failed_product_names) . "</li></ul>";
    363480                    /* translators: %s: failed product list */
    364                     wc_add_notice(sprintf(__('Please contact Customer Service. An issue with some of the products in your order is preventing checkout:<br>%s', 'echeckpoint'), $failed_product_list), 'error');
     481                    if ($isCheckoutBlock) {
     482                        // Create the client message as a variable
     483                        $message_template = __('Please contact Customer Service. An issue with some of the products in your order is preventing checkout:<br>', 'echeckpoint');
     484                        $client_message_content = $message_template . $failed_product_list;
     485                        $client_message_type = 'error';
     486
     487                        // Set the client message
     488                        self::$clientMessage = [
     489                            $client_message_content,
     490                            $client_message_type
     491                        ];
     492
     493                        // Set the cookie with the client message
     494                        setcookie(
     495                            'client_message',
     496                            wp_json_encode([
     497                                'message' => $client_message_content,
     498                                'type' => $client_message_type
     499                            ]),
     500                            time() + 1200,  // Cookie expires in 20 minutes
     501                            COOKIEPATH,
     502                            COOKIE_DOMAIN,
     503                            is_ssl(),  // Secure cookie if using HTTPS
     504                            false      // Not HTTPOnly to allow JavaScript access
     505                        );
     506                        $isECheckpointPassWithoutConditions = false;
     507                    } else {
     508                        $message_template = __('Please contact Customer Service. An issue with some of the products in your order is preventing checkout:<br>', 'echeckpoint');
     509                        $full_message = $message_template . $failed_product_list;
     510                        wc_add_notice($full_message, 'error');
     511                    }
     512
    365513                    $compliance_passed = false;
    366514                }
     
    378526                    // Handling Billing Address Validation
    379527                    if ($billingResponse == 2) { // Validation Failed
    380                         wc_add_notice(__('Your billing address is not valid. To ensure the fastest service for your order, we verify your billing address with the U.S. Postal Service. Please ensure it is correct and try again. If you need assistance locating your official billing address, please look it up here: https://tools.usps.com/zip-code-lookup.htm?byaddress', 'echeckpoint'), 'error');
     528                        if ($isCheckoutBlock) {
     529                            // Create the client message as a variable
     530                            $client_message_content = 'Your billing address is not valid. To ensure the fastest service for your order, we verify your billing address with the U.S. Postal Service. Please ensure it is correct and try again. If you need assistance locating your official billing address, please look it up here: https://tools.usps.com/zip-code-lookup.htm?byaddress';
     531                            $client_message_type = 'error';
     532
     533                            // Set the client message
     534                            self::$clientMessage = [
     535                                $client_message_content,
     536                                $client_message_type
     537                            ];
     538
     539                            // Set the cookie with the client message
     540                            setcookie(
     541                                'client_message',
     542                                wp_json_encode([
     543                                    'message' => $client_message_content,
     544                                    'type' => $client_message_type
     545                                ]),
     546                                time() + 1200,  // Cookie expires in 20 minutes
     547                                COOKIEPATH,
     548                                COOKIE_DOMAIN,
     549                                is_ssl(),  // Secure cookie if using HTTPS
     550                                false      // Not HTTPOnly to allow JavaScript access
     551                            );
     552                            $isECheckpointPassWithoutConditions = false;
     553                        } else {
     554                            wc_add_notice(__('Your billing address is not valid. To ensure the fastest service for your order, we verify your billing address with the U.S. Postal Service. Please ensure it is correct and try again. If you need assistance locating your official billing address, please look it up here: https://tools.usps.com/zip-code-lookup.htm?byaddress', 'echeckpoint'), 'error');
     555                        }
    381556                        $compliance_passed = false; // Set compliance passed flag to false to prevent checkout
    382557                    }
     
    384559                    // Handling Shipping Address Validation
    385560                    if ($shippingResponse == 2) { // Validation Failed
    386                         wc_add_notice(__('Your shipping address is not valid. To ensure the fastest service for your order, we verify your shipping address with the U.S. Postal Service. Please ensure it is correct and try again. If you need assistance locating your official shipping address, please look it up here: https://tools.usps.com/zip-code-lookup.htm?byaddress', 'echeckpoint'), 'error');
     561                        if ($isCheckoutBlock) {
     562                            // Create the client message as a variable
     563                            $client_message_content = 'Your shipping address is not valid. To ensure the fastest service for your order, we verify your shipping address with the U.S. Postal Service. Please ensure it is correct and try again. If you need assistance locating your official shipping address, please look it up here: https://tools.usps.com/zip-code-lookup.htm?byaddress';
     564                            $client_message_type = 'error';
     565
     566                            // Set the client message
     567                            self::$clientMessage = [
     568                                $client_message_content,
     569                                $client_message_type
     570                            ];
     571
     572                            // Set the cookie with the client message
     573                            setcookie(
     574                                'client_message',
     575                                wp_json_encode([
     576                                    'message' => $client_message_content,
     577                                    'type' => $client_message_type
     578                                ]),
     579                                time() + 1200,  // Cookie expires in 20 minutes
     580                                COOKIEPATH,
     581                                COOKIE_DOMAIN,
     582                                is_ssl(),  // Secure cookie if using HTTPS
     583                                false      // Not HTTPOnly to allow JavaScript access
     584                            );
     585                            $isECheckpointPassWithoutConditions = false;
     586                        } else {
     587                            wc_add_notice(__('Your shipping address is not valid. To ensure the fastest service for your order, we verify your shipping address with the U.S. Postal Service. Please ensure it is correct and try again. If you need assistance locating your official shipping address, please look it up here: https://tools.usps.com/zip-code-lookup.htm?byaddress', 'echeckpoint'), 'error');
     588                        }
    387589                        $compliance_passed = false; // Set compliance passed flag to false to prevent checkout
    388590                    }
    389                 }
    390             }
     591                }
     592            }
     593
    391594
    392595            // Regional Restrictions Check
     
    407610                        if (isset($item['businessTradeTypes'])) {
    408611                            $business_trade_types = $item['businessTradeTypes'];
     612                            // Log the businessTradeTypes to ensure it is being received correctly
    409613                            $additional_requirements = self::get_additional_requirements_message($business_trade_types);
    410                            
    411614                            if ($product) {
    412615                                /* translators: 1: product name, 2: additional requirements */
    413616                                $message = sprintf(__('To complete the purchase of %1$s, additional information will be required after checkout.  Eligible purchasers include: %2$s', 'echeckpoint'), $product->get_name(), $additional_requirements);
    414617                                $conditional_fail_messages[] = $message;
     618                                // Log the final message
    415619                            } else {
    416620                                /* translators: 1: SKU, 2: additional requirements */
    417621                                $message = sprintf(__('To complete the purchase of this SKU, %1$s, additional information will be required after checkout.  Eligible purchasers include: %2$s', 'echeckpoint'), $item['response']['productID'], $additional_requirements);
    418622                                $conditional_fail_messages[] = $message;
     623                                // Log the final message
    419624                            }
    420625                        }
     626                    } elseif (isset($item['response']['result']) && $item['response']['result'] == 3 && !$show_conditional_fail & $isCheckoutBlock) {
     627                        $client_message_content = 'show_conditional_fail disabled';
     628                        $client_message_type = 'N/A';
     629
     630                        // Set the client message
     631                        self::$clientMessage = [
     632                            $client_message_content,
     633                            $client_message_type
     634                        ];
     635
     636                        // Set the cookie with the client message
     637                        setcookie(
     638                            'client_message',
     639                            wp_json_encode([
     640                                'message' => $client_message_content,
     641                                'type' => $client_message_type
     642                            ]),
     643                            time() + 1200,  // Cookie expires in 20 minutes
     644                            COOKIEPATH,
     645                            COOKIE_DOMAIN,
     646                            is_ssl(),  // Secure cookie if using HTTPS
     647                            false      // Not HTTPOnly to allow JavaScript access
     648                        );
     649                        $isECheckpointPassWithoutConditions = false;
    421650                    }
    422651                    if (isset($item['regulatedProduct']) && $item['regulatedProduct'] === true) {
    423                         $product_id = wc_get_product_id_by_sku($item['response']['productID']);             
     652                        $product_id = wc_get_product_id_by_sku($item['response']['productID']);
     653
    424654                        $product = wc_get_product($product_id);
    425655                        array_push($regulatedProducts, $product->get_name());
     
    428658
    429659                if (count($regulatedProducts) > 0) {
    430                     // Hook into WooCommerce's fee calculation lifecycle
    431                     add_action('woocommerce_cart_calculate_fees', function () use ($regulatedProducts) {
    432                         eCheckpoint_Compliance_Fee::ComplianceFee_calculate($regulatedProducts);
    433                     }, 20);
    434                 }
     660                    // Define the fee calculation action
     661                    $calculate_fees_action = function () use ($regulatedProducts) {
     662                        // if (is_admin() && !defined('DOING_AJAX')) {
     663                        //  return; // Prevent running in the admin area except for AJAX
     664                        // }
     665
     666                        // Calculate and log the fee
     667                        self::$total_fee = eCheckpoint_Compliance_Fee::ComplianceFee_calculate($regulatedProducts);
     668                    };
     669
     670                    // Attach the fee calculation action to the WooCommerce hook
     671                    add_action('woocommerce_cart_calculate_fees', $calculate_fees_action, 20);
     672
     673                    // Manually trigger the hook to ensure it runs on page load
     674                    // Wrap this in a check to ensure it is only triggered once on page load, not within the context of an existing `woocommerce_cart_calculate_fees` execution.
     675                    if (!did_action('woocommerce_cart_calculate_fees')) {
     676                        do_action('woocommerce_cart_calculate_fees');
     677                    }
     678                }
     679
     680
    435681
    436682                if (!empty($failed_product_names)) {
    437683                    $failed_product_list = "<ul>" . implode('', $failed_product_names) . "</ul>";
    438684                    /* translators: %s: failed product list */
    439                     wc_add_notice(sprintf(__('The following items cannot be shipped to your location due to company policy or federal, state, or local regulations. Please remove these items from your cart to proceed with checkout.: %s', 'echeckpoint'), $failed_product_list), 'error');
     685                    if ($isCheckoutBlock) {
     686
     687                        // Create the client message as a variable
     688                        $message_template = __('The following items cannot be shipped to your location due to company policy or federal, state, or local regulations. Please remove these items from your cart to proceed with checkout:', 'echeckpoint');
     689                        $client_message_content = $message_template . '<br>' . $failed_product_list;
     690
     691
     692                        $client_message_type = 'error';
     693
     694                        // Set the client message
     695                        self::$clientMessage = [
     696                            $client_message_content,
     697                            $client_message_type
     698                        ];
     699
     700                        // Set the cookie with the client message
     701                        setcookie(
     702                            'client_message',
     703                            wp_json_encode([
     704                                'message' => $client_message_content,
     705                                'type' => $client_message_type
     706                            ]),
     707                            time() + 1200,  // Cookie expires in 20 minutes
     708                            COOKIEPATH,
     709                            COOKIE_DOMAIN,
     710                            is_ssl(),  // Secure cookie if using HTTPS
     711                            false      // Not HTTPOnly to allow JavaScript access
     712                        );
     713                        $isECheckpointPassWithoutConditions = false;
     714                        return;
     715                    } else {
     716                        // Create the notice message as a variable
     717                        $message_template = __('The following items cannot be shipped to your location due to company policy or federal, state, or local regulations. Please remove these items from your cart to proceed with checkout.:', 'echeckpoint');
     718                        $notice_message = $message_template . ' ' . $failed_product_list;
     719
     720                        // Add the notice using the variable
     721                        wc_add_notice($notice_message, 'error');
     722                    }
    440723                    $compliance_passed = false;
    441724                }
     
    446729            if (!empty($conditional_fail_messages)) {
    447730                $conditional_fail_messages[] = __('If you are not eligible to purchase these products, please remove them from your shopping cart.', 'echeckpoint');
    448                 wc_add_notice(implode('<br>', $conditional_fail_messages), 'success');
    449             }
    450 
     731                if ($isCheckoutBlock) {
     732                    // Create the client message as a variable
     733                    $client_message_content = implode('<br>', $conditional_fail_messages);
     734                    $client_message_type = 'info';
     735                    $client_message_total_fee = self::$total_fee;
     736
     737                    // Set the client message
     738                    self::$clientMessage = [
     739                        $client_message_content,
     740                        $client_message_type,
     741                        $client_message_total_fee
     742                    ];
     743
     744                    // Set the cookie with the client message
     745                    setcookie(
     746                        'client_message',
     747                        wp_json_encode([
     748                            'message' => $client_message_content,
     749                            'type' => $client_message_type,
     750                            'total_fee' => $client_message_total_fee
     751                        ]),
     752                        time() + 1200,  // Cookie expires in 20 minutes
     753                        COOKIEPATH,
     754                        COOKIE_DOMAIN,
     755                        is_ssl(),  // Secure cookie if using HTTPS
     756                        false      // Not HTTPOnly to allow JavaScript access
     757                    );
     758                    $isECheckpointPassWithoutConditions = false;
     759                } else {
     760                    // Combine the conditional failure messages into a single notice string
     761                    $notice_message = implode('<br>', $conditional_fail_messages);
     762                    // Add the notice using the variable
     763                    wc_add_notice($notice_message, 'notice');
     764                    WC()->session->set('wc_notices', WC()->session->get('wc_notices'));
     765                }
     766
     767            }
    451768
    452769            if (!$compliance_passed) {
     
    454771            }
    455772
     773            if ($isCheckoutBlock && $isECheckpointPassWithoutConditions) {
     774                // Create the client message as a variable
     775                $client_message_content = 'compliance passed.';
     776                $client_message_type = 'N/A';
     777
     778                // Set the client message
     779                self::$clientMessage = [
     780                    $client_message_content,
     781                    $client_message_type
     782                ];
     783
     784                // Set the cookie with the client message
     785                setcookie(
     786                    'client_message',
     787                    wp_json_encode([
     788                        'message' => $client_message_content,
     789                        'type' => $client_message_type
     790                    ]),
     791                    time() + 1200,  // Cookie expires in 20 minutes
     792                    COOKIEPATH,
     793                    COOKIE_DOMAIN,
     794                    is_ssl(),  // Secure cookie if using HTTPS
     795                    false      // Not HTTPOnly to allow JavaScript access
     796                );
     797            }
     798
     799            self::log_cart_details_on_checkout();
     800
    456801        }
    457802
    458803        public static function api_call_during_checkout($checkout_data)
    459804        {
    460        
     805
    461806            if (!self::pre_order_active())
    462807                return;
     
    559904            $billing_complete = self::is_billing_complete($checkout_data);
    560905            $shipping_complete = self::is_shipping_complete($checkout_data);
    561             $checkbox_checked = isset($checkout_data['ship_to_different_address']) ? (bool) $checkout_data['ship_to_different_address'] : false;
     906
     907            if (self::is_checkout_block()) {
     908                $checkbox_checked = true;
     909            } else {
     910                $checkbox_checked = isset($checkout_data['ship_to_different_address']) ? (bool) $checkout_data['ship_to_different_address'] : false;
     911            }
    562912
    563913            if ($checkbox_checked && $shipping_complete) {
     
    634984            }
    635985
    636             // Convert to unordered list with reduced margin
    637             $result = '<ul style="margin-bottom: 0;"><li>' . implode('</li><li>', $requirements) . '</li></ul>';
     986            if (self::is_checkout_block()) {
     987                // Prepend &emsp;&ensp; to each requirement item
     988                $requirements = array_map(fn($item) => '&emsp;&ensp;' . $item, $requirements);
     989
     990                // Use implode with <br> between each item and wrap with additional <br> tags
     991                $result = '<br>' . implode('<br>', $requirements) . '<br>';
     992
     993            } else {
     994                // Convert to unordered list with reduced margin
     995                $result = '<ul style="margin-bottom: 0;"><li>' . implode('</li><li>', $requirements) . '</li></ul>';
     996            }
    638997            return $result;
    639998        }
     999
     1000        /***************************************************************************************************** */
     1001        // WOOCOMMERCE CHECKOUT BLOCK
     1002/***************************************************************************************************** */
     1003        public static function add_fee()
     1004        {
     1005            if (!self::is_checkout_block()) {
     1006                return;
     1007            }
     1008
     1009            // Run compliance check; adapt this call if parameters are needed
     1010            eCheckpoint_Pre_Order_Checks::check_required_fields_and_run_compliance_blocks();
     1011        }
     1012
     1013        public static function log_cart_details_on_checkout()
     1014        {
     1015            if (!WC()->cart) {
     1016                return;
     1017            }
     1018
     1019            $cart_items = WC()->cart->get_cart();
     1020            $log_data = [];
     1021
     1022            // Log details for each product in the cart
     1023            foreach ($cart_items as $cart_item_key => $cart_item) {
     1024                $product = $cart_item['data'];
     1025
     1026                $log_data['Products'][] = [
     1027                    'Product Name' => $product->get_name(),
     1028                    'Product ID' => $product->get_id(),
     1029                    'SKU' => $product->get_sku(),
     1030                    'Quantity' => $cart_item['quantity'],
     1031                    'Price' => wc_price($product->get_price()),
     1032                    'Subtotal' => wc_price($cart_item['line_subtotal']),
     1033                    'Total' => wc_price($cart_item['line_total'])
     1034                ];
     1035            }
     1036
     1037            // Log any fees applied in the cart
     1038            $fees = WC()->cart->get_fees();
     1039            if (!empty($fees)) {
     1040                foreach ($fees as $fee) {
     1041                    $log_data['Fees'][] = [
     1042                        'Fee Name' => $fee->name,
     1043                        'Amount' => wc_price($fee->amount)
     1044                    ];
     1045                }
     1046            } else {
     1047                $log_data['Fees'] = 'No fees applied';
     1048            }
     1049
     1050            // Log cart totals
     1051            $log_data['Cart Totals'] = [
     1052                'Cart Total (excluding tax)' => wc_price(WC()->cart->cart_contents_total),
     1053                'Total Tax' => wc_price(WC()->cart->get_cart_contents_tax() + WC()->cart->get_shipping_tax()),
     1054                'Fees Total' => wc_price(WC()->cart->get_fee_total()),
     1055                'Shipping Total' => wc_price(WC()->cart->get_shipping_total()),
     1056                'Grand Total' => wc_price(WC()->cart->get_total(''))
     1057            ];
     1058        }
     1059
     1060
     1061        public static function run_compliance_check()
     1062        {
     1063            //Verify nonce if needed for security
     1064            if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'echeckpoint_nonce')) {
     1065                wp_send_json_error('Invalid nonce');
     1066            }
     1067
     1068
     1069            if (!self::is_checkout_block()) {
     1070                return;
     1071            }
     1072
     1073            // Run compliance check; adapt this call if parameters are needed
     1074            $result = eCheckpoint_Pre_Order_Checks::check_required_fields_and_run_compliance_blocks();
     1075            //If the compliance check passes, set the cookie
     1076            if (!empty(self::$clientMessage)) {
     1077                $data = array(
     1078                    'messages' => isset(self::$clientMessage[0]) ? self::$clientMessage[0] : '', // Default to an empty string if not set
     1079                    'notice' => isset(self::$clientMessage[1]) ? self::$clientMessage[1] : 'info', // Default notice type
     1080                    'total_fee' => isset(self::$clientMessage[2]) ? self::$clientMessage[2] : 0 // Default to 0 if not set
     1081                );
     1082                wp_send_json_success($data);
     1083            } else {
     1084                wp_send_json_error('Compliance check failed, cookie not set.');
     1085            }
     1086        }
     1087
     1088        // Handle customer update for WooCommerce Blocks
     1089
     1090        public static function handle_blocks_customer_update($customer, $request)
     1091        {
     1092
     1093            if (!self::is_checkout_block()) {
     1094                return;
     1095            }
     1096
     1097            // Get billing and shipping addresses from the customer object directly
     1098            $billing_address = array(
     1099                'first_name' => $customer->get_billing_first_name(),
     1100                'last_name' => $customer->get_billing_last_name(),
     1101                'address_1' => $customer->get_billing_address_1(),
     1102                'address_2' => $customer->get_billing_address_2(),
     1103                'city' => $customer->get_billing_city(),
     1104                'state' => $customer->get_billing_state(),
     1105                'postcode' => $customer->get_billing_postcode(),
     1106                'country' => $customer->get_billing_country(),
     1107                'phone' => $customer->get_billing_phone(),
     1108                'email' => $customer->get_billing_email()
     1109            );
     1110
     1111            $shipping_address = array(
     1112                'first_name' => $customer->get_shipping_first_name(),
     1113                'last_name' => $customer->get_shipping_last_name(),
     1114                'address_1' => $customer->get_shipping_address_1(),
     1115                'address_2' => $customer->get_shipping_address_2(),
     1116                'city' => $customer->get_shipping_city(),
     1117                'state' => $customer->get_shipping_state(),
     1118                'postcode' => $customer->get_shipping_postcode(),
     1119                'country' => $customer->get_shipping_country()
     1120            );
     1121
     1122
     1123            // Store the complete billing and shipping addresses in session
     1124            WC()->session->set('billing_address', $billing_address);
     1125            WC()->session->set('shipping_address', $shipping_address);
     1126
     1127            // Create checkout_data array from the customer object
     1128            $checkout_data = array(
     1129                'billing_first_name' => $billing_address['first_name'],
     1130                'billing_last_name' => $billing_address['last_name'],
     1131                'billing_address_1' => $billing_address['address_1'],
     1132                'billing_address_2' => $billing_address['address_2'],
     1133                'billing_city' => $billing_address['city'],
     1134                'billing_state' => $billing_address['state'],
     1135                'billing_postcode' => $billing_address['postcode'],
     1136                'billing_country' => $billing_address['country'],
     1137                'billing_phone' => $billing_address['phone'],
     1138                'billing_email' => $billing_address['email'],
     1139                'shipping_first_name' => $shipping_address['first_name'],
     1140                'shipping_last_name' => $shipping_address['last_name'],
     1141                'shipping_address_1' => $shipping_address['address_1'],
     1142                'shipping_address_2' => $shipping_address['address_2'],
     1143                'shipping_city' => $shipping_address['city'],
     1144                'shipping_state' => $shipping_address['state'],
     1145                'shipping_postcode' => $shipping_address['postcode'],
     1146                'shipping_country' => $shipping_address['country']
     1147            );
     1148
     1149
     1150            // Use the new helper function to check if address fields have been updated
     1151            if (!self::is_address_update($checkout_data)) {
     1152
     1153                return; // Exit the function early if no critical fields have been updated
     1154            }
     1155
     1156            // Prepare data to check for compliance
     1157            $data_to_check = array(
     1158                'billing_first_name' => sanitize_text_field($checkout_data['billing_first_name'] ?? ''),
     1159                'billing_last_name' => sanitize_text_field($checkout_data['billing_last_name'] ?? ''),
     1160                'billing_address_1' => sanitize_text_field($checkout_data['billing_address_1'] ?? ''),
     1161                'billing_address_2' => sanitize_text_field($checkout_data['billing_address_2'] ?? ''),
     1162                'billing_city' => sanitize_text_field($checkout_data['billing_city'] ?? ''),
     1163                'billing_state' => sanitize_text_field($checkout_data['billing_state'] ?? ''),
     1164                'billing_postcode' => sanitize_text_field($checkout_data['billing_postcode'] ?? ''),
     1165                'billing_email' => sanitize_email($checkout_data['billing_email'] ?? ''),
     1166                'ship_to_different_address' => !empty($checkout_data['ship_to_different_address']) ? '1' : '0',
     1167                'shipping_first_name' => sanitize_text_field($checkout_data['shipping_first_name'] ?? ''),
     1168                'shipping_last_name' => sanitize_text_field($checkout_data['shipping_last_name'] ?? ''),
     1169                'shipping_address_1' => sanitize_text_field($checkout_data['shipping_address_1'] ?? ''),
     1170                'shipping_address_2' => sanitize_text_field($checkout_data['shipping_address_2'] ?? ''),
     1171                'shipping_city' => sanitize_text_field($checkout_data['shipping_city'] ?? ''),
     1172                'shipping_state' => sanitize_text_field($checkout_data['shipping_state'] ?? ''),
     1173                'shipping_postcode' => sanitize_text_field($checkout_data['shipping_postcode'] ?? '')
     1174            );
     1175
     1176            if (self::are_required_fields_completed($data_to_check)) {
     1177                // Run the compliance check
     1178                self::trigger_compliance_check($data_to_check);
     1179            }
     1180
     1181        }
     1182
     1183        public static function check_required_fields_and_run_compliance_blocks()
     1184        {
     1185
     1186            if (!self::is_checkout_block()) {
     1187                return;
     1188            }
     1189
     1190            // Log the 'customer' session data
     1191            $customer_data = WC()->session->get('customer', []);
     1192
     1193            $checkout_data = array(
     1194                'billing_first_name' => $customer_data['first_name'] ?? '',
     1195                'billing_last_name' => $customer_data['last_name'] ?? '',
     1196                'billing_address_1' => $customer_data['address_1'] ?? '',
     1197                'billing_city' => $customer_data['city'] ?? '',
     1198                'billing_state' => $customer_data['state'] ?? '',
     1199                'billing_email' => $customer_data['email'] ?? '',
     1200                'billing_postcode' => $customer_data['postcode'] ?? '',
     1201                'shipping_first_name' => $customer_data['shipping_first_name'] ?? '',
     1202                'shipping_last_name' => $customer_data['shipping_last_name'] ?? '',
     1203                'shipping_address_1' => $customer_data['shipping_address_1'] ?? '',
     1204                'shipping_city' => $customer_data['shipping_city'] ?? '',
     1205                'shipping_state' => $customer_data['shipping_state'] ?? '',
     1206                'shipping_postcode' => $customer_data['shipping_postcode'] ?? ''
     1207            );
     1208
     1209            // Use the new helper function to check if address fields have been updated
     1210            if (!self::is_address_update($checkout_data)) {
     1211                return; // Exit the function early if no critical fields have been updated
     1212            }
     1213
     1214            // Prepare data to check for compliance
     1215            $data_to_check = array(
     1216                'billing_first_name' => sanitize_text_field($checkout_data['billing_first_name'] ?? ''),
     1217                'billing_last_name' => sanitize_text_field($checkout_data['billing_last_name'] ?? ''),
     1218                'billing_address_1' => sanitize_text_field($checkout_data['billing_address_1'] ?? ''),
     1219                'billing_address_2' => sanitize_text_field($checkout_data['billing_address_2'] ?? ''),
     1220                'billing_city' => sanitize_text_field($checkout_data['billing_city'] ?? ''),
     1221                'billing_state' => sanitize_text_field($checkout_data['billing_state'] ?? ''),
     1222                'billing_postcode' => sanitize_text_field($checkout_data['billing_postcode'] ?? ''),
     1223                'billing_email' => sanitize_email($checkout_data['billing_email'] ?? ''),
     1224                'ship_to_different_address' => !empty($checkout_data['ship_to_different_address']) ? '1' : '0',
     1225                'shipping_first_name' => sanitize_text_field($checkout_data['shipping_first_name'] ?? ''),
     1226                'shipping_last_name' => sanitize_text_field($checkout_data['shipping_last_name'] ?? ''),
     1227                'shipping_address_1' => sanitize_text_field($checkout_data['shipping_address_1'] ?? ''),
     1228                'shipping_address_2' => sanitize_text_field($checkout_data['shipping_address_2'] ?? ''),
     1229                'shipping_city' => sanitize_text_field($checkout_data['shipping_city'] ?? ''),
     1230                'shipping_state' => sanitize_text_field($checkout_data['shipping_state'] ?? ''),
     1231                'shipping_postcode' => sanitize_text_field($checkout_data['shipping_postcode'] ?? '')
     1232            );
     1233
     1234
     1235            $result = self::are_required_fields_completed($data_to_check);
     1236
     1237            if ($result) {
     1238                // Run the compliance check
     1239                self::trigger_compliance_check($data_to_check);
     1240            }
     1241        }
     1242
     1243        public static function is_checkout_block()
     1244        {
     1245            $result = WC_Blocks_Utils::has_block_in_page(wc_get_page_id('checkout'), 'woocommerce/checkout');
     1246
     1247            return $result;
     1248        }
     1249
     1250
    6401251    }
    6411252}
  • echeckpoint/trunk/ReleaseNotes.txt

    r3184600 r3193406  
     1= 2.00 - 2024.11.14 =
     2* Updated the plugin for compatibility with WooCommerce Block Checkout.
     3
    14= 1.5.1 - 2024.10.29 =
    25* Enhanced error handling for compatibility with WordPress 6.7.
  • echeckpoint/trunk/echeckpoint.php

    r3184600 r3193406  
    11<?php
    22/**
    3  * Plugin Name: eCheckpoint
    4  * Description: Robust compliance checks for firearms eCommerce. Verifies whether your customers can purchase products based on federal, state, and local sales laws.
    5  * Version: 1.5.1
    6  * Author: eCheckpoint
    7  * License: GPLv2 or later
    8  * License URI: https://www.gnu.org/licenses/gpl-2.0.html
     3 * Plugin Name:     eCheckpoint
     4 * Description:     Robust compliance checks for firearms eCommerce. Verifies whether your customers can purchase products based on federal, state, and local sales laws.
     5 * Requires at least: 6.6
     6 * Requires PHP:      7.2
     7 * Version:           2.0.0
     8 * Author:          eCheckpoint
     9 * License:         GPL-2.0-or-later
     10 * License URI:     https://www.gnu.org/licenses/gpl-2.0.html
     11 * Text Domain:     echeckpoint
     12 *
     13 * @package         create-block
    914 */
    1015
    11 ///////////////////////////////////////////
    12 // CONTROLLER
    13 // echeckpoint.php
    14 ///////////////////////////////////////////
    15 if (!defined('ABSPATH')) {
    16     exit; // Exit if accessed directly
     16  // Include other parts of the plugin
     17  require_once plugin_dir_path(__FILE__) . 'echeckpoint_settings.php';
     18  require_once plugin_dir_path(__FILE__) . 'echeckpoint_pre-order-check.php';
     19  require_once plugin_dir_path(__FILE__) . 'echeckpoint_post-order-check.php';
     20  require plugin_dir_path(__FILE__) . 'echeckpoint_compliance-fee.php';
     21
     22
     23add_action('woocommerce_blocks_loaded', function() {
     24    require_once __DIR__ . '/echeckpoint-blocks-integration.php';
     25    add_action(
     26        'woocommerce_blocks_cart_block_registration',
     27        function( $integration_registry ) {
     28            $integration_registry->register( new echeckpoint_Blocks_Integration() );
     29        }
     30    );
     31    add_action(
     32        'woocommerce_blocks_checkout_block_registration',
     33        function( $integration_registry ) {
     34            $integration_registry->register( new echeckpoint_Blocks_Integration() );
     35        }
     36    );
     37
     38    add_action( 'init', 'create_block_echeckpoint_block_init' );
     39});
     40
     41add_action( 'before_woocommerce_init', function() {
     42    if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
     43        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', __FILE__, true );
     44    }
     45} );
     46
     47function create_block_echeckpoint_block_init() {
     48    register_block_type( __DIR__ . '/build' );
    1749}
    18 
    19 // Include other parts of the plugin
    20 require_once plugin_dir_path(__FILE__) . 'echeckpoint_settings.php';
    21 require_once plugin_dir_path(__FILE__) . 'echeckpoint_pre-order-check.php';
    22 require_once plugin_dir_path(__FILE__) . 'echeckpoint_post-order-check.php';
    23 require plugin_dir_path(__FILE__) . 'echeckpoint_compliance-fee.php';
    24 
    2550
    2651if (!class_exists('eCheckpoint')) {
     
    4469                'eCheckpoint_Settings_Page',
    4570                ['eCheckpoint_Settings', 'settings_page'],
    46                 plugins_url('images/eCheckpointIcon24x24.png', __FILE__), // Ensure this URL is correct
     71                plugins_url('src/images/eCheckpointIcon24x24.png', __FILE__), // Ensure this URL is correct
    4772                57
    4873            );
     
    5075
    5176        public function enqueue_admin_styles() {
    52             wp_enqueue_style('echeckpoint-admin-styles', plugins_url('css/echeckpoint-admin-styles.css', __FILE__), [], '1.2.2');
     77            wp_enqueue_style('echeckpoint-admin-styles', plugins_url('src/css/echeckpoint-admin-styles.css', __FILE__), [], '1.2.2');
    5378        }
    5479
     
    6994        }
    7095    }
    71 
    7296    new eCheckpoint();
    7397}
  • echeckpoint/trunk/echeckpoint_compliance-fee.php

    r3169594 r3193406  
    8484            // Add the fee to the cart if it's greater than 0
    8585            if ($total_fee > 0) {
    86                 WC()->cart->add_fee(esc_html($compliance_fee_message), $total_fee);
    87                
     86                WC()->cart->add_fee(esc_html($compliance_fee_message), $total_fee, false, 'standard');
     87                return $total_fee;   
     88            } else {
     89                return;
    8890            }
    8991        }
  • echeckpoint/trunk/echeckpoint_post-order-check.php

    r3169594 r3193406  
    203203                $result = $item['response']['result'];
    204204                $description = isset($item['response']['description']) ? $item['response']['description'] : '';
    205                 $productName = $item['product']['name'];
    206                 $productSKU = $item['product']['sku'];
    207205
    208206                $noteContent = "eCheckpoint: ";
  • echeckpoint/trunk/echeckpoint_pre-order-check.php

    r3184600 r3193406  
    1515    {
    1616
     17        public static $clientMessage = [];
     18        public static $total_fee = 0;
    1719        public static function init()
    1820        {
     
    3436            // Hook into WooCommerce thank you page to clear session data
    3537            add_action('woocommerce_thankyou', [__CLASS__, 'clear_wc_session_data_after_order']);
     38
     39            // WooCommerce Blocks specific hooks
     40
     41            //Fires when checkout is updated.
     42            add_action('woocommerce_store_api_cart_update_customer_from_request', [__CLASS__, 'handle_blocks_customer_update'], 10, 2);
     43
     44            add_action('woocommerce_blocks_enqueue_checkout_block_scripts_before', [__CLASS__, 'add_fee'], 10);
     45
     46            add_action('woocommerce_store_api_checkout_order_processed', [__CLASS__, 'verify_fee_added_at_checkout'], 10);
     47
     48        }
     49
     50        public static function verify_fee_added_at_checkout($order)
     51        {
     52            try {
     53                // Check if the client_message cookie is set
     54                if (!isset($_COOKIE['client_message'])) {
     55                    return; // Return immediately to process the order as normal
     56                }
     57
     58                // Sanitize the raw input from the cookie
     59                $raw_client_message = sanitize_text_field(wp_unslash($_COOKIE['client_message']));
     60
     61                // Decode the JSON from the sanitized input
     62                $client_message = json_decode($raw_client_message, true);
     63
     64                // Optionally, log and sanitize the client_message data if it's an array
     65                if (is_array($client_message)) {
     66                    // Sanitize each value in the array for further use
     67                    $client_message = array_map('sanitize_text_field', $client_message);
     68                }
     69
     70                // Check if total_fee is available and valid in the decoded message
     71                if (isset($client_message['total_fee']) && $client_message['total_fee'] > 0) {
     72                    $total_fee = floatval($client_message['total_fee']);
     73
     74                    // Check if the fee with the name '50-State Compliance Fee' already exists in the order
     75                    $existing_fees = $order->get_items('fee');
     76                    foreach ($existing_fees as $existing_fee) {
     77                        if ($existing_fee->get_name() === '50-State Compliance Fee') {
     78                            return; // Fee already exists, do not add a duplicate
     79                        }
     80                    }
     81
     82                    // Add the fee to the order if it does not already exist
     83                    $fee = new WC_Order_Item_Fee();
     84                    $compliance_fee_message = get_option('eCheckpoint_compliance_fee_message', '50-State Compliance Fee');
     85                    $fee->set_name($compliance_fee_message); // Set the fee name
     86                    $fee->set_amount($total_fee); // Set the fee amount
     87                    $fee->set_total($total_fee); // Set the total fee
     88
     89                    // Add the fee to the order
     90                    $order->add_item($fee);
     91
     92                    // Save the order to ensure the fee is included
     93                    $order->calculate_totals();
     94                    $order->save();
     95                } else {
     96                    return; // Return immediately to process the order as normal
     97                }
     98
     99            } catch (Exception $e) {
     100                return; // Return immediately to process the order as normal
     101            }
     102
     103            $order->save(); // Ensure the order updates are saved.
    36104        }
    37105
     
    88156            if (class_exists('WooCommerce') && is_checkout()) {
    89157                $version = time(); // or use a static version number if preferred
    90                 wp_enqueue_script('echeckpoint_pre-order-check', plugin_dir_url(__FILE__) . 'js/echeckpoint_pre-order-check.js', array('jquery'), $version, true);
     158                wp_enqueue_script('echeckpoint_pre-order-check', plugin_dir_url(__FILE__) . 'src/js/echeckpoint_pre-order-check.js', array('jquery'), $version, true);
    91159                // Enqueue CSS (use wp_enqueue_style for CSS files)
    92                 wp_enqueue_style('echeckpoint-admin-styles', plugin_dir_url(__FILE__) . 'css/echeckpoint-admin-styles.css', array(), $version);
     160                wp_enqueue_style('echeckpoint-admin-styles', plugin_dir_url(__FILE__) . 'src/css/echeckpoint-admin-styles.css', array(), $version);
    93161                // Localize the script with parameters, including the nonce
    94162                wp_localize_script('echeckpoint_pre-order-check', 'eCheckpointParams', array(
     
    102170        {
    103171
     172
     173            if (!self::is_checkout_block()) {
     174                setcookie('checkout_block', 'false', time() + 3600, COOKIEPATH, COOKIE_DOMAIN); // 1 hour expiration
     175            }
     176
     177
     178            // Proceed with compliance check on normal request or place order action
    104179            // Use filter_input to safely get the post_data from the POST request
    105180            // Use FILTER_SANITIZE_STRING to properly sanitize the data instead of FILTER_DEFAULT
     
    130205            if (!wp_verify_nonce($nonce, 'echeckpoint_nonce')) {
    131206                wp_die('Invalid nonce.');
    132             } 
     207            }
    133208
    134209            // Check if $post_data is an array or a string, and handle accordingly
     
    240315        {
    241316
    242             $checkbox_checked = isset($checkout_data['ship_to_different_address']) ? (bool) $checkout_data['ship_to_different_address'] : false;
     317            if (self::is_checkout_block()) {
     318                $checkbox_checked = true;
     319            } else {
     320                $checkbox_checked = isset($checkout_data['ship_to_different_address']) ? (bool) $checkout_data['ship_to_different_address'] : false;
     321            }
     322
     323            // Check if billing fields are completed
     324            $billing_complete = self::is_billing_complete($checkout_data);
     325
     326            // Check if shipping fields are completed
     327            $shipping_complete = !$checkbox_checked || self::is_shipping_complete($checkout_data);
    243328
    244329            // Check if billing fields are completed
     
    298383                }
    299384            } catch (Exception $e) {
     385
    300386            }
    301387        }
     
    335421            $show_conditional_fail = isset($options['conditional_fail_checkbox']) && $options['conditional_fail_checkbox'] === 'on';
    336422            $regulatedProducts = [];
     423            $isCheckoutBlock = self::is_checkout_block();
     424            $isECheckpointPassWithoutConditions = true;
    337425            $response = self::api_call_during_checkout($checkout_data);
     426
    338427            if (!$response) {
    339                 wc_add_notice(__('Error: Could not perform compliance check. Please contact Customer Service.', 'echeckpoint'), 'error');
     428                if ($isCheckoutBlock) {
     429                    // Create the client message as a variable
     430                    $client_message_content = __('Error: Could not perform compliance check. Please contact Customer Service.', 'echeckpoint');
     431                    $client_message_type = 'error';
     432
     433                    // Set the client message
     434                    self::$clientMessage = [
     435                        $client_message_content,
     436                        $client_message_type
     437                    ];
     438
     439                    // Set the cookie with the client message
     440                    setcookie(
     441                        'client_message',
     442                        wp_json_encode([
     443                            'message' => $client_message_content,
     444                            'type' => $client_message_type
     445                        ]),
     446                        time() + 1200,  // Cookie expires in 20 minutes
     447                        COOKIEPATH,
     448                        COOKIE_DOMAIN,
     449                        is_ssl(),  // Secure cookie if using HTTPS
     450                        false      // Not HTTPOnly to allow JavaScript access
     451                    );
     452                    $isECheckpointPassWithoutConditions = false;
     453                } else {
     454                    wc_add_notice(__('Error: Could not perform compliance check. Please contact Customer Service.', 'echeckpoint'), 'error');
     455                }
     456
    340457                return;
    341458            }
     
    362479                    $failed_product_list = "<ul><li>" . implode('</li><li>', $failed_product_names) . "</li></ul>";
    363480                    /* translators: %s: failed product list */
    364                     wc_add_notice(sprintf(__('Please contact Customer Service. An issue with some of the products in your order is preventing checkout:<br>%s', 'echeckpoint'), $failed_product_list), 'error');
     481                    if ($isCheckoutBlock) {
     482                        // Create the client message as a variable
     483                        $message_template = __('Please contact Customer Service. An issue with some of the products in your order is preventing checkout:<br>', 'echeckpoint');
     484                        $client_message_content = $message_template . $failed_product_list;
     485                        $client_message_type = 'error';
     486
     487                        // Set the client message
     488                        self::$clientMessage = [
     489                            $client_message_content,
     490                            $client_message_type
     491                        ];
     492
     493                        // Set the cookie with the client message
     494                        setcookie(
     495                            'client_message',
     496                            wp_json_encode([
     497                                'message' => $client_message_content,
     498                                'type' => $client_message_type
     499                            ]),
     500                            time() + 1200,  // Cookie expires in 20 minutes
     501                            COOKIEPATH,
     502                            COOKIE_DOMAIN,
     503                            is_ssl(),  // Secure cookie if using HTTPS
     504                            false      // Not HTTPOnly to allow JavaScript access
     505                        );
     506                        $isECheckpointPassWithoutConditions = false;
     507                    } else {
     508                        $message_template = __('Please contact Customer Service. An issue with some of the products in your order is preventing checkout:<br>', 'echeckpoint');
     509                        $full_message = $message_template . $failed_product_list;
     510                        wc_add_notice($full_message, 'error');
     511                    }
     512
    365513                    $compliance_passed = false;
    366514                }
     
    378526                    // Handling Billing Address Validation
    379527                    if ($billingResponse == 2) { // Validation Failed
    380                         wc_add_notice(__('Your billing address is not valid. To ensure the fastest service for your order, we verify your billing address with the U.S. Postal Service. Please ensure it is correct and try again. If you need assistance locating your official billing address, please look it up here: https://tools.usps.com/zip-code-lookup.htm?byaddress', 'echeckpoint'), 'error');
     528                        if ($isCheckoutBlock) {
     529                            // Create the client message as a variable
     530                            $client_message_content = 'Your billing address is not valid. To ensure the fastest service for your order, we verify your billing address with the U.S. Postal Service. Please ensure it is correct and try again. If you need assistance locating your official billing address, please look it up here: https://tools.usps.com/zip-code-lookup.htm?byaddress';
     531                            $client_message_type = 'error';
     532
     533                            // Set the client message
     534                            self::$clientMessage = [
     535                                $client_message_content,
     536                                $client_message_type
     537                            ];
     538
     539                            // Set the cookie with the client message
     540                            setcookie(
     541                                'client_message',
     542                                wp_json_encode([
     543                                    'message' => $client_message_content,
     544                                    'type' => $client_message_type
     545                                ]),
     546                                time() + 1200,  // Cookie expires in 20 minutes
     547                                COOKIEPATH,
     548                                COOKIE_DOMAIN,
     549                                is_ssl(),  // Secure cookie if using HTTPS
     550                                false      // Not HTTPOnly to allow JavaScript access
     551                            );
     552                            $isECheckpointPassWithoutConditions = false;
     553                        } else {
     554                            wc_add_notice(__('Your billing address is not valid. To ensure the fastest service for your order, we verify your billing address with the U.S. Postal Service. Please ensure it is correct and try again. If you need assistance locating your official billing address, please look it up here: https://tools.usps.com/zip-code-lookup.htm?byaddress', 'echeckpoint'), 'error');
     555                        }
    381556                        $compliance_passed = false; // Set compliance passed flag to false to prevent checkout
    382557                    }
     
    384559                    // Handling Shipping Address Validation
    385560                    if ($shippingResponse == 2) { // Validation Failed
    386                         wc_add_notice(__('Your shipping address is not valid. To ensure the fastest service for your order, we verify your shipping address with the U.S. Postal Service. Please ensure it is correct and try again. If you need assistance locating your official shipping address, please look it up here: https://tools.usps.com/zip-code-lookup.htm?byaddress', 'echeckpoint'), 'error');
     561                        if ($isCheckoutBlock) {
     562                            // Create the client message as a variable
     563                            $client_message_content = 'Your shipping address is not valid. To ensure the fastest service for your order, we verify your shipping address with the U.S. Postal Service. Please ensure it is correct and try again. If you need assistance locating your official shipping address, please look it up here: https://tools.usps.com/zip-code-lookup.htm?byaddress';
     564                            $client_message_type = 'error';
     565
     566                            // Set the client message
     567                            self::$clientMessage = [
     568                                $client_message_content,
     569                                $client_message_type
     570                            ];
     571
     572                            // Set the cookie with the client message
     573                            setcookie(
     574                                'client_message',
     575                                wp_json_encode([
     576                                    'message' => $client_message_content,
     577                                    'type' => $client_message_type
     578                                ]),
     579                                time() + 1200,  // Cookie expires in 20 minutes
     580                                COOKIEPATH,
     581                                COOKIE_DOMAIN,
     582                                is_ssl(),  // Secure cookie if using HTTPS
     583                                false      // Not HTTPOnly to allow JavaScript access
     584                            );
     585                            $isECheckpointPassWithoutConditions = false;
     586                        } else {
     587                            wc_add_notice(__('Your shipping address is not valid. To ensure the fastest service for your order, we verify your shipping address with the U.S. Postal Service. Please ensure it is correct and try again. If you need assistance locating your official shipping address, please look it up here: https://tools.usps.com/zip-code-lookup.htm?byaddress', 'echeckpoint'), 'error');
     588                        }
    387589                        $compliance_passed = false; // Set compliance passed flag to false to prevent checkout
    388590                    }
    389                 }
    390             }
     591                }
     592            }
     593
    391594
    392595            // Regional Restrictions Check
     
    407610                        if (isset($item['businessTradeTypes'])) {
    408611                            $business_trade_types = $item['businessTradeTypes'];
     612                            // Log the businessTradeTypes to ensure it is being received correctly
    409613                            $additional_requirements = self::get_additional_requirements_message($business_trade_types);
    410                            
    411614                            if ($product) {
    412615                                /* translators: 1: product name, 2: additional requirements */
    413616                                $message = sprintf(__('To complete the purchase of %1$s, additional information will be required after checkout.  Eligible purchasers include: %2$s', 'echeckpoint'), $product->get_name(), $additional_requirements);
    414617                                $conditional_fail_messages[] = $message;
     618                                // Log the final message
    415619                            } else {
    416620                                /* translators: 1: SKU, 2: additional requirements */
    417621                                $message = sprintf(__('To complete the purchase of this SKU, %1$s, additional information will be required after checkout.  Eligible purchasers include: %2$s', 'echeckpoint'), $item['response']['productID'], $additional_requirements);
    418622                                $conditional_fail_messages[] = $message;
     623                                // Log the final message
    419624                            }
    420625                        }
     626                    } elseif (isset($item['response']['result']) && $item['response']['result'] == 3 && !$show_conditional_fail & $isCheckoutBlock) {
     627                        $client_message_content = 'show_conditional_fail disabled';
     628                        $client_message_type = 'N/A';
     629
     630                        // Set the client message
     631                        self::$clientMessage = [
     632                            $client_message_content,
     633                            $client_message_type
     634                        ];
     635
     636                        // Set the cookie with the client message
     637                        setcookie(
     638                            'client_message',
     639                            wp_json_encode([
     640                                'message' => $client_message_content,
     641                                'type' => $client_message_type
     642                            ]),
     643                            time() + 1200,  // Cookie expires in 20 minutes
     644                            COOKIEPATH,
     645                            COOKIE_DOMAIN,
     646                            is_ssl(),  // Secure cookie if using HTTPS
     647                            false      // Not HTTPOnly to allow JavaScript access
     648                        );
     649                        $isECheckpointPassWithoutConditions = false;
    421650                    }
    422651                    if (isset($item['regulatedProduct']) && $item['regulatedProduct'] === true) {
    423                         $product_id = wc_get_product_id_by_sku($item['response']['productID']);             
     652                        $product_id = wc_get_product_id_by_sku($item['response']['productID']);
     653
    424654                        $product = wc_get_product($product_id);
    425655                        array_push($regulatedProducts, $product->get_name());
     
    428658
    429659                if (count($regulatedProducts) > 0) {
    430                     // Hook into WooCommerce's fee calculation lifecycle
    431                     add_action('woocommerce_cart_calculate_fees', function () use ($regulatedProducts) {
    432                         eCheckpoint_Compliance_Fee::ComplianceFee_calculate($regulatedProducts);
    433                     }, 20);
    434                 }
     660                    // Define the fee calculation action
     661                    $calculate_fees_action = function () use ($regulatedProducts) {
     662                        // if (is_admin() && !defined('DOING_AJAX')) {
     663                        //  return; // Prevent running in the admin area except for AJAX
     664                        // }
     665
     666                        // Calculate and log the fee
     667                        self::$total_fee = eCheckpoint_Compliance_Fee::ComplianceFee_calculate($regulatedProducts);
     668                    };
     669
     670                    // Attach the fee calculation action to the WooCommerce hook
     671                    add_action('woocommerce_cart_calculate_fees', $calculate_fees_action, 20);
     672
     673                    // Manually trigger the hook to ensure it runs on page load
     674                    // Wrap this in a check to ensure it is only triggered once on page load, not within the context of an existing `woocommerce_cart_calculate_fees` execution.
     675                    if (!did_action('woocommerce_cart_calculate_fees')) {
     676                        do_action('woocommerce_cart_calculate_fees');
     677                    }
     678                }
     679
     680
    435681
    436682                if (!empty($failed_product_names)) {
    437683                    $failed_product_list = "<ul>" . implode('', $failed_product_names) . "</ul>";
    438684                    /* translators: %s: failed product list */
    439                     wc_add_notice(sprintf(__('The following items cannot be shipped to your location due to company policy or federal, state, or local regulations. Please remove these items from your cart to proceed with checkout.: %s', 'echeckpoint'), $failed_product_list), 'error');
     685                    if ($isCheckoutBlock) {
     686
     687                        // Create the client message as a variable
     688                        $message_template = __('The following items cannot be shipped to your location due to company policy or federal, state, or local regulations. Please remove these items from your cart to proceed with checkout:', 'echeckpoint');
     689                        $client_message_content = $message_template . '<br>' . $failed_product_list;
     690
     691
     692                        $client_message_type = 'error';
     693
     694                        // Set the client message
     695                        self::$clientMessage = [
     696                            $client_message_content,
     697                            $client_message_type
     698                        ];
     699
     700                        // Set the cookie with the client message
     701                        setcookie(
     702                            'client_message',
     703                            wp_json_encode([
     704                                'message' => $client_message_content,
     705                                'type' => $client_message_type
     706                            ]),
     707                            time() + 1200,  // Cookie expires in 20 minutes
     708                            COOKIEPATH,
     709                            COOKIE_DOMAIN,
     710                            is_ssl(),  // Secure cookie if using HTTPS
     711                            false      // Not HTTPOnly to allow JavaScript access
     712                        );
     713                        $isECheckpointPassWithoutConditions = false;
     714                        return;
     715                    } else {
     716                        // Create the notice message as a variable
     717                        $message_template = __('The following items cannot be shipped to your location due to company policy or federal, state, or local regulations. Please remove these items from your cart to proceed with checkout.:', 'echeckpoint');
     718                        $notice_message = $message_template . ' ' . $failed_product_list;
     719
     720                        // Add the notice using the variable
     721                        wc_add_notice($notice_message, 'error');
     722                    }
    440723                    $compliance_passed = false;
    441724                }
     
    446729            if (!empty($conditional_fail_messages)) {
    447730                $conditional_fail_messages[] = __('If you are not eligible to purchase these products, please remove them from your shopping cart.', 'echeckpoint');
    448                 wc_add_notice(implode('<br>', $conditional_fail_messages), 'success');
    449             }
    450 
     731                if ($isCheckoutBlock) {
     732                    // Create the client message as a variable
     733                    $client_message_content = implode('<br>', $conditional_fail_messages);
     734                    $client_message_type = 'info';
     735                    $client_message_total_fee = self::$total_fee;
     736
     737                    // Set the client message
     738                    self::$clientMessage = [
     739                        $client_message_content,
     740                        $client_message_type,
     741                        $client_message_total_fee
     742                    ];
     743
     744                    // Set the cookie with the client message
     745                    setcookie(
     746                        'client_message',
     747                        wp_json_encode([
     748                            'message' => $client_message_content,
     749                            'type' => $client_message_type,
     750                            'total_fee' => $client_message_total_fee
     751                        ]),
     752                        time() + 1200,  // Cookie expires in 20 minutes
     753                        COOKIEPATH,
     754                        COOKIE_DOMAIN,
     755                        is_ssl(),  // Secure cookie if using HTTPS
     756                        false      // Not HTTPOnly to allow JavaScript access
     757                    );
     758                    $isECheckpointPassWithoutConditions = false;
     759                } else {
     760                    // Combine the conditional failure messages into a single notice string
     761                    $notice_message = implode('<br>', $conditional_fail_messages);
     762                    // Add the notice using the variable
     763                    wc_add_notice($notice_message, 'notice');
     764                    WC()->session->set('wc_notices', WC()->session->get('wc_notices'));
     765                }
     766
     767            }
    451768
    452769            if (!$compliance_passed) {
     
    454771            }
    455772
     773            if ($isCheckoutBlock && $isECheckpointPassWithoutConditions) {
     774                // Create the client message as a variable
     775                $client_message_content = 'compliance passed.';
     776                $client_message_type = 'N/A';
     777
     778                // Set the client message
     779                self::$clientMessage = [
     780                    $client_message_content,
     781                    $client_message_type
     782                ];
     783
     784                // Set the cookie with the client message
     785                setcookie(
     786                    'client_message',
     787                    wp_json_encode([
     788                        'message' => $client_message_content,
     789                        'type' => $client_message_type
     790                    ]),
     791                    time() + 1200,  // Cookie expires in 20 minutes
     792                    COOKIEPATH,
     793                    COOKIE_DOMAIN,
     794                    is_ssl(),  // Secure cookie if using HTTPS
     795                    false      // Not HTTPOnly to allow JavaScript access
     796                );
     797            }
     798
     799            self::log_cart_details_on_checkout();
     800
    456801        }
    457802
    458803        public static function api_call_during_checkout($checkout_data)
    459804        {
    460        
     805
    461806            if (!self::pre_order_active())
    462807                return;
     
    559904            $billing_complete = self::is_billing_complete($checkout_data);
    560905            $shipping_complete = self::is_shipping_complete($checkout_data);
    561             $checkbox_checked = isset($checkout_data['ship_to_different_address']) ? (bool) $checkout_data['ship_to_different_address'] : false;
     906
     907            if (self::is_checkout_block()) {
     908                $checkbox_checked = true;
     909            } else {
     910                $checkbox_checked = isset($checkout_data['ship_to_different_address']) ? (bool) $checkout_data['ship_to_different_address'] : false;
     911            }
    562912
    563913            if ($checkbox_checked && $shipping_complete) {
     
    634984            }
    635985
    636             // Convert to unordered list with reduced margin
    637             $result = '<ul style="margin-bottom: 0;"><li>' . implode('</li><li>', $requirements) . '</li></ul>';
     986            if (self::is_checkout_block()) {
     987                // Prepend &emsp;&ensp; to each requirement item
     988                $requirements = array_map(fn($item) => '&emsp;&ensp;' . $item, $requirements);
     989
     990                // Use implode with <br> between each item and wrap with additional <br> tags
     991                $result = '<br>' . implode('<br>', $requirements) . '<br>';
     992
     993            } else {
     994                // Convert to unordered list with reduced margin
     995                $result = '<ul style="margin-bottom: 0;"><li>' . implode('</li><li>', $requirements) . '</li></ul>';
     996            }
    638997            return $result;
    639998        }
     999
     1000        /***************************************************************************************************** */
     1001        // WOOCOMMERCE CHECKOUT BLOCK
     1002/***************************************************************************************************** */
     1003        public static function add_fee()
     1004        {
     1005            if (!self::is_checkout_block()) {
     1006                return;
     1007            }
     1008
     1009            // Run compliance check; adapt this call if parameters are needed
     1010            eCheckpoint_Pre_Order_Checks::check_required_fields_and_run_compliance_blocks();
     1011        }
     1012
     1013        public static function log_cart_details_on_checkout()
     1014        {
     1015            if (!WC()->cart) {
     1016                return;
     1017            }
     1018
     1019            $cart_items = WC()->cart->get_cart();
     1020            $log_data = [];
     1021
     1022            // Log details for each product in the cart
     1023            foreach ($cart_items as $cart_item_key => $cart_item) {
     1024                $product = $cart_item['data'];
     1025
     1026                $log_data['Products'][] = [
     1027                    'Product Name' => $product->get_name(),
     1028                    'Product ID' => $product->get_id(),
     1029                    'SKU' => $product->get_sku(),
     1030                    'Quantity' => $cart_item['quantity'],
     1031                    'Price' => wc_price($product->get_price()),
     1032                    'Subtotal' => wc_price($cart_item['line_subtotal']),
     1033                    'Total' => wc_price($cart_item['line_total'])
     1034                ];
     1035            }
     1036
     1037            // Log any fees applied in the cart
     1038            $fees = WC()->cart->get_fees();
     1039            if (!empty($fees)) {
     1040                foreach ($fees as $fee) {
     1041                    $log_data['Fees'][] = [
     1042                        'Fee Name' => $fee->name,
     1043                        'Amount' => wc_price($fee->amount)
     1044                    ];
     1045                }
     1046            } else {
     1047                $log_data['Fees'] = 'No fees applied';
     1048            }
     1049
     1050            // Log cart totals
     1051            $log_data['Cart Totals'] = [
     1052                'Cart Total (excluding tax)' => wc_price(WC()->cart->cart_contents_total),
     1053                'Total Tax' => wc_price(WC()->cart->get_cart_contents_tax() + WC()->cart->get_shipping_tax()),
     1054                'Fees Total' => wc_price(WC()->cart->get_fee_total()),
     1055                'Shipping Total' => wc_price(WC()->cart->get_shipping_total()),
     1056                'Grand Total' => wc_price(WC()->cart->get_total(''))
     1057            ];
     1058        }
     1059
     1060
     1061        public static function run_compliance_check()
     1062        {
     1063            //Verify nonce if needed for security
     1064            if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'echeckpoint_nonce')) {
     1065                wp_send_json_error('Invalid nonce');
     1066            }
     1067
     1068
     1069            if (!self::is_checkout_block()) {
     1070                return;
     1071            }
     1072
     1073            // Run compliance check; adapt this call if parameters are needed
     1074            $result = eCheckpoint_Pre_Order_Checks::check_required_fields_and_run_compliance_blocks();
     1075            //If the compliance check passes, set the cookie
     1076            if (!empty(self::$clientMessage)) {
     1077                $data = array(
     1078                    'messages' => isset(self::$clientMessage[0]) ? self::$clientMessage[0] : '', // Default to an empty string if not set
     1079                    'notice' => isset(self::$clientMessage[1]) ? self::$clientMessage[1] : 'info', // Default notice type
     1080                    'total_fee' => isset(self::$clientMessage[2]) ? self::$clientMessage[2] : 0 // Default to 0 if not set
     1081                );
     1082                wp_send_json_success($data);
     1083            } else {
     1084                wp_send_json_error('Compliance check failed, cookie not set.');
     1085            }
     1086        }
     1087
     1088        // Handle customer update for WooCommerce Blocks
     1089
     1090        public static function handle_blocks_customer_update($customer, $request)
     1091        {
     1092
     1093            if (!self::is_checkout_block()) {
     1094                return;
     1095            }
     1096
     1097            // Get billing and shipping addresses from the customer object directly
     1098            $billing_address = array(
     1099                'first_name' => $customer->get_billing_first_name(),
     1100                'last_name' => $customer->get_billing_last_name(),
     1101                'address_1' => $customer->get_billing_address_1(),
     1102                'address_2' => $customer->get_billing_address_2(),
     1103                'city' => $customer->get_billing_city(),
     1104                'state' => $customer->get_billing_state(),
     1105                'postcode' => $customer->get_billing_postcode(),
     1106                'country' => $customer->get_billing_country(),
     1107                'phone' => $customer->get_billing_phone(),
     1108                'email' => $customer->get_billing_email()
     1109            );
     1110
     1111            $shipping_address = array(
     1112                'first_name' => $customer->get_shipping_first_name(),
     1113                'last_name' => $customer->get_shipping_last_name(),
     1114                'address_1' => $customer->get_shipping_address_1(),
     1115                'address_2' => $customer->get_shipping_address_2(),
     1116                'city' => $customer->get_shipping_city(),
     1117                'state' => $customer->get_shipping_state(),
     1118                'postcode' => $customer->get_shipping_postcode(),
     1119                'country' => $customer->get_shipping_country()
     1120            );
     1121
     1122
     1123            // Store the complete billing and shipping addresses in session
     1124            WC()->session->set('billing_address', $billing_address);
     1125            WC()->session->set('shipping_address', $shipping_address);
     1126
     1127            // Create checkout_data array from the customer object
     1128            $checkout_data = array(
     1129                'billing_first_name' => $billing_address['first_name'],
     1130                'billing_last_name' => $billing_address['last_name'],
     1131                'billing_address_1' => $billing_address['address_1'],
     1132                'billing_address_2' => $billing_address['address_2'],
     1133                'billing_city' => $billing_address['city'],
     1134                'billing_state' => $billing_address['state'],
     1135                'billing_postcode' => $billing_address['postcode'],
     1136                'billing_country' => $billing_address['country'],
     1137                'billing_phone' => $billing_address['phone'],
     1138                'billing_email' => $billing_address['email'],
     1139                'shipping_first_name' => $shipping_address['first_name'],
     1140                'shipping_last_name' => $shipping_address['last_name'],
     1141                'shipping_address_1' => $shipping_address['address_1'],
     1142                'shipping_address_2' => $shipping_address['address_2'],
     1143                'shipping_city' => $shipping_address['city'],
     1144                'shipping_state' => $shipping_address['state'],
     1145                'shipping_postcode' => $shipping_address['postcode'],
     1146                'shipping_country' => $shipping_address['country']
     1147            );
     1148
     1149
     1150            // Use the new helper function to check if address fields have been updated
     1151            if (!self::is_address_update($checkout_data)) {
     1152
     1153                return; // Exit the function early if no critical fields have been updated
     1154            }
     1155
     1156            // Prepare data to check for compliance
     1157            $data_to_check = array(
     1158                'billing_first_name' => sanitize_text_field($checkout_data['billing_first_name'] ?? ''),
     1159                'billing_last_name' => sanitize_text_field($checkout_data['billing_last_name'] ?? ''),
     1160                'billing_address_1' => sanitize_text_field($checkout_data['billing_address_1'] ?? ''),
     1161                'billing_address_2' => sanitize_text_field($checkout_data['billing_address_2'] ?? ''),
     1162                'billing_city' => sanitize_text_field($checkout_data['billing_city'] ?? ''),
     1163                'billing_state' => sanitize_text_field($checkout_data['billing_state'] ?? ''),
     1164                'billing_postcode' => sanitize_text_field($checkout_data['billing_postcode'] ?? ''),
     1165                'billing_email' => sanitize_email($checkout_data['billing_email'] ?? ''),
     1166                'ship_to_different_address' => !empty($checkout_data['ship_to_different_address']) ? '1' : '0',
     1167                'shipping_first_name' => sanitize_text_field($checkout_data['shipping_first_name'] ?? ''),
     1168                'shipping_last_name' => sanitize_text_field($checkout_data['shipping_last_name'] ?? ''),
     1169                'shipping_address_1' => sanitize_text_field($checkout_data['shipping_address_1'] ?? ''),
     1170                'shipping_address_2' => sanitize_text_field($checkout_data['shipping_address_2'] ?? ''),
     1171                'shipping_city' => sanitize_text_field($checkout_data['shipping_city'] ?? ''),
     1172                'shipping_state' => sanitize_text_field($checkout_data['shipping_state'] ?? ''),
     1173                'shipping_postcode' => sanitize_text_field($checkout_data['shipping_postcode'] ?? '')
     1174            );
     1175
     1176            if (self::are_required_fields_completed($data_to_check)) {
     1177                // Run the compliance check
     1178                self::trigger_compliance_check($data_to_check);
     1179            }
     1180
     1181        }
     1182
     1183        public static function check_required_fields_and_run_compliance_blocks()
     1184        {
     1185
     1186            if (!self::is_checkout_block()) {
     1187                return;
     1188            }
     1189
     1190            // Log the 'customer' session data
     1191            $customer_data = WC()->session->get('customer', []);
     1192
     1193            $checkout_data = array(
     1194                'billing_first_name' => $customer_data['first_name'] ?? '',
     1195                'billing_last_name' => $customer_data['last_name'] ?? '',
     1196                'billing_address_1' => $customer_data['address_1'] ?? '',
     1197                'billing_city' => $customer_data['city'] ?? '',
     1198                'billing_state' => $customer_data['state'] ?? '',
     1199                'billing_email' => $customer_data['email'] ?? '',
     1200                'billing_postcode' => $customer_data['postcode'] ?? '',
     1201                'shipping_first_name' => $customer_data['shipping_first_name'] ?? '',
     1202                'shipping_last_name' => $customer_data['shipping_last_name'] ?? '',
     1203                'shipping_address_1' => $customer_data['shipping_address_1'] ?? '',
     1204                'shipping_city' => $customer_data['shipping_city'] ?? '',
     1205                'shipping_state' => $customer_data['shipping_state'] ?? '',
     1206                'shipping_postcode' => $customer_data['shipping_postcode'] ?? ''
     1207            );
     1208
     1209            // Use the new helper function to check if address fields have been updated
     1210            if (!self::is_address_update($checkout_data)) {
     1211                return; // Exit the function early if no critical fields have been updated
     1212            }
     1213
     1214            // Prepare data to check for compliance
     1215            $data_to_check = array(
     1216                'billing_first_name' => sanitize_text_field($checkout_data['billing_first_name'] ?? ''),
     1217                'billing_last_name' => sanitize_text_field($checkout_data['billing_last_name'] ?? ''),
     1218                'billing_address_1' => sanitize_text_field($checkout_data['billing_address_1'] ?? ''),
     1219                'billing_address_2' => sanitize_text_field($checkout_data['billing_address_2'] ?? ''),
     1220                'billing_city' => sanitize_text_field($checkout_data['billing_city'] ?? ''),
     1221                'billing_state' => sanitize_text_field($checkout_data['billing_state'] ?? ''),
     1222                'billing_postcode' => sanitize_text_field($checkout_data['billing_postcode'] ?? ''),
     1223                'billing_email' => sanitize_email($checkout_data['billing_email'] ?? ''),
     1224                'ship_to_different_address' => !empty($checkout_data['ship_to_different_address']) ? '1' : '0',
     1225                'shipping_first_name' => sanitize_text_field($checkout_data['shipping_first_name'] ?? ''),
     1226                'shipping_last_name' => sanitize_text_field($checkout_data['shipping_last_name'] ?? ''),
     1227                'shipping_address_1' => sanitize_text_field($checkout_data['shipping_address_1'] ?? ''),
     1228                'shipping_address_2' => sanitize_text_field($checkout_data['shipping_address_2'] ?? ''),
     1229                'shipping_city' => sanitize_text_field($checkout_data['shipping_city'] ?? ''),
     1230                'shipping_state' => sanitize_text_field($checkout_data['shipping_state'] ?? ''),
     1231                'shipping_postcode' => sanitize_text_field($checkout_data['shipping_postcode'] ?? '')
     1232            );
     1233
     1234
     1235            $result = self::are_required_fields_completed($data_to_check);
     1236
     1237            if ($result) {
     1238                // Run the compliance check
     1239                self::trigger_compliance_check($data_to_check);
     1240            }
     1241        }
     1242
     1243        public static function is_checkout_block()
     1244        {
     1245            $result = WC_Blocks_Utils::has_block_in_page(wc_get_page_id('checkout'), 'woocommerce/checkout');
     1246
     1247            return $result;
     1248        }
     1249
     1250
    6401251    }
    6411252}
Note: See TracChangeset for help on using the changeset viewer.