Plugin Directory

Changeset 3266406


Ignore:
Timestamp:
04/03/2025 01:32:49 PM (10 months ago)
Author:
vivawalletplugins
Message:

preparing version 1.0.1

Location:
viva-com-smart-for-woocommerce/trunk
Files:
22 edited

Legend:

Unmodified
Added
Removed
  • viva-com-smart-for-woocommerce/trunk/changelog.txt

    r3245677 r3266406  
    1 2024-01-28 - version 1.0.0
     12025-03-27 - version 1.0.1
     2* Add brand color selection for smart checkout
     3* Fix double call to viva ( both environments) on configuration
     4
     52025-01-28 - version 1.0.0
    26* Viva.com | Smart Checkout. Initial release.
  • viva-com-smart-for-woocommerce/trunk/composer.json

    r3245677 r3266406  
    1616        "phpunit/phpunit": "*",
    1717        "humbug/php-scoper": "*",
    18         "vivawallet/vivawallet-php": "2.2.2"
     18        "vivawallet/vivawallet-php": "2.2.3"
    1919    },
    2020    "repositories": {
     
    3131    },
    3232    "scripts": {
     33        "phpcs-config": [
     34            "\"phpcs/vendor/bin/phpcs\" --config-set installed_paths phpcs/vendor/wp-coding-standards/wpcs,phpcs/vendor/phpcompatibility/php-compatibility,phpcs/vendor/woocommerce/woocommerce-sniffs/src,phpcs/vendor/phpcompatibility/phpcompatibility-wp,phpcs/vendor/phpcompatibility/phpcompatibility-paragonie,phpcs/vendor/phpcsstandards/phpcsutils,phpcs/vendor/phpcsstandards/phpcsextra"
     35        ],
     36        "phpcs-scan": [
     37            "@phpcs-config",
     38            "\"phpcs/vendor/bin/phpcs\""
     39        ],
    3340        "post-autoload-dump": [
    3441            "@php vendor/humbug/php-scoper/bin/php-scoper add-prefix --prefix=VivaComSmartCheckout --output-dir=./vendor_prefixed/guzzlehttp --config=php-scoper/guzzlehttp.inc.php --force",
  • viva-com-smart-for-woocommerce/trunk/includes/assets/js/admin-vivacom-smart.js

    r3245677 r3266406  
    77        var advanced_settings_checkbox = jQuery( '#woocommerce_vivacom_smart_advanced_settings_enabled' );
    88        var advancedSettingsEnabled    = advanced_settings_checkbox.is( ':checked' );
     9
     10        jQuery('#woocommerce_vivacom_smart_brand_color').wpColorPicker();
    911
    1012        if ( demoMode ) {
  • viva-com-smart-for-woocommerce/trunk/includes/assets/js/admin-vivacom-smart.min.js

    r3245677 r3266406  
    1 jQuery(document).ready(function(){var e=jQuery("#woocommerce_vivacom_smart_test_mode"),o=e.is(":checked"),t=jQuery("#woocommerce_vivacom_smart_advanced_settings_enabled"),r=t.is(":checked");(o?(jQuery("#woocommerce_vivacom_smart_client_id").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_client_secret").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_source_code").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_title_live")):(jQuery("#woocommerce_vivacom_smart_demo_client_id").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_demo_client_secret").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_demo_source_code").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_title_demo"))).hide(),r?(jQuery("#woocommerce_vivacom_smart_main_descr").show(),jQuery("#woocommerce_vivacom_smart_title").closest("tr").show(),jQuery("#woocommerce_vivacom_smart_description").closest("tr").show(),jQuery("#woocommerce_vivacom_smart_order_status").closest("tr").show(),jQuery("#woocommerce_vivacom_smart_logo_enabled").closest("tr").show(),jQuery("#woocommerce_vivacom_smart_installments").closest("tr").show(),(e.is(":checked")?jQuery("#woocommerce_vivacom_smart_demo_source_code"):jQuery("#woocommerce_vivacom_smart_source_code")).closest("tr").show()):(jQuery("#woocommerce_vivacom_smart_main_descr").hide(),jQuery("#woocommerce_vivacom_smart_title").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_description").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_order_status").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_logo_enabled").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_installments").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_demo_source_code").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_source_code").closest("tr").hide()),t.on("change",function(){jQuery("#woocommerce_vivacom_smart_main_descr").toggle(),jQuery("#woocommerce_vivacom_smart_title").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_description").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_order_status").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_logo_enabled").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_installments").closest("tr").toggle(),(e.is(":checked")?jQuery("#woocommerce_vivacom_smart_demo_source_code"):jQuery("#woocommerce_vivacom_smart_source_code")).closest("tr").toggle()}),e.on("change",function(){jQuery("#woocommerce_vivacom_smart_client_id").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_client_secret").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_demo_client_id").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_demo_client_secret").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_title_live").toggle(),jQuery("#woocommerce_vivacom_smart_title_demo").toggle(),t.is(":checked")&&(jQuery("#woocommerce_vivacom_smart_demo_source_code").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_source_code").closest("tr").toggle())})});
     1jQuery(document).ready(function(){var e=jQuery("#woocommerce_vivacom_smart_test_mode"),o=e.is(":checked"),c=jQuery("#woocommerce_vivacom_smart_advanced_settings_enabled"),r=c.is(":checked");jQuery("#woocommerce_vivacom_smart_brand_color").wpColorPicker(),(o?(jQuery("#woocommerce_vivacom_smart_client_id").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_client_secret").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_source_code").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_title_live")):(jQuery("#woocommerce_vivacom_smart_demo_client_id").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_demo_client_secret").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_demo_source_code").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_title_demo"))).hide(),r?(jQuery("#woocommerce_vivacom_smart_main_descr").show(),jQuery("#woocommerce_vivacom_smart_title").closest("tr").show(),jQuery("#woocommerce_vivacom_smart_description").closest("tr").show(),jQuery("#woocommerce_vivacom_smart_order_status").closest("tr").show(),jQuery("#woocommerce_vivacom_smart_logo_enabled").closest("tr").show(),jQuery("#woocommerce_vivacom_smart_installments").closest("tr").show(),(e.is(":checked")?jQuery("#woocommerce_vivacom_smart_demo_source_code"):jQuery("#woocommerce_vivacom_smart_source_code")).closest("tr").show()):(jQuery("#woocommerce_vivacom_smart_main_descr").hide(),jQuery("#woocommerce_vivacom_smart_title").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_description").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_order_status").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_logo_enabled").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_installments").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_demo_source_code").closest("tr").hide(),jQuery("#woocommerce_vivacom_smart_source_code").closest("tr").hide()),c.on("change",function(){jQuery("#woocommerce_vivacom_smart_main_descr").toggle(),jQuery("#woocommerce_vivacom_smart_title").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_description").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_order_status").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_logo_enabled").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_installments").closest("tr").toggle(),(e.is(":checked")?jQuery("#woocommerce_vivacom_smart_demo_source_code"):jQuery("#woocommerce_vivacom_smart_source_code")).closest("tr").toggle()}),e.on("change",function(){jQuery("#woocommerce_vivacom_smart_client_id").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_client_secret").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_demo_client_id").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_demo_client_secret").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_title_live").toggle(),jQuery("#woocommerce_vivacom_smart_title_demo").toggle(),c.is(":checked")&&(jQuery("#woocommerce_vivacom_smart_demo_source_code").closest("tr").toggle(),jQuery("#woocommerce_vivacom_smart_source_code").closest("tr").toggle())})});
  • viva-com-smart-for-woocommerce/trunk/includes/class-wc-vivacom-smart-blocks-support.php

    r3245677 r3266406  
    11<?php
     2/**
     3 * Blocks support
     4 *
     5 * @package   VivaComSmartForWooCommerce
     6 */
     7
    28use Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType;
    39
  • viva-com-smart-for-woocommerce/trunk/includes/class-wc-vivacom-smart-endpoints.php

    r3245677 r3266406  
    8585
    8686            if (
    87                 empty( $parameters['EventData']['TransactionId'] )
    88                 || empty( $parameters['EventData']['OrderCode'] )
    89                 || is_null( $parameters['EventData']['TransactionTypeId'] )
    90             ) {
     87                empty( $parameters['EventData']['TransactionId'] )
     88                || empty( $parameters['EventData']['OrderCode'] )
     89                || is_null( $parameters['EventData']['TransactionTypeId'] )
     90            ) {
    9191                return new WP_REST_Response( $res, 200 );
    9292            }
    9393
    94             $order_code     = (string) $parameters['EventData']['OrderCode'];
    95             $transaction = array(
    96                 'id' =>  (string) $parameters['EventData']['TransactionId'],
    97                 'typeId' =>  (int) $parameters['EventData']['TransactionTypeId'],
    98             );
     94            $order_code  = (string) $parameters['EventData']['OrderCode'];
     95            $transaction = array(
     96                'id'     => (string) $parameters['EventData']['TransactionId'],
     97                'typeId' => (int) $parameters['EventData']['TransactionTypeId'],
     98            );
    9999
    100100            global $wpdb;
    101101
    102             $wc_order_id = $wpdb->get_var( $wpdb->prepare(
    103                 "SELECT woocommerce_order_id FROM {$wpdb->prefix}viva_com_smart_wc_checkout_orders WHERE vivacom_order_code = %s ORDER BY date_add LIMIT 1",
    104                 $order_code
    105             )
    106             );
     102            $wc_order_id = $wpdb->get_var(
     103                $wpdb->prepare(
     104                    "SELECT woocommerce_order_id FROM {$wpdb->prefix}viva_com_smart_wc_checkout_orders WHERE vivacom_order_code = %s ORDER BY date_add LIMIT 1",
     105                    $order_code
     106                )
     107            );
    107108
    108109            if ( ! empty( $wc_order_id ) ) {
     
    119120            WC_Vivacom_Smart_Logger::log( "Payments methods endpoint post callback\n Smart checkout\n Request: " . wp_json_encode( $parameters ) );
    120121
    121             if ( isset( $parameters['EventTypeId'] ) && 1796 === $parameters['EventTypeId'] ) {
    122                 $viva_settings         = get_option( 'woocommerce_vivacom_smart_settings' );
    123                 $environment           = 'yes' === $viva_settings['test_mode'] ? 'demo' : 'live';
    124                 $bearer_authentication = WC_Vivacom_Smart_Helpers::get_bearer_authentication( $environment );
    125                 $transaction_response  = WC_Vivacom_Smart_Helpers::get_transaction( $bearer_authentication, $transaction['id'] );
    126 
    127                 if ( ! empty( $transaction_response ) && ! empty( $transaction_response->orderCode ) ) {
    128                     // CHECK TRANSACTION VALID AND UPDATE.
    129                     $transaction_order = (string) $transaction_response->orderCode;
    130 
    131                     if ( $transaction_order === $order_code ) {
    132                         if ( 'F' === $transaction_response->statusId ) {
    133                             $date = new DateTime($parameters['EventData']['CardExpirationDate']);
    134                             $tokenData = array(
    135                                 'lastFourDigits' => (isset($parameters['EventData']['CardNumber']) && strlen($parameters['EventData']['CardNumber']) > 4) ? substr((string)$parameters['EventData']['CardNumber'], -4) : 'XXXX',
    136                                 'cardType'     => (string) $parameters['EventData']['BankId'],
    137                                 'expiryMonth' => $date->format('m') ?? null,
    138                                 'expiryYear' => $date->format('Y') ?? null,
    139                             );
    140                             WC_Vivacom_Smart_Helpers::complete_order( $order->get_id(), $transaction, '', false );
    141 
    142                             // Check and save card token if subscription.
    143                             if ( WC_Vivacom_Smart_Helpers::check_subscription( $order->get_id() ) && $order->get_user() ) {
    144                                 WC_Vivacom_Smart_Helpers::save_payment_token( $transaction['id'], $order, $tokenData );
    145                             }
    146                         }
    147                     }
    148                 } else {
    149                     // WEBHOOK WILL BE RESEND.
    150                     return new WP_REST_Response( $res, 400 );
    151                 }
    152             } else {
    153                 $note = __( 'Transaction failed using Viva.com Smart Checkout', 'viva-com-smart-for-woocommerce' );
    154 
    155                 if ( isset( $parameters['CorrelationId'] ) && ! empty( $parameters['CorrelationId'] ) ) {
    156                     $note .= __( 'with Viva-CorrelationId: ', 'viva-com-smart-for-woocommerce' ) . $parameters['CorrelationId'];
    157 
    158                 } else {
    159                     $note .= '.';
    160                 }
    161 
    162                 $order->add_order_note( $note, false );
    163                 $order->save();
    164             }
     122            if ( isset( $parameters['EventTypeId'] ) && 1796 === $parameters['EventTypeId'] ) {
     123                $viva_settings         = get_option( 'woocommerce_vivacom_smart_settings' );
     124                $environment           = 'yes' === $viva_settings['test_mode'] ? 'demo' : 'live';
     125                $bearer_authentication = WC_Vivacom_Smart_Helpers::get_bearer_authentication( $environment );
     126                $transaction_response  = WC_Vivacom_Smart_Helpers::get_transaction( $bearer_authentication, $transaction['id'] );
     127
     128                if ( ! empty( $transaction_response ) && ! empty( $transaction_response->orderCode ) ) {
     129                    // CHECK TRANSACTION VALID AND UPDATE.
     130                    $transaction_order = (string) $transaction_response->orderCode;
     131
     132                    if ( $transaction_order === $order_code ) {
     133                        if ( 'F' === $transaction_response->statusId ) {
     134                            $date      = new DateTime( $parameters['EventData']['CardExpirationDate'] );
     135                            $token_data = array(
     136                                'lastFourDigits' => ( isset( $parameters['EventData']['CardNumber'] ) && strlen( $parameters['EventData']['CardNumber'] ) > 4 ) ? substr( (string) $parameters['EventData']['CardNumber'], -4 ) : 'XXXX',
     137                                'cardType'       => (string) $parameters['EventData']['BankId'],
     138                                'expiryMonth'    => $date->format( 'm' ) ?? null,
     139                                'expiryYear'     => $date->format( 'Y' ) ?? null,
     140                            );
     141                            WC_Vivacom_Smart_Helpers::complete_order( $order->get_id(), $transaction, '', false );
     142
     143                            // Check and save card token if subscription.
     144                            if ( WC_Vivacom_Smart_Helpers::check_subscription( $order->get_id() ) && $order->get_user() ) {
     145                                WC_Vivacom_Smart_Helpers::save_payment_token( $transaction['id'], $order, $token_data );
     146                            }
     147                        }
     148                    }
     149                } else {
     150                    // WEBHOOK WILL BE RESEND.
     151                    return new WP_REST_Response( $res, 400 );
     152                }
     153            } else {
     154                $note = __( 'Transaction failed using Viva.com Smart Checkout', 'viva-com-smart-for-woocommerce' );
     155
     156                if ( isset( $parameters['CorrelationId'] ) && ! empty( $parameters['CorrelationId'] ) ) {
     157                    $note .= __( 'with Viva-CorrelationId: ', 'viva-com-smart-for-woocommerce' ) . $parameters['CorrelationId'];
     158
     159                } else {
     160                    $note .= '.';
     161                }
     162
     163                $order->add_order_note( $note, false );
     164                $order->save();
     165            }
    165166
    166167            return new WP_REST_Response( $res, 200 );
     
    182183            global $wpdb;
    183184
    184             $wc_order_id = $wpdb->get_var( $wpdb->prepare(
    185                 "SELECT woocommerce_order_id FROM {$wpdb->prefix}viva_com_smart_wc_checkout_orders WHERE vivacom_order_code = %s ORDER BY date_add DESC LIMIT 1",
    186                 $viva_ref
    187             )
    188             );
     185            $wc_order_id = $wpdb->get_var(
     186                $wpdb->prepare(
     187                    "SELECT woocommerce_order_id FROM {$wpdb->prefix}viva_com_smart_wc_checkout_orders WHERE vivacom_order_code = %s ORDER BY date_add DESC LIMIT 1",
     188                    $viva_ref
     189                )
     190            );
    189191
    190192            if ( ! empty( $wc_order_id ) ) {
     
    199201                wp_safe_redirect( esc_url_raw( ( wc_get_checkout_url() ) ) );
    200202            }
    201 
    202203        }
    203204
     
    212213                wc_add_notice( __( 'There was a problem processing your payment. Please try again', 'viva-com-smart-for-woocommerce' ), 'error' );
    213214                wp_safe_redirect( esc_url_raw( ( wc_get_checkout_url() ) ) );
    214                 exit();
    215             }
    216 
    217             $viva_ref = sanitize_text_field( wp_unslash( $_GET['s'] ) );
    218             $cancelled = isset( $_GET['cancel'] ) && 1 == $_GET['cancel'];
     215                exit();
     216            }
     217
     218            $viva_ref  = sanitize_text_field( wp_unslash( $_GET['s'] ) );
     219            $cancelled = isset( $_GET['cancel'] ) && 1 == $_GET['cancel'];
    219220            global $wpdb;
    220221
    221             $wc_order_id = $wpdb->get_var( $wpdb->prepare(
    222                 "SELECT woocommerce_order_id FROM {$wpdb->prefix}viva_com_smart_wc_checkout_orders WHERE vivacom_order_code = %s ORDER BY date_add DESC LIMIT 1",
    223                 $viva_ref
    224             )
    225             );
    226 
    227             if (  empty( $wc_order_id ) ) {
    228 
    229                 wc_add_notice( __( 'There was a problem processing your payment. Please try again', 'viva-com-smart-for-woocommerce' ), 'error' );
    230                 wp_safe_redirect( esc_url_raw( ( wc_get_checkout_url() ) ) );
    231                 exit();
    232 
    233             }
    234 
    235             $order = wc_get_order( $wc_order_id );
    236 
    237             if ( $cancelled ) {
    238                 $viva_settings         = get_option( 'woocommerce_vivacom_smart_settings' );
    239                 $environment           = 'yes' === $viva_settings['test_mode'] ? 'demo' : 'live';
    240                 $bearer_authentication = WC_Vivacom_Smart_Helpers::get_bearer_authentication( $environment );
    241                 $order_response = WC_Vivacom_Smart_Helpers::get_order( $bearer_authentication, [ 'orderCode' => $viva_ref ] );
    242                 $stateId = $order_response->stateId;
    243             }
    244 
    245             if ( isset( $stateId ) && 2 == $stateId ) {
    246                 $order->update_status( 'cancelled', __( 'Unpaid order cancelled - customer cancelled in smart checkout.', 'viva-com-smart-for-woocommerce' ) );
    247                 wc_add_notice( __( 'The Order was cancelled', 'viva-com-smart-for-woocommerce' ), 'error' );
    248                 wp_safe_redirect( esc_url_raw( ( wc_get_checkout_url() ) ) );
    249                 exit();
    250             }
    251 
    252             wc_add_notice( __( 'There was a problem processing your payment. Please try again', 'viva-com-smart-for-woocommerce' ), 'error' );
    253             wp_safe_redirect( esc_url_raw( ( wc_get_checkout_url() ) ) );
    254             exit();
    255         }
    256 
     222            $wc_order_id = $wpdb->get_var(
     223                $wpdb->prepare(
     224                    "SELECT woocommerce_order_id FROM {$wpdb->prefix}viva_com_smart_wc_checkout_orders WHERE vivacom_order_code = %s ORDER BY date_add DESC LIMIT 1",
     225                    $viva_ref
     226                )
     227            );
     228
     229            if ( empty( $wc_order_id ) ) {
     230
     231                wc_add_notice( __( 'There was a problem processing your payment. Please try again', 'viva-com-smart-for-woocommerce' ), 'error' );
     232                wp_safe_redirect( esc_url_raw( ( wc_get_checkout_url() ) ) );
     233                exit();
     234
     235            }
     236
     237            $order = wc_get_order( $wc_order_id );
     238
     239            if ( $cancelled ) {
     240                $viva_settings         = get_option( 'woocommerce_vivacom_smart_settings' );
     241                $environment           = 'yes' === $viva_settings['test_mode'] ? 'demo' : 'live';
     242                $bearer_authentication = WC_Vivacom_Smart_Helpers::get_bearer_authentication( $environment );
     243                $order_response        = WC_Vivacom_Smart_Helpers::get_order( $bearer_authentication, array( 'orderCode' => $viva_ref ) );
     244                $state_id               = $order_response->stateId;
     245            }
     246
     247            if ( isset( $state_id ) && 2 == $state_id ) {
     248                $order->update_status( 'cancelled', __( 'Unpaid order cancelled - customer cancelled in smart checkout.', 'viva-com-smart-for-woocommerce' ) );
     249                wc_add_notice( __( 'The Order was cancelled', 'viva-com-smart-for-woocommerce' ), 'error' );
     250                wp_safe_redirect( esc_url_raw( ( wc_get_checkout_url() ) ) );
     251                exit();
     252            }
     253
     254            wc_add_notice( __( 'There was a problem processing your payment. Please try again', 'viva-com-smart-for-woocommerce' ), 'error' );
     255            wp_safe_redirect( esc_url_raw( ( wc_get_checkout_url() ) ) );
     256            exit();
     257        }
    257258    }
    258259
  • viva-com-smart-for-woocommerce/trunk/includes/class-wc-vivacom-smart-helpers.php

    r3245677 r3266406  
    8989     *
    9090     * @param int    $order_id order_id.
    91      * @param array $transaction transaction.
     91     * @param array  $transaction transaction.
    9292     * @param string $note note.
    9393     * @param bool   $has_cart has_cart.
     
    102102        }
    103103
    104         global $wpdb;
     104        global $wpdb;
    105105
    106106        $order = wc_get_order( $order_id );
     
    108108        $order->payment_complete( $transaction['id'] );
    109109
    110         $vivacom_order = self::get_smart_checkout_order( $order_id );
    111 
    112         $transaction_type = in_array( $transaction['typeId'], [ 1, 80 ] ) ? 'preauthorization' : 'payment';
    113 
    114         $transaction_data = array(
    115             'order_id' => $vivacom_order['id'],
    116             'transaction_id' => $transaction['id'],
    117             'transaction_type_id' => self::get_transaction_type( $transaction_type ),
    118             'amount' => $order->get_total()
    119         );
    120 
    121         $status = __( 'Order has been paid with Viva.com Smart Checkout, Transaction Id:', 'viva-com-smart-for-woocommerce' );
    122         $status .= $transaction['id'];
    123         $status .= '<br>' . $note;
    124 
    125         $wpdb->insert(
    126             $wpdb->prefix . 'viva_com_smart_wc_checkout_transactions',
    127             $transaction_data
    128         );
     110        $vivacom_order = self::get_smart_checkout_order( $order_id );
     111
     112        $transaction_type = in_array( $transaction['typeId'], array( 1, 80 ) ) ? 'preauthorization' : 'payment';
     113
     114        $transaction_data = array(
     115            'order_id'            => $vivacom_order['id'],
     116            'transaction_id'      => $transaction['id'],
     117            'transaction_type_id' => self::get_transaction_type( $transaction_type ),
     118            'amount'              => $order->get_total(),
     119        );
     120
     121        $status = __( 'Order has been paid with Viva.com Smart Checkout, Transaction Id:', 'viva-com-smart-for-woocommerce' );
     122        $status .= $transaction['id'];
     123        $status .= '<br>' . $note;
     124
     125        $wpdb->insert(
     126            $wpdb->prefix . 'viva_com_smart_wc_checkout_transactions',
     127            $transaction_data
     128        );
    129129
    130130        $order->set_transaction_id( $transaction['id'] );
     
    134134        $viva_settings = get_option( 'woocommerce_vivacom_smart_settings' );
    135135
    136         $default_order_status = ! empty( $viva_settings['order_status'] ) ? $viva_settings['order_status'] : 'completed';
    137 
    138         $order_status = 'preauthorization' === $transaction_type ? 'on-hold' : $default_order_status;
     136        $default_order_status = ! empty( $viva_settings['order_status'] ) ? $viva_settings['order_status'] : 'completed';
     137
     138        $order_status = 'preauthorization' === $transaction_type ? 'on-hold' : $default_order_status;
    139139
    140140        $order->update_status( $order_status );
     
    143143    }
    144144
    145     /**
    146      * Get order from viva orders table
    147      *
    148      * @param string $order_id order_id.
    149      *
    150      * @return array|null
    151      */
    152     public static function get_smart_checkout_order( string $order_id ) {
    153         global $wpdb;
    154 
    155         return $wpdb->get_row(
    156             $wpdb->prepare(
    157                 "SELECT * FROM {$wpdb->prefix}viva_com_smart_wc_checkout_orders WHERE woocommerce_order_id = %s ORDER BY date_add DESC LIMIT 1",
    158                 $order_id
    159             ), ARRAY_A
    160         );
    161     }
    162 
    163     /**
    164      * Get transaction
    165      *
    166      * @param string $order_id order_id.
    167      * @param string $type_id type_id.
    168      *
    169      * @return string|null
    170      */
    171     public static function get_smart_checkout_transaction(string $order_id, string $type_id) {
    172         global $wpdb;
    173 
    174         return $wpdb->get_row(
    175           $wpdb->prepare(
    176               "SELECT * FROM {$wpdb->prefix}viva_com_smart_wc_checkout_transactions WHERE order_id = %s AND transaction_type_id = %s ORDER BY date_add DESC LIMIT 1",
    177               $order_id,
    178               $type_id
    179           ), ARRAY_A
    180         );
    181     }
    182 
    183     /**
    184      * Get transaction type from db
    185      *
    186      * @param string $name name.
    187      *
    188      * @return string|null $transaction_type_id transaction_type_id
    189      */
    190     public static function get_transaction_type( string $name) {
    191         global $wpdb;
    192 
    193         return $wpdb->get_var(
    194             $wpdb->prepare(
    195                 "SELECT id FROM {$wpdb->prefix}viva_com_smart_wc_checkout_transaction_types WHERE name = %s",
    196                 $name
    197             )
    198         );
    199     }
     145    /**
     146     * Get order from viva orders table
     147     *
     148     * @param string $order_id order_id.
     149     *
     150     * @return array|null
     151     */
     152    public static function get_smart_checkout_order( string $order_id ) {
     153        global $wpdb;
     154
     155        return $wpdb->get_row(
     156            $wpdb->prepare(
     157                "SELECT * FROM {$wpdb->prefix}viva_com_smart_wc_checkout_orders WHERE woocommerce_order_id = %s ORDER BY date_add DESC LIMIT 1",
     158                $order_id
     159            ),
     160            ARRAY_A
     161        );
     162    }
     163
     164    /**
     165     * Get transaction
     166     *
     167     * @param string $order_id order_id.
     168     * @param string $type_id type_id.
     169     *
     170     * @return string|null
     171     */
     172    public static function get_smart_checkout_transaction( string $order_id, string $type_id ) {
     173        global $wpdb;
     174
     175        return $wpdb->get_row(
     176            $wpdb->prepare(
     177                "SELECT * FROM {$wpdb->prefix}viva_com_smart_wc_checkout_transactions WHERE order_id = %s AND transaction_type_id = %s ORDER BY date_add DESC LIMIT 1",
     178                $order_id,
     179                $type_id
     180            ),
     181            ARRAY_A
     182        );
     183    }
     184
     185    /**
     186     * Get transaction type from db
     187     *
     188     * @param string $name name.
     189     *
     190     * @return string|null $transaction_type_id transaction_type_id
     191     */
     192    public static function get_transaction_type( string $name ) {
     193        global $wpdb;
     194
     195        return $wpdb->get_var(
     196            $wpdb->prepare(
     197                "SELECT id FROM {$wpdb->prefix}viva_com_smart_wc_checkout_transaction_types WHERE name = %s",
     198                $name
     199            )
     200        );
     201    }
    200202
    201203    /**
     
    212214    public static function process_refund( $authentication, $source, $order_id, $amount ) {
    213215
    214         global $wpdb;
     216        global $wpdb;
    215217        $order       = wc_get_order( $order_id );
    216218        $order_total = $order->get_total();
     
    227229            }
    228230
    229             $vivacom_order = self::get_smart_checkout_order( $order_id );
    230 
    231             if ( empty( $vivacom_order ) ) {
    232                 throw new Exception( __( 'The viva order code for this order could not be found. Something is wrong!', 'viva-com-smart-for-woocommerce' ) );
    233             }
    234 
    235             // Get capture transaction if present or payment
    236             $vivacom_transaction = self::get_smart_checkout_transaction( $vivacom_order['id'], self::get_transaction_type( 'capture' ) ) ?? self::get_smart_checkout_transaction( $vivacom_order['id'], self::get_transaction_type( 'payment' ) );
     231            $vivacom_order = self::get_smart_checkout_order( $order_id );
     232
     233            if ( empty( $vivacom_order ) ) {
     234                throw new Exception( __( 'The viva order code for this order could not be found. Something is wrong!', 'viva-com-smart-for-woocommerce' ) );
     235            }
     236
     237            // Get capture transaction if present or payment.
     238            $vivacom_transaction = self::get_smart_checkout_transaction( $vivacom_order['id'], self::get_transaction_type( 'capture' ) ) ?? self::get_smart_checkout_transaction( $vivacom_order['id'], self::get_transaction_type( 'payment' ) );
    237239
    238240            if ( empty( $vivacom_transaction ) ) {
     
    250252
    251253                $transaction_data = array(
    252                     'order_id' => $vivacom_order['id'],
    253                     'transaction_id' => $transaction_id,
    254                     'transaction_type_id' => self::get_transaction_type('refund'),
    255                     'amount'          => $refund_amount
     254                    'order_id'            => $vivacom_order['id'],
     255                    'transaction_id'      => $transaction_id,
     256                    'transaction_type_id' => self::get_transaction_type( 'refund' ),
     257                    'amount'              => $refund_amount,
    256258                );
    257259
    258                 $wpdb->insert(
    259                     $wpdb->prefix . 'viva_com_smart_wc_checkout_transactions',
    260                     $transaction_data
    261                 );
     260                $wpdb->insert(
     261                    $wpdb->prefix . 'viva_com_smart_wc_checkout_transactions',
     262                    $transaction_data
     263                );
    262264
    263265                $note = ( $full_refund ) ? __( 'Full refund was executed with ID: ', 'viva-com-smart-for-woocommerce' ) . $transaction_id : __( 'Partial refund was executed with ID: ', 'viva-com-smart-for-woocommerce' ) . $transaction_id;
     
    265267                $order->add_order_note( $note, false );
    266268                $order->save();
    267             } else {
    268                 if ( $transaction_response->hasError() ) {
     269            } elseif ( $transaction_response->hasError() ) {
    269270                    throw new Exception( __( 'Transaction Response Error: ', 'viva-com-smart-for-woocommerce' ) . $transaction_response->getError()->getMessage() );
    270                 }
    271271            }
    272272
     
    277277    }
    278278
    279     /**
    280      * Process Capture
    281      */
    282     public static function process_capture( $authentication, $order, $amount ) {
    283 
    284         global $wpdb;
    285         $transaction_id = null;
    286         $order_id = $order->get_id();
    287         $order_status = $order->get_status();
    288 
    289         try {
    290 
    291             if ( 'on-hold' !== $order_status ) {
    292                 throw new Exception( __( 'Wrong order status for capturing.', 'viva-com-smart-for-woocommerce' ) );
    293             }
    294 
    295             if ( self::TECHNICAL_NAME !== $order->get_payment_method() ) {
    296                 throw new Exception( __( 'Wrong payment method of order.', 'viva-com-smart-for-woocommerce' ) );
    297             }
    298 
    299             $vivacom_order = WC_Vivacom_Smart_Helpers::get_smart_checkout_order( $order_id );
    300 
    301             if ( empty( $vivacom_order ) ) {
    302                 throw new Exception( __(  'The viva order code for this order could not be found. Something is wrong!', 'viva-com-smart-for-woocommerce' ) );
    303             }
    304 
    305             $vivacom_transaction = self::get_smart_checkout_transaction( $vivacom_order['id'], self::get_transaction_type('preauthorization') );
    306 
    307             if ( empty( $vivacom_transaction ) ) {
    308                 throw new Exception( __( 'The transaction ID for this order could not be found. Something is wrong!', 'viva-com-smart-for-woocommerce' ) );
    309             }
    310 
    311             if ( ! ( self::get_transaction_type('preauthorization') === $vivacom_transaction['transaction_type_id'] ) ) {
    312                 throw new Exception( __( 'Wrong transaction type!', 'viva-com-smart-for-woocommerce' ) );
    313             }
    314 
    315             $transaction_client   = new TransactionClient( $authentication );
    316             $transaction_response = $transaction_client->captureAuthorizedTransaction( $vivacom_transaction['transaction_id'], $amount );
    317 
    318             WC_Vivacom_Smart_Logger::log( 'Api Capture response: ' . wp_json_encode( $transaction_response->all() ) );
    319 
    320             if ( $transaction_response->isSuccessful() && ! empty( $transaction_response->getBody() ) && ! empty( $transaction_response->getBody()->transactionId ) ) {
    321                 $transaction_id = $transaction_response->getBody()->transactionId;
    322 
    323                 $transaction_data = array(
    324                     'order_id' => $vivacom_order['id'],
    325                     'transaction_id' => $transaction_id,
    326                     'transaction_type_id' => self::get_transaction_type('capture'),
    327                     'amount'          => $amount
    328                 );
    329 
    330                 $wpdb->insert(
    331                     $wpdb->prefix . 'viva_com_smart_wc_checkout_transactions',
    332                     $transaction_data
    333                 );
    334 
    335             } else {
    336                 if ( $transaction_response->hasError() ) {
    337                     throw new Exception( __( 'Transaction Response Error: ', 'viva-com-smart-for-woocommerce' ) . $transaction_response->getError()->getMessage() );
    338                 }
    339             }
    340 
    341         } catch ( Exception $e ) {
    342             return new WP_Error( 'error', $e->getMessage() );
    343         }
    344 
    345         return [
    346             'transaction_id' => $transaction_id ?? 'n/a'
    347         ];
    348     }
    349 
    350     /**
    351      * Process Void
    352      */
    353     public static function process_void( $authentication, $source, $order, $amount ) {
    354         global $wpdb;
    355         $transaction_id = null;
    356         $order_id = $order->get_id();
    357         $order_status = $order->get_status();
    358 
    359         try {
    360             if ( 'on-hold' !== $order_status ) {
    361                 throw new Exception( __( 'Wrong order status for capturing.', 'viva-com-smart-for-woocommerce' ) );
    362             }
    363 
    364             if ( self::TECHNICAL_NAME !== $order->get_payment_method() ) {
    365                 throw new Exception( __( 'Wrong payment method of order.', 'viva-com-smart-for-woocommerce' ) );
    366             }
    367 
    368             $vivacom_order = WC_Vivacom_Smart_Helpers::get_smart_checkout_order( $order_id );
    369 
    370             if ( empty( $vivacom_order ) ) {
    371                 throw new Exception( __(  'The viva order code for this order could not be found. Something is wrong!', 'viva-com-smart-for-woocommerce' ) );
    372             }
    373 
    374             $vivacom_transaction = self::get_smart_checkout_transaction( $vivacom_order['id'], self::get_transaction_type('preauthorization') );
    375 
    376             if ( empty( $vivacom_transaction ) ) {
    377                 throw new Exception( __( 'The transaction ID for this order could not be found. Something is wrong!', 'viva-com-smart-for-woocommerce' ) );
    378             }
    379 
    380             if ( ! ( self::get_transaction_type('preauthorization') === $vivacom_transaction['transaction_type_id'] ) ) {
    381                 throw new Exception( __( 'Wrong transaction type!', 'viva-com-smart-for-woocommerce' ) );
    382             }
    383 
    384             $transaction_client   = new TransactionClient( $authentication );
    385             $transaction_response = $transaction_client->voidAuthorizedTransaction( $vivacom_transaction['transaction_id'], $amount, $source );
    386 
    387             WC_Vivacom_Smart_Logger::log( 'Api Void response: ' . wp_json_encode( $transaction_response->all() ) );
    388 
    389             if ( $transaction_response->isSuccessful() && ! empty( $transaction_response->getBody() ) && ! empty( $transaction_response->getBody()->transactionId ) ) {
    390                 $transaction_id = $transaction_response->getBody()->transactionId;
    391 
    392                 $transaction_data = array(
    393                     'order_id' => $vivacom_order['id'],
    394                     'transaction_id' => $transaction_id,
    395                     'transaction_type_id' => self::get_transaction_type('void'),
    396                     'amount'          => $amount
    397                 );
    398 
    399                 $wpdb->insert(
    400                     $wpdb->prefix . 'viva_com_smart_wc_checkout_transactions',
    401                     $transaction_data
    402                 );
    403 
    404             } else {
    405                 if ( $transaction_response->hasError() ) {
    406                     throw new Exception( __( 'Transaction Response Error: ', 'viva-com-smart-for-woocommerce' ) . $transaction_response->getError()->getMessage() );
    407                 }
    408             }
    409 
    410         } catch ( Exception $e ) {
    411             return new WP_Error( 'error', $e->getMessage() );
    412         }
    413 
    414         return [
    415             'transaction_id' => $transaction_id ?? 'n/a'
    416         ];
    417     }
     279    /**
     280     * Process Capture
     281     *
     282     * @param Authentication  $authentication authentication.
     283     * @param object|WC_Order $order order.
     284     * @param string          $amount amount.
     285     *
     286     * @return array|WP_Error
     287     * @throws Exception Throws exception.
     288     */
     289    public static function process_capture( $authentication, $order, $amount ) {
     290
     291        global $wpdb;
     292        $transaction_id = null;
     293        $order_id       = $order->get_id();
     294        $order_status   = $order->get_status();
     295
     296        try {
     297
     298            if ( 'on-hold' !== $order_status ) {
     299                throw new Exception( __( 'Wrong order status for capturing.', 'viva-com-smart-for-woocommerce' ) );
     300            }
     301
     302            if ( self::TECHNICAL_NAME !== $order->get_payment_method() ) {
     303                throw new Exception( __( 'Wrong payment method of order.', 'viva-com-smart-for-woocommerce' ) );
     304            }
     305
     306            $vivacom_order = self::get_smart_checkout_order( $order_id );
     307
     308            if ( empty( $vivacom_order ) ) {
     309                throw new Exception( __( 'The viva order code for this order could not be found. Something is wrong!', 'viva-com-smart-for-woocommerce' ) );
     310            }
     311
     312            $vivacom_transaction = self::get_smart_checkout_transaction( $vivacom_order['id'], self::get_transaction_type( 'preauthorization' ) );
     313
     314            if ( empty( $vivacom_transaction ) ) {
     315                throw new Exception( __( 'The transaction ID for this order could not be found. Something is wrong!', 'viva-com-smart-for-woocommerce' ) );
     316            }
     317
     318            if ( ! ( self::get_transaction_type( 'preauthorization' ) === $vivacom_transaction['transaction_type_id'] ) ) {
     319                throw new Exception( __( 'Wrong transaction type!', 'viva-com-smart-for-woocommerce' ) );
     320            }
     321
     322            $transaction_client   = new TransactionClient( $authentication );
     323            $transaction_response = $transaction_client->captureAuthorizedTransaction( $vivacom_transaction['transaction_id'], $amount );
     324
     325            WC_Vivacom_Smart_Logger::log( 'Api Capture response: ' . wp_json_encode( $transaction_response->all() ) );
     326
     327            if ( $transaction_response->isSuccessful() && ! empty( $transaction_response->getBody() ) && ! empty( $transaction_response->getBody()->transactionId ) ) {
     328                $transaction_id = $transaction_response->getBody()->transactionId;
     329
     330                $transaction_data = array(
     331                    'order_id'            => $vivacom_order['id'],
     332                    'transaction_id'      => $transaction_id,
     333                    'transaction_type_id' => self::get_transaction_type( 'capture' ),
     334                    'amount'              => $amount,
     335                );
     336
     337                $wpdb->insert(
     338                    $wpdb->prefix . 'viva_com_smart_wc_checkout_transactions',
     339                    $transaction_data
     340                );
     341
     342            } elseif ( $transaction_response->hasError() ) {
     343                    throw new Exception( __( 'Transaction Response Error: ', 'viva-com-smart-for-woocommerce' ) . $transaction_response->getError()->getMessage() );
     344            }
     345        } catch ( Exception $e ) {
     346            return new WP_Error( 'error', $e->getMessage() );
     347        }
     348
     349        return array(
     350            'transaction_id' => $transaction_id ?? 'n/a',
     351        );
     352    }
     353
     354    /**
     355     * Process Void
     356     *
     357     * @param Authentication  $authentication authentication.
     358     * @param string          $source source.
     359     * @param object|WC_Order $order order.
     360     * @param string          $amount amount.
     361     *
     362     * @return array|WP_Error
     363     * @throws Exception Throws exception.
     364     */
     365    public static function process_void( $authentication, $source, $order, $amount ) {
     366        global $wpdb;
     367        $transaction_id = null;
     368        $order_id       = $order->get_id();
     369        $order_status   = $order->get_status();
     370
     371        try {
     372            if ( 'on-hold' !== $order_status ) {
     373                throw new Exception( __( 'Wrong order status for capturing.', 'viva-com-smart-for-woocommerce' ) );
     374            }
     375
     376            if ( self::TECHNICAL_NAME !== $order->get_payment_method() ) {
     377                throw new Exception( __( 'Wrong payment method of order.', 'viva-com-smart-for-woocommerce' ) );
     378            }
     379
     380            $vivacom_order = self::get_smart_checkout_order( $order_id );
     381
     382            if ( empty( $vivacom_order ) ) {
     383                throw new Exception( __( 'The viva order code for this order could not be found. Something is wrong!', 'viva-com-smart-for-woocommerce' ) );
     384            }
     385
     386            $vivacom_transaction = self::get_smart_checkout_transaction( $vivacom_order['id'], self::get_transaction_type( 'preauthorization' ) );
     387
     388            if ( empty( $vivacom_transaction ) ) {
     389                throw new Exception( __( 'The transaction ID for this order could not be found. Something is wrong!', 'viva-com-smart-for-woocommerce' ) );
     390            }
     391
     392            if ( ! ( self::get_transaction_type( 'preauthorization' ) === $vivacom_transaction['transaction_type_id'] ) ) {
     393                throw new Exception( __( 'Wrong transaction type!', 'viva-com-smart-for-woocommerce' ) );
     394            }
     395
     396            $transaction_client   = new TransactionClient( $authentication );
     397            $transaction_response = $transaction_client->voidAuthorizedTransaction( $vivacom_transaction['transaction_id'], $amount, $source );
     398
     399            WC_Vivacom_Smart_Logger::log( 'Api Void response: ' . wp_json_encode( $transaction_response->all() ) );
     400
     401            if ( $transaction_response->isSuccessful() && ! empty( $transaction_response->getBody() ) && ! empty( $transaction_response->getBody()->transactionId ) ) {
     402                $transaction_id = $transaction_response->getBody()->transactionId;
     403
     404                $transaction_data = array(
     405                    'order_id'            => $vivacom_order['id'],
     406                    'transaction_id'      => $transaction_id,
     407                    'transaction_type_id' => self::get_transaction_type( 'void' ),
     408                    'amount'              => $amount,
     409                );
     410
     411                $wpdb->insert(
     412                    $wpdb->prefix . 'viva_com_smart_wc_checkout_transactions',
     413                    $transaction_data
     414                );
     415
     416            } elseif ( $transaction_response->hasError() ) {
     417                    throw new Exception( __( 'Transaction Response Error: ', 'viva-com-smart-for-woocommerce' ) . $transaction_response->getError()->getMessage() );
     418            }
     419        } catch ( Exception $e ) {
     420            return new WP_Error( 'error', $e->getMessage() );
     421        }
     422
     423        return array(
     424            'transaction_id' => $transaction_id ?? 'n/a',
     425        );
     426    }
    418427
    419428    /**
     
    422431     * @param string          $transaction_id transaction_id.
    423432     * @param object|WC_Order $order order.
    424      * @param array           $tokenData tokenData.
     433     * @param array           $token_data token_data.
    425434     *
    426435     * @return int
    427436     */
    428     public static function save_payment_token( $transaction_id, $order, $tokenData ) {
    429         // Check token provided or create.
    430         global $wpdb;
    431         $users_tokens = WC_Payment_Tokens::get_customer_tokens( $order->get_customer_id(), self::TECHNICAL_NAME );
    432 
    433         foreach ( $users_tokens as $key => $value ) {
    434             $token_object = WC_Payment_Tokens::get( $key );
    435             if ( $token_object->get_token() === $transaction_id ) {
    436                 $token = $token_object;
    437                 break;
    438             }
    439         }
    440 
    441         if ( empty( $token ) ) {
    442             $token = new WC_Payment_Token_CC();
    443         }
    444 
    445         $token->set_token( $transaction_id );
    446         $token->set_gateway_id( self::TECHNICAL_NAME );
    447         $token->set_user_id( $order->get_customer_id() );
    448         $token->set_card_type( $tokenData['cardType'] );
    449         $token->set_last4( $tokenData['lastFourDigits'] );
    450         $token->set_expiry_month( $tokenData['expiryMonth'] );
    451         $token->set_expiry_year( $tokenData['expiryYear'] );
    452         $token->save();
    453 
    454         if ( ! empty( $order ) ) {
    455             if ( self::check_subscription( $order->get_id() ) ) {
    456                 if ( function_exists( 'wcs_get_subscriptions_for_order' ) && class_exists( 'WC_Subscriptions_Change_Payment_Gateway' ) ) {
    457                     $subscriptions = wcs_get_subscriptions_for_order( $order );
    458                     foreach ( $subscriptions as $subscription ) {
    459                         // check if subscription already has a saved token related.
    460                         $token_id = $wpdb->get_var( $wpdb->prepare(
    461                             "SELECT token_id FROM {$wpdb->prefix}viva_com_smart_wc_checkout_recurring WHERE recurring_id = %s ORDER BY date_add LIMIT 1",
    462                             $subscription->get_id()
    463                         )
    464                         );
    465 
    466                         $transaction_object_id = $wpdb->get_var( $wpdb->prepare(
    467                             "SELECT id FROM {$wpdb->prefix}viva_com_smart_wc_checkout_transactions WHERE transaction_id = %s ORDER BY date_add LIMIT 1",
    468                             $transaction_id
    469                         )
    470                         );
    471 
    472                         $wpdb->insert($wpdb->prefix."viva_com_smart_wc_checkout_recurring",
    473                             array(
    474                                 "token_id" => $token->get_id(),
    475                                 "transaction_id" => $transaction_object_id,
    476                                 "recurring_id" => $subscription->get_id()
    477                             )
    478                         );
    479 
    480 
    481                         if ( ! empty( $token_id ) ) {
    482                             WC_Subscriptions_Change_Payment_Gateway::update_payment_method( $subscription, self::TECHNICAL_NAME, $token->get_meta_data() );
    483                         }
    484                     }
    485                 }
    486             }
    487         }
    488 
    489         return $token->get_id();
    490     }
     437    public static function save_payment_token( $transaction_id, $order, $token_data ) {
     438        // Check token provided or create.
     439        global $wpdb;
     440        $users_tokens = WC_Payment_Tokens::get_customer_tokens( $order->get_customer_id(), self::TECHNICAL_NAME );
     441
     442        foreach ( $users_tokens as $key => $value ) {
     443            $token_object = WC_Payment_Tokens::get( $key );
     444            if ( $token_object->get_token() === $transaction_id ) {
     445                $token = $token_object;
     446                break;
     447            }
     448        }
     449
     450        if ( empty( $token ) ) {
     451            $token = new WC_Payment_Token_CC();
     452        }
     453
     454        $token->set_token( $transaction_id );
     455        $token->set_gateway_id( self::TECHNICAL_NAME );
     456        $token->set_user_id( $order->get_customer_id() );
     457        $token->set_card_type( $token_data['cardType'] );
     458        $token->set_last4( $token_data['lastFourDigits'] );
     459        $token->set_expiry_month( $token_data['expiryMonth'] );
     460        $token->set_expiry_year( $token_data['expiryYear'] );
     461        $token->save();
     462
     463        if ( ! empty( $order ) ) {
     464            if ( self::check_subscription( $order->get_id() ) ) {
     465                if ( function_exists( 'wcs_get_subscriptions_for_order' ) && class_exists( 'WC_Subscriptions_Change_Payment_Gateway' ) ) {
     466                    $subscriptions = wcs_get_subscriptions_for_order( $order );
     467                    foreach ( $subscriptions as $subscription ) {
     468                        // check if subscription already has a saved token related.
     469                        $token_id = $wpdb->get_var(
     470                            $wpdb->prepare(
     471                                "SELECT token_id FROM {$wpdb->prefix}viva_com_smart_wc_checkout_recurring WHERE recurring_id = %s ORDER BY date_add LIMIT 1",
     472                                $subscription->get_id()
     473                            )
     474                        );
     475
     476                        $transaction_object_id = $wpdb->get_var(
     477                            $wpdb->prepare(
     478                                "SELECT id FROM {$wpdb->prefix}viva_com_smart_wc_checkout_transactions WHERE transaction_id = %s ORDER BY date_add LIMIT 1",
     479                                $transaction_id
     480                            )
     481                        );
     482
     483                        $wpdb->insert(
     484                            $wpdb->prefix . 'viva_com_smart_wc_checkout_recurring',
     485                            array(
     486                                'token_id'       => $token->get_id(),
     487                                'transaction_id' => $transaction_object_id,
     488                                'recurring_id'   => $subscription->get_id(),
     489                            )
     490                        );
     491
     492                        if ( ! empty( $token_id ) ) {
     493                            WC_Subscriptions_Change_Payment_Gateway::update_payment_method( $subscription, self::TECHNICAL_NAME, $token->get_meta_data() );
     494                        }
     495                    }
     496                }
     497            }
     498        }
     499
     500        return $token->get_id();
     501    }
    491502
    492503    /**
     
    509520
    510521        return ! empty( $merchant_currencies ) ? $merchant_currencies : array();
    511 
    512522    }
    513523
     
    608618    }
    609619
    610     /**
    611     * Create Source Item
    612     *
    613     * @param Authentication $authentication authentication.
    614      * @param string $prefix
    615      * @param array $options
    616     *
    617      * @return void
    618     */
    619     public static function create_source_item ( Authentication $authentication, string $prefix, array $options ) {
    620         $source_client    = new SourceClient( $authentication );
    621         do {
    622             $already_exists_error = false;
    623             $random_code = sprintf("%04d", rand( 101, 9999));
    624             $options['code'] = "$prefix-" . $random_code;
    625             $source_item     = new SourceItem( (object) $options );
    626             $source_response = $source_client->createSource( $source_item );
    627             WC_Vivacom_Smart_Logger::log( 'API CREATE SOURCE' . ( $source_response->isSuccessful() ? ' SUCCESS ' : ' FAILED ' ) . " \nARGS: " . wp_json_encode( $options ) . "\nRESULT: " . wp_json_encode( $source_response->all() ) );
    628             $already_exists_error = $source_response->isSuccessful() && 409 === $source_response->getHttpCode() && $source_response->hasError() && stripos( $source_response->getBody()->message, 'already exists' );
    629         } while ( true === $already_exists_error );
    630 
    631         return $source_item;
    632     }
     620    /**
     621    * Create Source Item
     622    *
     623    * @param Authentication $authentication authentication.
     624     * @param string         $prefix prefix.
     625     * @param array          $options options.
     626    *
     627     * @return SourceItem
     628    */
     629    public static function create_source_item( Authentication $authentication, string $prefix, array $options ) {
     630        $source_client = new SourceClient( $authentication );
     631        do {
     632            $already_exists_error = false;
     633            $random_code          = sprintf( '%04d', rand( 101, 9999 ) );
     634            $options['code']      = "$prefix-" . $random_code;
     635            $source_item          = new SourceItem( (object) $options );
     636            $source_response      = $source_client->createSource( $source_item );
     637            WC_Vivacom_Smart_Logger::log( 'API CREATE SOURCE' . ( $source_response->isSuccessful() ? ' SUCCESS ' : ' FAILED ' ) . " \nARGS: " . wp_json_encode( $options ) . "\nRESULT: " . wp_json_encode( $source_response->all() ) );
     638            $already_exists_error = $source_response->isSuccessful() && 409 === $source_response->getHttpCode() && $source_response->hasError() && stripos( $source_response->getBody()->message, 'already exists' );
     639        } while ( true === $already_exists_error );
     640
     641        return $source_item;
     642    }
    633643
    634644    /**
     
    643653        $domain           = self::get_domain();
    644654        $options          = array(
    645             'name'       => sprintf( Application::SOURCE_NAME_FORMAT, $cms_abbreviation, $domain ),
    646             'domain'     => $domain,
    647             'successUrl' => self::get_redirect_url( 'success' ),
    648             'failureUrl' => self::get_redirect_url( 'fail' ),
     655            'name'             => sprintf( Application::SOURCE_NAME_FORMAT, $cms_abbreviation, $domain ),
     656            'domain'           => $domain,
     657            'successUrl'       => self::get_redirect_url( 'success' ),
     658            'failureUrl'       => self::get_redirect_url( 'fail' ),
    649659            'paramCancelOrder' => Application::PARAM_CANCEL_ORDER,
    650660        );
    651661
    652         $source_item = self::create_source_item( $authentication, $cms_abbreviation, $options );
     662        $source_item = self::create_source_item( $authentication, $cms_abbreviation, $options );
    653663        return ! empty( $source_item ) ? $source_item : null;
    654664    }
     
    735745
    736746        return $order_response ?? null;
    737 
    738     }
    739 
    740     /**
    741      * Get Viva order
    742      *
    743      * @param Authentication $authentication authentication
    744      * @param array $options options
    745      *
    746      * @return Response|null
    747      */
    748     public static function get_order( Authentication $authentication, $options = array() ) {
    749         $order_client = new OrderClient( $authentication );
    750         $order_response = $order_client->retrieveOrder( $options );
    751         if ( $order_response->isSuccessful() && ! is_null( $order_response->getBody() ) ) {
    752             $response = $order_response->getBody();
    753         } else {
    754             WC_Vivacom_Smart_Logger::log( 'Order Retrieve failed for order code : ' . $options['orderCode'] );
    755         }
    756 
    757         return $response ?? null;
    758     }
     747    }
     748
     749    /**
     750     * Get Viva order
     751     *
     752     * @param Authentication $authentication authentication.
     753     * @param array          $options options.
     754     *
     755     * @return Response|null
     756     */
     757    public static function get_order( Authentication $authentication, $options = array() ) {
     758        $order_client   = new OrderClient( $authentication );
     759        $order_response = $order_client->retrieveOrder( $options );
     760        if ( $order_response->isSuccessful() && ! is_null( $order_response->getBody() ) ) {
     761            $response = $order_response->getBody();
     762        } else {
     763            WC_Vivacom_Smart_Logger::log( 'Order Retrieve failed for order code : ' . $options['orderCode'] );
     764        }
     765
     766        return $response ?? null;
     767    }
    759768
    760769    /**
     
    848857            || ( function_exists( 'wcs_is_subscription' ) && wcs_is_subscription( $order_id ) )
    849858            || ( function_exists( 'wcs_order_contains_renewal' ) && wcs_order_contains_renewal( $order_id ) );
    850 
    851859    }
    852860
     
    869877            'viva-com-smart-for-woocommerce'
    870878        );
    871         $settings = array(
    872             'main_title'                => array(
    873                 'title' => __( 'Viva.com Smart Checkout settings', 'viva-com-smart-for-woocommerce' ),
    874                 'type'  => 'title',
    875             ),
    876             'enabled'                   => array(
    877                 'title'   => __( 'Enable Viva.com Smart Checkout', 'viva-com-smart-for-woocommerce' ),
    878                 'type'    => 'checkbox',
    879                 'label'   => __( 'Enable Viva.com Smart Checkout', 'viva-com-smart-for-woocommerce' ),
    880                 'default' => 'no',
    881             ),
    882             'sep'                       => array(
    883                 'title'       => '',
    884                 'type'        => 'title',
    885                 'description' => '<hr>',
    886             ),
    887             'credentials'               => array(
    888                 'title'       => __( 'Set Viva.com API credentials', 'viva-com-smart-for-woocommerce' ),
    889                 'type'        => 'title',
    890                 'description' => $credentials_desc,
    891             ),
    892             'test_mode'                 => array(
    893                 'title'       => __( 'Demo mode', 'viva-com-smart-for-woocommerce' ),
    894                 'type'        => 'checkbox',
    895                 'label'       => __( 'Enable demo mode', 'viva-com-smart-for-woocommerce' ),
    896                 'description' => $test_mode_desc,
    897                 'default'     => 'yes',
    898             ),
    899             'title_live'                => array(
    900                 'title' => __( 'Live mode credentials', 'viva-com-smart-for-woocommerce' ),
    901                 'type'  => 'title',
    902             ),
    903             'title_demo'                => array(
    904                 'title' => __( 'Demo mode credentials', 'viva-com-smart-for-woocommerce' ),
    905                 'type'  => 'title',
    906             ),
    907             'client_id'                 => array(
    908                 'title'       => __( 'Live Client ID', 'viva-com-smart-for-woocommerce' ),
     879        $settings       = array(
     880            'main_title'                => array(
     881                'title' => __( 'Viva.com Smart Checkout settings', 'viva-com-smart-for-woocommerce' ),
     882                'type'  => 'title',
     883            ),
     884            'enabled'                   => array(
     885                'title'   => __( 'Enable Viva.com Smart Checkout', 'viva-com-smart-for-woocommerce' ),
     886                'type'    => 'checkbox',
     887                'label'   => __( 'Enable Viva.com Smart Checkout', 'viva-com-smart-for-woocommerce' ),
     888                'default' => 'no',
     889            ),
     890            'sep'                       => array(
     891                'title'       => '',
     892                'type'        => 'title',
     893                'description' => '<hr>',
     894            ),
     895            'credentials'               => array(
     896                'title'       => __( 'Set Viva.com API credentials', 'viva-com-smart-for-woocommerce' ),
     897                'type'        => 'title',
     898                'description' => $credentials_desc,
     899            ),
     900            'test_mode'                 => array(
     901                'title'       => __( 'Demo mode', 'viva-com-smart-for-woocommerce' ),
     902                'type'        => 'checkbox',
     903                'label'       => __( 'Enable demo mode', 'viva-com-smart-for-woocommerce' ),
     904                'description' => $test_mode_desc,
     905                'default'     => 'yes',
     906            ),
     907            'title_live'                => array(
     908                'title' => __( 'Live mode credentials', 'viva-com-smart-for-woocommerce' ),
     909                'type'  => 'title',
     910            ),
     911            'title_demo'                => array(
     912                'title' => __( 'Demo mode credentials', 'viva-com-smart-for-woocommerce' ),
     913                'type'  => 'title',
     914            ),
     915            'client_id'                 => array(
     916                'title'       => __( 'Live Client ID', 'viva-com-smart-for-woocommerce' ),
     917                'type'        => 'text',
     918                'description' => __( 'Client ID provided by Viva.com.', 'viva-com-smart-for-woocommerce' ),
     919                'default'     => '',
     920            ),
     921            'demo_client_id'            => array(
     922                'title'       => __( 'Demo Client ID', 'viva-com-smart-for-woocommerce' ),
     923                'type'        => 'text',
     924                'description' => __( 'Client ID provided by Viva.com. ', 'viva-com-smart-for-woocommerce' ),
     925                'default'     => '',
     926            ),
     927            'client_secret'             => array(
     928                'title'       => __( 'Live Client Secret', 'viva-com-smart-for-woocommerce' ),
     929                'type'        => 'text',
     930                'description' => __( 'Client Secret provided by Viva.com.', 'viva-com-smart-for-woocommerce' ),
     931                'default'     => '',
     932            ),
     933            'demo_client_secret'        => array(
     934                'title'       => __( 'Demo Client Secret', 'viva-com-smart-for-woocommerce' ),
     935                'type'        => 'text',
     936                'description' => __( 'Client Secret provided by Viva.com.', 'viva-com-smart-for-woocommerce' ),
     937                'default'     => '',
     938            ),
     939            'sep_2'                     => array(
     940                'title'       => '',
     941                'type'        => 'title',
     942                'description' => '<hr>',
     943            ),
     944            'advanced_settings_title'   => array(
     945                'title' => __( 'Advanced settings', 'viva-com-smart-for-woocommerce' ),
     946                'type'  => 'title',
     947            ),
     948            'advanced_settings_enabled' => array(
     949                'title'   => __( 'Show advanced settings', 'viva-com-smart-for-woocommerce' ),
     950                'type'    => 'checkbox',
     951                'label'   => __( 'Show advanced settings. If this checkbox is unchecked, the plugin will use default settings.', 'viva-com-smart-for-woocommerce' ),
     952                'default' => 'no',
     953            ),
     954            'sep_3'                     => array(
     955                'title'       => '',
     956                'type'        => 'title',
     957                'description' => '<hr>',
     958            ),
     959            'main_descr'                => array(
     960                'title' => $main_desc,
     961                'type'  => 'title',
     962            ),
     963            'title'                     => array(
     964                'title'       => __( 'Title', 'viva-com-smart-for-woocommerce' ),
     965                'type'        => 'text',
     966                'description' => __( 'This controls the title that the user sees during checkout.', 'viva-com-smart-for-woocommerce' ),
     967                'default'     => __( 'Viva.com Smart Checkout', 'viva-com-smart-for-woocommerce' ),
     968            ),
     969            'description'               => array(
     970                'title'       => __( 'Description', 'viva-com-smart-for-woocommerce' ),
     971                'type'        => 'text',
     972                'description' => __( 'This controls the description that the user sees during checkout.', 'viva-com-smart-for-woocommerce' ),
     973                'default'     => __( 'Pay using 30+ methods (cards, digital wallets, local payment methods, online banking, and more)', 'viva-com-smart-for-woocommerce' ),
     974            ),
     975            'installments'              => array(
     976                'title'       => __( 'Instalments', 'viva-com-smart-for-woocommerce' ),
     977                'type'        => 'text',
     978                'description' => __( 'WARNING: Only available to Greek Viva.com accounts. <br>Example: 90:3,180:6<br>Order total 90 euro -> allow 0 and 3 installments <br>Order total 180 euro -> allow 0, 3 and 6 installments<br>Leave empty in case you do not want to offer installments.', 'viva-com-smart-for-woocommerce' ),
     979                'default'     => '',
     980            ),
     981            'brand_color'              => array(
     982                'title'       => __( 'Brand color', 'viva-com-smart-for-woocommerce' ),
    909983                'type'        => 'text',
    910                 'description' => __( 'Client ID provided by Viva.com.', 'viva-com-smart-for-woocommerce' ),
     984                'description' => __('Select a color or enter a HEX code.', 'viva-com-smart-for-woocommerce'),
    911985                'default'     => '',
    912986            ),
    913             'demo_client_id'            => array(
    914                 'title'       => __( 'Demo Client ID', 'viva-com-smart-for-woocommerce' ),
    915                 'type'        => 'text',
    916                 'description' => __( 'Client ID provided by Viva.com. ', 'viva-com-smart-for-woocommerce' ),
    917                 'default'     => '',
    918             ),
    919             'client_secret'             => array(
    920                 'title'       => __( 'Live Client Secret', 'viva-com-smart-for-woocommerce' ),
    921                 'type'        => 'text',
    922                 'description' => __( 'Client Secret provided by Viva.com.', 'viva-com-smart-for-woocommerce' ),
    923                 'default'     => '',
    924             ),
    925             'demo_client_secret'        => array(
    926                 'title'       => __( 'Demo Client Secret', 'viva-com-smart-for-woocommerce' ),
    927                 'type'        => 'text',
    928                 'description' => __( 'Client Secret provided by Viva.com.', 'viva-com-smart-for-woocommerce' ),
    929                 'default'     => '',
    930             ),
    931             'sep_2'                     => array(
    932                 'title'       => '',
    933                 'type'        => 'title',
    934                 'description' => '<hr>',
    935             ),
    936             'advanced_settings_title'   => array(
    937                 'title' => __( 'Advanced settings', 'viva-com-smart-for-woocommerce' ),
    938                 'type'  => 'title',
    939             ),
    940             'advanced_settings_enabled' => array(
    941                 'title'   => __( 'Show advanced settings', 'viva-com-smart-for-woocommerce' ),
    942                 'type'    => 'checkbox',
    943                 'label'   => __( 'Show advanced settings. If this checkbox is unchecked, the plugin will use default settings.', 'viva-com-smart-for-woocommerce' ),
    944                 'default' => 'no',
    945             ),
    946             'sep_3'                     => array(
    947                 'title'       => '',
    948                 'type'        => 'title',
    949                 'description' => '<hr>',
    950             ),
    951             'main_descr'                => array(
    952                 'title' => $main_desc,
    953                 'type'  => 'title',
    954             ),
    955             'title'                     => array(
    956                 'title'       => __( 'Title', 'viva-com-smart-for-woocommerce' ),
    957                 'type'        => 'text',
    958                 'description' => __( 'This controls the title that the user sees during checkout.', 'viva-com-smart-for-woocommerce' ),
    959                 'default'     => __( 'Viva.com Smart Checkout', 'viva-com-smart-for-woocommerce' ),
    960             ),
    961             'description'               => array(
    962                 'title'       => __( 'Description', 'viva-com-smart-for-woocommerce' ),
    963                 'type'        => 'text',
    964                 'description' => __( 'This controls the description that the user sees during checkout.', 'viva-com-smart-for-woocommerce' ),
    965                 'default'     => __( 'Pay using 30+ methods (cards, digital wallets, local payment methods, online banking, and more)', 'viva-com-smart-for-woocommerce' ),
    966             ),
    967             'installments'              => array(
    968                 'title'       => __( 'Instalments', 'viva-com-smart-for-woocommerce' ),
    969                 'type'        => 'text',
    970                 'description' => __( 'WARNING: Only available to Greek Viva.com accounts. <br>Example: 90:3,180:6<br>Order total 90 euro -> allow 0 and 3 installments <br>Order total 180 euro -> allow 0, 3 and 6 installments<br>Leave empty in case you do not want to offer installments.', 'viva-com-smart-for-woocommerce' ),
    971                 'default'     => '',
    972             ),
    973 
    974             'source_code'               => array(
    975                 'title'       => __( 'Live Source Code List', 'viva-com-smart-for-woocommerce' ),
    976                 'type'        => 'select',
    977                 'description' => __( 'Provides a list with all source codes that are set in your Viva.com banking app.', 'viva-com-smart-for-woocommerce' ),
    978                 'default'     => '',
    979                 'options'     => array(),
    980             ),
    981             'demo_source_code'          => array(
    982                 'title'       => __( 'Demo Source Code List', 'viva-com-smart-for-woocommerce' ),
    983                 'type'        => 'select',
    984                 'description' => __( 'Provides a list with all source codes that are set in your Viva.com banking app.', 'viva-com-smart-for-woocommerce' ),
    985                 'default'     => '',
    986                 'options'     => array(),
    987             ),
    988             'logo_enabled'              => array(
    989                 'title'   => __( 'Show logo on checkout page', 'viva-com-smart-for-woocommerce' ),
    990                 'type'    => 'checkbox',
    991                 'label'   => __( 'Enable Viva.com logo on checkout page (default = yes).', 'viva-com-smart-for-woocommerce' ),
    992                 'default' => 'yes',
    993             ),
    994             'order_status'              => array(
    995                 'title'       => __( 'Order status after successful payment.', 'viva-com-smart-for-woocommerce' ),
    996                 'description' => __( 'Your WooCommerce will be updated to this status after successful payment on Viva.com (default = completed).', 'viva-com-smart-for-woocommerce' ),
    997                 'default'     => 'completed',
    998                 'type'        => 'select',
    999                 'options'     => array(
    1000                     'completed'  => __( 'Completed', 'viva-com-smart-for-woocommerce' ),
    1001                     'processing' => __( 'Processing', 'viva-com-smart-for-woocommerce' ),
    1002                 ),
    1003             ),
    1004         );
    1005 
    1006         if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, '6.5.0', '>' ) ) {
    1007             $settings['enable_preauthorizations'] = array(
    1008                 'title'       => __( 'Preauthorized Payments', 'viva-com-smart-for-woocommerce' ),
    1009                 'type'        => 'checkbox',
    1010                 'label'       => __( 'Enable Preauthorized Payments', 'viva-com-smart-for-woocommerce' ),
    1011                 'description' => 'By enabling this you will create order in preauthorized status',
    1012                 'default'     => 'no',
    1013             );
    1014         }
     987            'source_code'               => array(
     988                'title'       => __( 'Live Source Code List', 'viva-com-smart-for-woocommerce' ),
     989                'type'        => 'select',
     990                'description' => __( 'Provides a list with all source codes that are set in your Viva.com banking app.', 'viva-com-smart-for-woocommerce' ),
     991                'default'     => '',
     992                'options'     => array(),
     993            ),
     994            'demo_source_code'          => array(
     995                'title'       => __( 'Demo Source Code List', 'viva-com-smart-for-woocommerce' ),
     996                'type'        => 'select',
     997                'description' => __( 'Provides a list with all source codes that are set in your Viva.com banking app.', 'viva-com-smart-for-woocommerce' ),
     998                'default'     => '',
     999                'options'     => array(),
     1000            ),
     1001            'logo_enabled'              => array(
     1002                'title'   => __( 'Show logo on checkout page', 'viva-com-smart-for-woocommerce' ),
     1003                'type'    => 'checkbox',
     1004                'label'   => __( 'Enable Viva.com logo on checkout page (default = yes).', 'viva-com-smart-for-woocommerce' ),
     1005                'default' => 'yes',
     1006            ),
     1007            'order_status'              => array(
     1008                'title'       => __( 'Order status after successful payment.', 'viva-com-smart-for-woocommerce' ),
     1009                'description' => __( 'Your WooCommerce will be updated to this status after successful payment on Viva.com (default = completed).', 'viva-com-smart-for-woocommerce' ),
     1010                'default'     => 'completed',
     1011                'type'        => 'select',
     1012                'options'     => array(
     1013                    'completed'  => __( 'Completed', 'viva-com-smart-for-woocommerce' ),
     1014                    'processing' => __( 'Processing', 'viva-com-smart-for-woocommerce' ),
     1015                ),
     1016            ),
     1017        );
     1018
     1019        if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, '6.5.0', '>' ) ) {
     1020            $settings['enable_preauthorizations'] = array(
     1021                'title'       => __( 'Preauthorized Payments', 'viva-com-smart-for-woocommerce' ),
     1022                'type'        => 'checkbox',
     1023                'label'       => __( 'Enable Preauthorized Payments', 'viva-com-smart-for-woocommerce' ),
     1024                'description' => 'By enabling this you will create order in preauthorized status',
     1025                'default'     => 'no',
     1026            );
     1027        }
    10151028
    10161029        /**
     
    10741087
    10751088        $split_instal_vivacom = explode( ',', $installments_pattern );
    1076         $c                       = count( $split_instal_vivacom );
     1089        $c                    = count( $split_instal_vivacom );
    10771090        $instal_vivacom_max   = array();
    1078         for ( $i = 0; $i < $c; $i ++ ) {
     1091        for ( $i = 0; $i < $c; $i++ ) {
    10791092            list( $instal_amount, $instal_term ) = explode( ':', $split_instal_vivacom[ $i ] );
    10801093            $instal_amount                       = (int) number_format( $instal_amount, 2, '', '' );
  • viva-com-smart-for-woocommerce/trunk/includes/class-wc-vivacom-smart-subscriptions.php

    r3245677 r3266406  
    4545    public function viva_payments_subscription_payment_method_to_display( $title ) {
    4646
    47         global $wpdb;
     47        global $wpdb;
    4848        if ( ! isset( $_SERVER['REQUEST_URI'] ) ) {
    4949            return $title;
     
    7474        }
    7575
    76         $token_id = $wpdb->get_var( $wpdb->prepare(
    77             "SELECT token_id FROM {$wpdb->prefix}viva_com_smart_wc_checkout_recurring WHERE recurring_id = %s ORDER BY date_add LIMIT 1",
    78             $subscription->get_id()
    79         )
    80         );
     76        $token_id = $wpdb->get_var(
     77            $wpdb->prepare(
     78                "SELECT token_id FROM {$wpdb->prefix}viva_com_smart_wc_checkout_recurring WHERE recurring_id = %s ORDER BY date_add LIMIT 1",
     79                $subscription->get_id()
     80            )
     81        );
    8182
    8283        $token = WC_Payment_Tokens::get( $token_id );
     
    8687
    8788        return $title . ' - ' . $token->get_display_name();
    88 
    8989    }
    9090
     
    9898     */
    9999    public function add_subscription_payment_meta( $payment_meta, $subscription ) {
    100         global $wpdb;
    101 
    102         $token_data = $wpdb->get_row( $wpdb->prepare(
    103             "SELECT * FROM {$wpdb->prefix}viva_com_smart_wc_checkout_recurring WHERE recurring_id = %s ORDER BY date_add LIMIT 1",
    104             $subscription->get_id()
    105         ), ARRAY_A
    106         );
    107 
    108         $token = $wpdb->get_row( $wpdb->prepare(
    109             "SELECT token FROM {$wpdb->prefix}woocommerce_payment_tokens WHERE token_id = %s LIMIT 1",
    110             $token_data['token_id']        ), ARRAY_A
    111         );
    112 
    113         $token_id = $token_data['token_id'];
     100        global $wpdb;
     101
     102        $token_data = $wpdb->get_row(
     103            $wpdb->prepare(
     104                "SELECT * FROM {$wpdb->prefix}viva_com_smart_wc_checkout_recurring WHERE recurring_id = %s ORDER BY date_add LIMIT 1",
     105                $subscription->get_id()
     106            ),
     107            ARRAY_A
     108        );
     109
     110        $token = $wpdb->get_row(
     111            $wpdb->prepare(
     112                "SELECT token FROM {$wpdb->prefix}woocommerce_payment_tokens WHERE token_id = %s LIMIT 1",
     113                $token_data['token_id']
     114            ),
     115            ARRAY_A
     116        );
     117
     118        $token_id = $token_data['token_id'];
    114119
    115120        // disabled option to not allow admin to change the tokens from subscription edit admin page.
     
    122127                    'disabled' => true,
    123128                ),
    124                 WC_Vivacom_Smart_Helpers::TOKEN => array(
     129                WC_Vivacom_Smart_Helpers::TOKEN    => array(
    125130                    'value'    => $token['token'],
    126131                    'label'    => __( 'Viva.com Smart Card Token', 'viva-com-smart-for-woocommerce' ),
     
    130135        );
    131136        return $payment_meta;
    132 
    133137    }
    134138
     
    159163                || $token_object->get_token() !== $payment_meta['post_meta'][ WC_Vivacom_Smart_Helpers::TOKEN ]['value']
    160164                ) {
    161                     throw new Exception( __( 'You are not allowed to change the Card Token.', 'viva-com-smart-for-woocommerce' ) );
     165                    throw new Exception( esc_html__( 'You are not allowed to change the Card Token.', 'viva-com-smart-for-woocommerce' ) );
    162166                }
    163167            }
     
    199203     */
    200204    public function process_subscription_payment( $order_id, $amount ) {
    201         global $wpdb;
     205        global $wpdb;
    202206
    203207        $order = wc_get_order( $order_id );
     
    211215            foreach ( $related_subscriptions as $subscription ) {
    212216                $subscription  = wcs_get_subscription( $subscription );
    213                 $token_id = $wpdb->get_var( $wpdb->prepare(
    214                     "SELECT token_id FROM {$wpdb->prefix}viva_com_smart_wc_checkout_recurring WHERE recurring_id = %s ORDER BY date_add LIMIT 1",
    215                     $subscription->get_id()
    216                 )
    217                 );
     217                $token_id      = $wpdb->get_var(
     218                    $wpdb->prepare(
     219                        "SELECT token_id FROM {$wpdb->prefix}viva_com_smart_wc_checkout_recurring WHERE recurring_id = %s ORDER BY date_add LIMIT 1",
     220                        $subscription->get_id()
     221                    )
     222                );
    218223                $payment_token = WC_Payment_Tokens::get( $token_id );
    219224            }
     
    255260
    256261                if ( $transaction_response->isSuccessful() && ! empty( $transaction_response->getBody() ) ) {
    257                     $transaction = array (
    258                         'id'     => $transaction_response->getBody()->transactionId,
    259                         'typeId' => 5 // id for chrgetoken
    260                     );
    261                     $note = __( 'Payment method used for automatic renewal: ', 'viva-com-smart-for-woocommerce' );
    262                     $note .= $payment_token->get_display_name();
     262                    $transaction = array(
     263                        'id'     => $transaction_response->getBody()->transactionId,
     264                        'typeId' => 5, // id for chrgetoken.
     265                    );
     266                    $note        = __( 'Payment method used for automatic renewal: ', 'viva-com-smart-for-woocommerce' );
     267                    $note       .= $payment_token->get_display_name();
    263268
    264269                    WC_Vivacom_Smart_Helpers::complete_order( $order_id, $transaction, $note, false );
  • viva-com-smart-for-woocommerce/trunk/includes/class-wc-vivacom-smart.php

    r3245677 r3266406  
    113113             * @since 1.0.0
    114114             */
    115             $this->icon = apply_filters( 'viva_com_smart_wc_icon', '' . $plugin_dir . 'assets/vivacom.png' );
     115            $this->icon = apply_filters( 'viva_com_smart_wc_icon', '' . $plugin_dir . 'assets/vivacom.png' );
    116116        }
    117117
     
    169169        $this->order_status       = $this->get_option( 'order_status' );
    170170
    171         set_transient( 'viva_com_smart_wc_admin_notice', true, 0 );
     171        set_transient( 'viva_com_smart_wc_admin_notice', true, 0 );
    172172
    173173        add_action( 'woocommerce_receipt_vivacom_smart', array( $this, 'receipt_page' ) );
     
    186186        add_action( 'woocommerce_settings_start', array( $this, 'admin_settings_start' ) );
    187187
    188         //Add custom Order actions
    189         add_filter('woocommerce_order_actions', array( $this, 'woocommerce_vivacom_smart_custom_actions' ) );
    190         add_action('woocommerce_order_action_wc_viva_smart_capture', array( $this, 'woocommerce_vivacom_smart_capture' ) );
    191         add_action('woocommerce_order_action_wc_viva_smart_void', array( $this, 'woocommerce_vivacom_smart_void' ) );
    192 
    193     }
    194 
    195     /**
    196      * Custom Order Actions
    197      */
    198     public function woocommerce_vivacom_smart_custom_actions( $actions ) {
    199         $actions['wc_viva_smart_capture'] = __( 'Capture Viva.com Payment', 'viva-com-smart-for-woocommerce' );
    200         $actions['wc_viva_smart_void'] = __( 'Void Viva.com Payment', 'viva-com-smart-for-woocommerce' );
    201 
    202         return $actions;
    203     }
    204 
    205     /**
    206      * Capture Payment
    207      */
    208     public function woocommerce_vivacom_smart_capture( $order ) {
    209         $environment           = 'yes' === $this->test_mode ? 'demo' : 'live';
    210         $bearer_authentication = WC_Vivacom_Smart_Helpers::get_bearer_authentication( $environment );
    211         $amount = (int) number_format( $order->get_total(), 2, '', '' );
    212 
    213         if ( $bearer_authentication->hasValidToken() ) {
    214             $result = WC_Vivacom_Smart_Helpers::process_capture( $bearer_authentication, $order, $amount );
    215             if ( is_wp_error( $result ) ) {
    216                 $order->add_order_note( sprintf( __( 'Capture prauthorized payment failed: %s', 'viva-com-smart-for-woocommerce' ), $result->get_error_message() ) );
    217             } else {
    218                 $order->add_order_note( sprintf( __( 'Capture prauthorized payment successfull: Tranaction Id: %s', 'viva-com-smart-for-woocommerce' ), $result['transaction_id'] ) );
    219                 $order->update_status( 'completed' );
    220             }
    221             $order->save();
    222         } else {
    223             return new WP_Error( 'error', sprintf( __( 'Viva.com: Your %s credentials are NOT valid. Please check your credentials!', 'viva-com-smart-for-woocommerce' ), $environment ) );
    224         }
    225     }
    226 
    227     /**
    228      * Void Payment
    229      */
    230     public function woocommerce_vivacom_smart_void( $order ) {
    231         $environment           = 'yes' === $this->test_mode ? 'demo' : 'live';
    232         $source                = 'yes' === $this->test_mode ? $this->demo_source_code : $this->source_code;
    233         $bearer_authentication = WC_Vivacom_Smart_Helpers::get_bearer_authentication( $environment );
    234         $amount = (int) number_format( $order->get_total(), 2, '', '' );
    235 
    236         if ( $bearer_authentication->hasValidToken() ) {
    237             $result = WC_Vivacom_Smart_Helpers::process_void( $bearer_authentication, $source, $order, $amount );
    238             if ( is_wp_error( $result ) ) {
    239                 $order->add_order_note( sprintf( __( 'Cancel of prauthorized payment failed: %s', 'viva-com-smart-for-woocommerce' ), $result->get_error_message() ) );
    240             } else {
    241                 $order->add_order_note( sprintf( __( 'Cancel of prauthorized payment successfull: Tranaction Id: %s', 'viva-com-smart-for-woocommerce' ), $result['transaction_id'] ) );
    242                 $order->update_status( 'cancelled' );
    243             }
    244             $order->save();
    245         } else {
    246             return new WP_Error( 'error', sprintf( __( 'Viva.com: Your %s credentials are NOT valid. Please check your credentials!', 'viva-com-smart-for-woocommerce' ), $environment ) );
    247         }
    248     }
     188        // Add custom Order actions.
     189        add_filter( 'woocommerce_order_actions', array( $this, 'woocommerce_vivacom_smart_custom_actions' ) );
     190        add_action( 'woocommerce_order_action_wc_viva_smart_capture', array( $this, 'woocommerce_vivacom_smart_capture' ) );
     191        add_action( 'woocommerce_order_action_wc_viva_smart_void', array( $this, 'woocommerce_vivacom_smart_void' ) );
     192    }
     193
     194    /**
     195     * Adds custom actions for Viva.com Smart payments in WooCommerce.
     196     *
     197     * @param array $actions An array of existing WooCommerce payment actions.
     198     *
     199     * @return array Modified array including Viva.com Smart custom actions.
     200     */
     201    public function woocommerce_vivacom_smart_custom_actions( $actions ) {
     202        $actions['wc_viva_smart_capture'] = __( 'Capture Viva.com Payment', 'viva-com-smart-for-woocommerce' );
     203        $actions['wc_viva_smart_void']    = __( 'Void Viva.com Payment', 'viva-com-smart-for-woocommerce' );
     204
     205        return $actions;
     206    }
     207
     208    /**
     209     * Captures a Viva.com Smart payment for a WooCommerce order.
     210     *
     211     * @param object|WC_Order $order order.
     212     *
     213     * @return  bool|WP_Error
     214     */
     215    public function woocommerce_vivacom_smart_capture( $order ) {
     216        $environment           = 'yes' === $this->test_mode ? 'demo' : 'live';
     217        $bearer_authentication = WC_Vivacom_Smart_Helpers::get_bearer_authentication( $environment );
     218        $amount                = (int) number_format( $order->get_total(), 2, '', '' );
     219
     220        if ( $bearer_authentication->hasValidToken() ) {
     221            $result = WC_Vivacom_Smart_Helpers::process_capture( $bearer_authentication, $order, $amount );
     222            if ( is_wp_error( $result ) ) {
     223                $order->add_order_note( sprintf( __( 'Capture prauthorized payment failed: %s', 'viva-com-smart-for-woocommerce' ), $result->get_error_message() ) );
     224            } else {
     225                $order->add_order_note( sprintf( __( 'Capture prauthorized payment successfull: Tranaction Id: %s', 'viva-com-smart-for-woocommerce' ), $result['transaction_id'] ) );
     226                $order->update_status( 'completed' );
     227            }
     228            $order->save();
     229        } else {
     230            return new WP_Error( 'error', sprintf( __( 'Viva.com: Your %s credentials are NOT valid. Please check your credentials!', 'viva-com-smart-for-woocommerce' ), $environment ) );
     231        }
     232    }
     233
     234    /**
     235     * Void a Viva.com Smart payment for a WooCommerce order.
     236     *
     237     * @param object|WC_Order $order order.
     238     *
     239     * @return bool|WP_Error
     240     */
     241    public function woocommerce_vivacom_smart_void( $order ) {
     242        $environment           = 'yes' === $this->test_mode ? 'demo' : 'live';
     243        $source                = 'yes' === $this->test_mode ? $this->demo_source_code : $this->source_code;
     244        $bearer_authentication = WC_Vivacom_Smart_Helpers::get_bearer_authentication( $environment );
     245        $amount                = (int) number_format( $order->get_total(), 2, '', '' );
     246
     247        if ( $bearer_authentication->hasValidToken() ) {
     248            $result = WC_Vivacom_Smart_Helpers::process_void( $bearer_authentication, $source, $order, $amount );
     249            if ( is_wp_error( $result ) ) {
     250                $order->add_order_note( sprintf( __( 'Cancel of prauthorized payment failed: %s', 'viva-com-smart-for-woocommerce' ), $result->get_error_message() ) );
     251            } else {
     252                $order->add_order_note( sprintf( __( 'Cancel of prauthorized payment successfull: Tranaction Id: %s', 'viva-com-smart-for-woocommerce' ), $result['transaction_id'] ) );
     253                $order->update_status( 'cancelled' );
     254            }
     255            $order->save();
     256        } else {
     257            return new WP_Error( 'error', sprintf( __( 'Viva.com: Your %s credentials are NOT valid. Please check your credentials!', 'viva-com-smart-for-woocommerce' ), $environment ) );
     258        }
     259    }
    249260
    250261    /**
     
    265276     * @param string $order_id order_id.
    266277     *
    267      * @return string
     278     * @return void
    268279     */
    269280    public function generate_form( string $order_id ) {
    270281
    271         global $wpdb;
     282        global $wpdb;
    272283        $order      = wc_get_order( $order_id );
    273284        $order_data = WC_Vivacom_Smart_Helpers::get_order_data( $order );
     285
     286        $brand_color = str_replace( '#', '', $this->get_option( 'brand_color' ) );
    274287
    275288        $allow_recurring = false;
     
    298311            ),
    299312            'payment'    => array(
    300                 'maxInstallments'     => $max_installments,
    301                 'allowRecurring'      => $allow_recurring,
    302                 'preauth'             => 'yes' === $this->get_option('enable_preauthorizations'),
     313                'maxInstallments' => $max_installments,
     314                'allowRecurring'  => $allow_recurring,
     315                'preauth'         => 'yes' === $this->get_option( 'enable_preauthorizations' ),
    303316            ),
    304317            'messages'   => array(
    305318                'customer' => $order_data['messages']['customer_message'],
    306319                'merchant' => $order_data['messages']['merchant_message'],
    307                 'tags'     => array( 'woocommerce-smart' ),
     320                'tags'     => array( 'woocommerce-smart' ),
    308321            ),
    309322        );
     
    312325
    313326        // IF ORDER CODE AND ORDER PENDING EXISTS ELSE CREATE OTHER.
    314         $vivacom_order = WC_Vivacom_Smart_Helpers::get_smart_checkout_order( $order->get_id() );
     327        $vivacom_order = WC_Vivacom_Smart_Helpers::get_smart_checkout_order( $order->get_id() );
    315328
    316329        $action_adr = '';
    317330        if ( ! empty( $vivacom_order['vivacom_order_code'] ) ) {
    318331            $order_code = $vivacom_order['vivacom_order_code'];
    319             $action_adr = Application::getSmartCheckoutUrl( $order_code, $environment );
     332            $action_adr = Application::getSmartCheckoutUrl(
     333                [
     334                    'ref'   => $order_code,
     335                    'color' => $brand_color,
     336                ],
     337                $environment
     338            );
    320339        } else {
    321340            $bearer_authentication = WC_Vivacom_Smart_Helpers::get_bearer_authentication( $environment );
     
    325344
    326345                if ( $order_response->isSuccessful() ) {
    327                     $order_code = $order_response->getBody()->orderCode;
    328                     $insert_data = array(
    329                         'woocommerce_order_id' => $order->get_id(),
    330                         'vivacom_order_code' => $order_code,
    331                         'client_id' => 'yes' === $this->test_mode ? $this->demo_client_id : $this->client_id,//get client id
    332                         'currency' => $order_data['currency'],
    333                         'amount' => $order->get_total(),
    334                         'is_demo' => 'yes' === $this->test_mode
    335                     );
    336                     $wpdb->insert(
    337                         $wpdb->prefix . 'viva_com_smart_wc_checkout_orders',
    338                         $insert_data
    339                     );
    340                     $action_adr = Application::getSmartCheckoutUrl( $order_code, $environment );
    341                 } else {
     346                    $order_code  = $order_response->getBody()->orderCode;
     347                    $insert_data = array(
     348                        'woocommerce_order_id' => $order->get_id(),
     349                        'vivacom_order_code'   => $order_code,
     350                        'client_id'            => 'yes' === $this->test_mode ? $this->demo_client_id : $this->client_id, // get client id.
     351                        'currency'             => $order_data['currency'],
     352                        'amount'               => $order->get_total(),
     353                        'is_demo'              => 'yes' === $this->test_mode,
     354                    );
     355                    $wpdb->insert(
     356                        $wpdb->prefix . 'viva_com_smart_wc_checkout_orders',
     357                        $insert_data
     358                    );
     359                    $action_adr = Application::getSmartCheckoutUrl(
     360                        [
     361                            'ref'   => $order_code,
     362                            'color' => $brand_color,
     363                        ],
     364                        $environment
     365                    );              } else {
    342366                    $error = __( 'There was a problem processing your payment. Please try again or use an other payment method.', 'viva-com-smart-for-woocommerce' );
    343367                    wc_add_notice( $error, 'error' );
     
    351375        }
    352376
    353         $order_ref = $order_code ?? '';
     377        $order_ref = $order_code ?? '';
    354378
    355379        wc_enqueue_js(
     
    377401
    378402        echo '<form action="' . esc_url( $action_adr ) . '" method="GET" id="vivacom_smart_payment_form">' . "\n" .
    379             '<input type="hidden" name="Ref" value="' . esc_attr($order_ref) . '" />' . "\n" .
    380             '<input type="submit" class="button alt" id="submit_vivacom_smart_payment_form" value="' . esc_html__( 'Pay Now', 'viva-com-smart-for-woocommerce' ) . '" /> <a class="button cancel" href="' . esc_url( $order->get_cancel_order_url() ) . '">' . esc_html__( 'Cancel', 'viva-com-smart-for-woocommerce' ) . '</a>' . "\n" .
     403            '<input type="hidden" name="Ref" value="' . esc_attr( $order_ref ) . '" />' . "\n" .
     404            '<input type="hidden" name="color" value="' . esc_attr( $brand_color ) . '" />' . "\n" .
     405            '<input type="submit" class="button alt" id="submit_vivacom_smart_payment_form" value="' . esc_html__( 'Pay Now', 'viva-com-smart-for-woocommerce' ) . '" /> <a class="button cancel" href="' . esc_url( $order->get_cancel_order_url() ) . '">' . esc_html__( 'Cancel', 'viva-com-smart-for-woocommerce' ) . '</a>' . "\n" .
    381406            '</form>';
    382407    }
     
    397422            'redirect' => esc_url_raw( add_query_arg( 'order-pay', $order->get_id(), add_query_arg( 'key', $order->get_order_key(), wc_get_page_permalink( 'checkout' ) ) ) ),
    398423        );
    399 
    400424    }
    401425
     
    605629        }
    606630
     631        wp_enqueue_style('wp-color-picker');
     632        wp_enqueue_script('wp-color-picker');
     633
    607634        $suffix = defined( 'SCRIPT_DEBUG' ) && true === SCRIPT_DEBUG ? '' : '.min';
    608635
     
    650677                $this->update_option( 'demo_source_code', '' );
    651678            }
    652         } else {
    653             if ( $this->client_id !== $old_client_id || $this->client_secret !== $old_client_secret ) {
     679        } elseif ( $this->client_id !== $old_client_id || $this->client_secret !== $old_client_secret ) {
    654680                $this->update_option( 'source_code', '' );
    655             }
    656681        }
    657682
     
    699724     */
    700725    private function admin_sources() {
    701         // GET DEMO AND LIVE CLIENT TOKEN THEN GET SOURCES.
    702         $demo_bearer_authentication = WC_Vivacom_Smart_Helpers::get_bearer_authentication( 'demo' );
    703         $live_bearer_authentication = WC_Vivacom_Smart_Helpers::get_bearer_authentication( 'live' );
    704 
    705         $this->demo_source_list = $demo_bearer_authentication->hasValidToken() ? WC_Vivacom_Smart_Helpers::get_sources( $demo_bearer_authentication ) : new SourceList();
    706         $this->live_source_list = $live_bearer_authentication->hasValidToken() ? WC_Vivacom_Smart_Helpers::get_sources( $live_bearer_authentication ) : new SourceList();
    707 
    708         if ( count( $this->demo_source_list ) > 0 ) {
    709             foreach ( $this->demo_source_list as $key => $value ) {
    710                 $this->form_fields['demo_source_code']['options'][ $value->getCode() ] =
     726        $environment                          = 'yes' == $this->test_mode ? 'demo' : 'live';
     727        $bearer_authentication                = WC_Vivacom_Smart_Helpers::get_bearer_authentication( $environment );
     728        $this->{"{$environment}_source_list"} = $bearer_authentication->hasValidToken() ? WC_Vivacom_Smart_Helpers::get_sources( $bearer_authentication ) : new SourceList();
     729
     730        if ( count( $this->{"{$environment}_source_list"} ) > 0 ) {
     731            $source_code_key = 'demo' == $environment ? "{$environment}_source_code" : 'source_code';
     732
     733            foreach ( $this->{"{$environment}_source_list"} as $key => $value ) {
     734                $this->form_fields[ $source_code_key ]['options'][ $value->getCode() ] =
    711735                    $value->getCode() . ' - ' . $value->getname() . ' - ' . $value->getDomain();
    712736            }
    713737        }
    714 
    715         if ( count( $this->live_source_list ) > 0 ) {
    716             foreach ( $this->live_source_list as $key => $value ) {
    717                 $this->form_fields['source_code']['options'][ $value->getCode() ] =
    718                     $value->getCode() . ' - ' . $value->getName() . ' - ' . $value->getDomain();
    719             }
    720         }
    721 
    722738    }
    723739
     
    775791        return true;
    776792    }
    777 
    778793}
  • viva-com-smart-for-woocommerce/trunk/package.json

    r3245677 r3266406  
    22  "name": "viva-com-smart-for-woocommerce",
    33  "title": "Viva Wallet Smart Checkout",
    4   "version": "1.0.0",
     4  "version": "1.0.1",
    55  "repository": {
    66    "type": "git",
  • viva-com-smart-for-woocommerce/trunk/readme.md

    r3266254 r3266406  
    66**Tested up to:** 6.7
    77**Requires PHP:** 7.4
    8 **Stable tag:** 1.0.0
     8**Stable tag:** 1.0.1
    99**License:** GPLv2
    1010**License URI:** [https://www.gnu.org/licenses/old-licenses/lgpl-2.0.html](https://www.gnu.org/licenses/old-licenses/lgpl-2.0.html)
     
    5555## Changelog
    5656
     57## 1.0.1 - 2025-03-27
     58- Add brand color picker option for smart checkout
     59- Fix double request to viva during configuration
    5760### 1.0.0 - 2025-02-05
    5861- Initial release. 
  • viva-com-smart-for-woocommerce/trunk/uninstall.php

    r3245677 r3266406  
    11<?php
     2/**
     3 * Uninstall script for the Viva.com Smart for WooCommerce plugin.
     4 *
     5 * This script is executed when the plugin is uninstalled via WordPress.
     6 * It ensures that all relevant settings and options related to the plugin
     7 * are removed from the database.
     8 *
     9 * @package VivaCom_Smart_For_WooCommerce
     10 */
     11
    212if ( ! defined( 'ABSPATH' ) ) {
    313    exit;
  • viva-com-smart-for-woocommerce/trunk/vendor/autoload.php

    r3245677 r3266406  
    2323require_once __DIR__ . '/composer/autoload_real.php';
    2424
    25 return ComposerAutoloaderInit166d4c7020968fe2a6155eb8d0d0c1d8::getLoader();
     25return ComposerAutoloaderInit8799c650735842202cde6eabb2f6ea6d::getLoader();
  • viva-com-smart-for-woocommerce/trunk/vendor/composer/ClassLoader.php

    r3245677 r3266406  
    4343class ClassLoader
    4444{
    45     /** @var ?string */
     45    /** @var \Closure(string):void */
     46    private static $includeFile;
     47
     48    /** @var string|null */
    4649    private $vendorDir;
    4750
    4851    // PSR-4
    4952    /**
    50      * @var array[]
    51      * @psalm-var array<string, array<string, int>>
     53     * @var array<string, array<string, int>>
    5254     */
    5355    private $prefixLengthsPsr4 = array();
    5456    /**
    55      * @var array[]
    56      * @psalm-var array<string, array<int, string>>
     57     * @var array<string, list<string>>
    5758     */
    5859    private $prefixDirsPsr4 = array();
    5960    /**
    60      * @var array[]
    61      * @psalm-var array<string, string>
     61     * @var list<string>
    6262     */
    6363    private $fallbackDirsPsr4 = array();
     
    6565    // PSR-0
    6666    /**
    67      * @var array[]
    68      * @psalm-var array<string, array<string, string[]>>
     67     * List of PSR-0 prefixes
     68     *
     69     * Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2')))
     70     *
     71     * @var array<string, array<string, list<string>>>
    6972     */
    7073    private $prefixesPsr0 = array();
    7174    /**
    72      * @var array[]
    73      * @psalm-var array<string, string>
     75     * @var list<string>
    7476     */
    7577    private $fallbackDirsPsr0 = array();
     
    7981
    8082    /**
    81      * @var string[]
    82      * @psalm-var array<string, string>
     83     * @var array<string, string>
    8384     */
    8485    private $classMap = array();
     
    8889
    8990    /**
    90      * @var bool[]
    91      * @psalm-var array<string, bool>
     91     * @var array<string, bool>
    9292     */
    9393    private $missingClasses = array();
    9494
    95     /** @var ?string */
     95    /** @var string|null */
    9696    private $apcuPrefix;
    9797
    9898    /**
    99      * @var self[]
     99     * @var array<string, self>
    100100     */
    101101    private static $registeredLoaders = array();
    102102
    103103    /**
    104      * @param ?string $vendorDir
     104     * @param string|null $vendorDir
    105105     */
    106106    public function __construct($vendorDir = null)
    107107    {
    108108        $this->vendorDir = $vendorDir;
    109     }
    110 
    111     /**
    112      * @return string[]
     109        self::initializeIncludeClosure();
     110    }
     111
     112    /**
     113     * @return array<string, list<string>>
    113114     */
    114115    public function getPrefixes()
     
    122123
    123124    /**
    124      * @return array[]
    125      * @psalm-return array<string, array<int, string>>
     125     * @return array<string, list<string>>
    126126     */
    127127    public function getPrefixesPsr4()
     
    131131
    132132    /**
    133      * @return array[]
    134      * @psalm-return array<string, string>
     133     * @return list<string>
    135134     */
    136135    public function getFallbackDirs()
     
    140139
    141140    /**
    142      * @return array[]
    143      * @psalm-return array<string, string>
     141     * @return list<string>
    144142     */
    145143    public function getFallbackDirsPsr4()
     
    149147
    150148    /**
    151      * @return string[] Array of classname => path
    152      * @psalm-return array<string, string>
     149     * @return array<string, string> Array of classname => path
    153150     */
    154151    public function getClassMap()
     
    158155
    159156    /**
    160      * @param string[] $classMap Class to filename map
    161      * @psalm-param array<string, string> $classMap
     157     * @param array<string, string> $classMap Class to filename map
    162158     *
    163159     * @return void
     
    176172     * appending or prepending to the ones previously set for this prefix.
    177173     *
    178      * @param string          $prefix  The prefix
    179      * @param string[]|string $paths   The PSR-0 root directories
    180      * @param bool            $prepend Whether to prepend the directories
     174     * @param string              $prefix  The prefix
     175     * @param list<string>|string $paths   The PSR-0 root directories
     176     * @param bool                $prepend Whether to prepend the directories
    181177     *
    182178     * @return void
     
    184180    public function add($prefix, $paths, $prepend = false)
    185181    {
     182        $paths = (array) $paths;
    186183        if (!$prefix) {
    187184            if ($prepend) {
    188185                $this->fallbackDirsPsr0 = array_merge(
    189                     (array) $paths,
     186                    $paths,
    190187                    $this->fallbackDirsPsr0
    191188                );
     
    193190                $this->fallbackDirsPsr0 = array_merge(
    194191                    $this->fallbackDirsPsr0,
    195                     (array) $paths
     192                    $paths
    196193                );
    197194            }
     
    202199        $first = $prefix[0];
    203200        if (!isset($this->prefixesPsr0[$first][$prefix])) {
    204             $this->prefixesPsr0[$first][$prefix] = (array) $paths;
     201            $this->prefixesPsr0[$first][$prefix] = $paths;
    205202
    206203            return;
     
    208205        if ($prepend) {
    209206            $this->prefixesPsr0[$first][$prefix] = array_merge(
    210                 (array) $paths,
     207                $paths,
    211208                $this->prefixesPsr0[$first][$prefix]
    212209            );
     
    214211            $this->prefixesPsr0[$first][$prefix] = array_merge(
    215212                $this->prefixesPsr0[$first][$prefix],
    216                 (array) $paths
     213                $paths
    217214            );
    218215        }
     
    223220     * appending or prepending to the ones previously set for this namespace.
    224221     *
    225      * @param string          $prefix  The prefix/namespace, with trailing '\\'
    226      * @param string[]|string $paths   The PSR-4 base directories
    227      * @param bool            $prepend Whether to prepend the directories
     222     * @param string              $prefix  The prefix/namespace, with trailing '\\'
     223     * @param list<string>|string $paths   The PSR-4 base directories
     224     * @param bool                $prepend Whether to prepend the directories
    228225     *
    229226     * @throws \InvalidArgumentException
     
    233230    public function addPsr4($prefix, $paths, $prepend = false)
    234231    {
     232        $paths = (array) $paths;
    235233        if (!$prefix) {
    236234            // Register directories for the root namespace.
    237235            if ($prepend) {
    238236                $this->fallbackDirsPsr4 = array_merge(
    239                     (array) $paths,
     237                    $paths,
    240238                    $this->fallbackDirsPsr4
    241239                );
     
    243241                $this->fallbackDirsPsr4 = array_merge(
    244242                    $this->fallbackDirsPsr4,
    245                     (array) $paths
     243                    $paths
    246244                );
    247245            }
     
    253251            }
    254252            $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
    255             $this->prefixDirsPsr4[$prefix] = (array) $paths;
     253            $this->prefixDirsPsr4[$prefix] = $paths;
    256254        } elseif ($prepend) {
    257255            // Prepend directories for an already registered namespace.
    258256            $this->prefixDirsPsr4[$prefix] = array_merge(
    259                 (array) $paths,
     257                $paths,
    260258                $this->prefixDirsPsr4[$prefix]
    261259            );
     
    264262            $this->prefixDirsPsr4[$prefix] = array_merge(
    265263                $this->prefixDirsPsr4[$prefix],
    266                 (array) $paths
     264                $paths
    267265            );
    268266        }
     
    273271     * replacing any others previously set for this prefix.
    274272     *
    275      * @param string          $prefix The prefix
    276      * @param string[]|string $paths  The PSR-0 base directories
     273     * @param string              $prefix The prefix
     274     * @param list<string>|string $paths  The PSR-0 base directories
    277275     *
    278276     * @return void
     
    291289     * replacing any others previously set for this namespace.
    292290     *
    293      * @param string          $prefix The prefix/namespace, with trailing '\\'
    294      * @param string[]|string $paths  The PSR-4 base directories
     291     * @param string              $prefix The prefix/namespace, with trailing '\\'
     292     * @param list<string>|string $paths  The PSR-4 base directories
    295293     *
    296294     * @throws \InvalidArgumentException
     
    426424    {
    427425        if ($file = $this->findFile($class)) {
    428             includeFile($file);
     426            $includeFile = self::$includeFile;
     427            $includeFile($file);
    429428
    430429            return true;
     
    477476
    478477    /**
    479      * Returns the currently registered loaders indexed by their corresponding vendor directories.
    480      *
    481      * @return self[]
     478     * Returns the currently registered loaders keyed by their corresponding vendor directories.
     479     *
     480     * @return array<string, self>
    482481     */
    483482    public static function getRegisteredLoaders()
     
    556555        return false;
    557556    }
     557
     558    /**
     559     * @return void
     560     */
     561    private static function initializeIncludeClosure()
     562    {
     563        if (self::$includeFile !== null) {
     564            return;
     565        }
     566
     567        /**
     568         * Scope isolated include.
     569         *
     570         * Prevents access to $this/self from included files.
     571         *
     572         * @param  string $file
     573         * @return void
     574         */
     575        self::$includeFile = \Closure::bind(static function($file) {
     576            include $file;
     577        }, null, null);
     578    }
    558579}
    559 
    560 /**
    561  * Scope isolated include.
    562  *
    563  * Prevents access to $this/self from included files.
    564  *
    565  * @param  string $file
    566  * @return void
    567  * @private
    568  */
    569 function includeFile($file)
    570 {
    571     include $file;
    572 }
  • viva-com-smart-for-woocommerce/trunk/vendor/composer/InstalledVersions.php

    r3245677 r3266406  
    3434
    3535    /**
     36     * @var bool
     37     */
     38    private static $installedIsLocalDir;
     39
     40    /**
    3641     * @var bool|null
    3742     */
     
    99104        foreach (self::getInstalled() as $installed) {
    100105            if (isset($installed['versions'][$packageName])) {
    101                 return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']);
     106                return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false;
    102107            }
    103108        }
     
    120125    public static function satisfies(VersionParser $parser, $packageName, $constraint)
    121126    {
    122         $constraint = $parser->parseConstraints($constraint);
     127        $constraint = $parser->parseConstraints((string) $constraint);
    123128        $provided = $parser->parseConstraints(self::getVersionRanges($packageName));
    124129
     
    310315        self::$installed = $data;
    311316        self::$installedByVendor = array();
     317
     318        // when using reload, we disable the duplicate protection to ensure that self::$installed data is
     319        // always returned, but we cannot know whether it comes from the installed.php in __DIR__ or not,
     320        // so we have to assume it does not, and that may result in duplicate data being returned when listing
     321        // all installed packages for example
     322        self::$installedIsLocalDir = false;
    312323    }
    313324
     
    323334
    324335        $installed = array();
     336        $copiedLocalDir = false;
    325337
    326338        if (self::$canGetVendors) {
     339            $selfDir = strtr(__DIR__, '\\', '/');
    327340            foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
     341                $vendorDir = strtr($vendorDir, '\\', '/');
    328342                if (isset(self::$installedByVendor[$vendorDir])) {
    329343                    $installed[] = self::$installedByVendor[$vendorDir];
    330344                } elseif (is_file($vendorDir.'/composer/installed.php')) {
    331                     $installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php';
    332                     if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
    333                         self::$installed = $installed[count($installed) - 1];
     345                    /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
     346                    $required = require $vendorDir.'/composer/installed.php';
     347                    self::$installedByVendor[$vendorDir] = $required;
     348                    $installed[] = $required;
     349                    if (self::$installed === null && $vendorDir.'/composer' === $selfDir) {
     350                        self::$installed = $required;
     351                        self::$installedIsLocalDir = true;
    334352                    }
     353                }
     354                if (self::$installedIsLocalDir && $vendorDir.'/composer' === $selfDir) {
     355                    $copiedLocalDir = true;
    335356                }
    336357            }
     
    341362            // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
    342363            if (substr(__DIR__, -8, 1) !== 'C') {
    343                 self::$installed = require __DIR__ . '/installed.php';
     364                /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
     365                $required = require __DIR__ . '/installed.php';
     366                self::$installed = $required;
    344367            } else {
    345368                self::$installed = array();
    346369            }
    347370        }
    348         $installed[] = self::$installed;
     371
     372        if (self::$installed !== array() && !$copiedLocalDir) {
     373            $installed[] = self::$installed;
     374        }
    349375
    350376        return $installed;
  • viva-com-smart-for-woocommerce/trunk/vendor/composer/autoload_real.php

    r3245677 r3266406  
    33// autoload_real.php @generated by Composer
    44
    5 class ComposerAutoloaderInit166d4c7020968fe2a6155eb8d0d0c1d8
     5class ComposerAutoloaderInit8799c650735842202cde6eabb2f6ea6d
    66{
    77    private static $loader;
     
    2525        require __DIR__ . '/platform_check.php';
    2626
    27         spl_autoload_register(array('ComposerAutoloaderInit166d4c7020968fe2a6155eb8d0d0c1d8', 'loadClassLoader'), true, true);
     27        spl_autoload_register(array('ComposerAutoloaderInit8799c650735842202cde6eabb2f6ea6d', 'loadClassLoader'), true, true);
    2828        self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
    29         spl_autoload_unregister(array('ComposerAutoloaderInit166d4c7020968fe2a6155eb8d0d0c1d8', 'loadClassLoader'));
     29        spl_autoload_unregister(array('ComposerAutoloaderInit8799c650735842202cde6eabb2f6ea6d', 'loadClassLoader'));
    3030
    3131        require __DIR__ . '/autoload_static.php';
    32         call_user_func(\Composer\Autoload\ComposerStaticInit166d4c7020968fe2a6155eb8d0d0c1d8::getInitializer($loader));
     32        call_user_func(\Composer\Autoload\ComposerStaticInit8799c650735842202cde6eabb2f6ea6d::getInitializer($loader));
    3333
    3434        $loader->register(true);
  • viva-com-smart-for-woocommerce/trunk/vendor/composer/autoload_static.php

    r3245677 r3266406  
    55namespace Composer\Autoload;
    66
    7 class ComposerStaticInit166d4c7020968fe2a6155eb8d0d0c1d8
     7class ComposerStaticInit8799c650735842202cde6eabb2f6ea6d
    88{
    99    public static $prefixLengthsPsr4 = array (
     
    164164    {
    165165        return \Closure::bind(function () use ($loader) {
    166             $loader->prefixLengthsPsr4 = ComposerStaticInit166d4c7020968fe2a6155eb8d0d0c1d8::$prefixLengthsPsr4;
    167             $loader->prefixDirsPsr4 = ComposerStaticInit166d4c7020968fe2a6155eb8d0d0c1d8::$prefixDirsPsr4;
    168             $loader->classMap = ComposerStaticInit166d4c7020968fe2a6155eb8d0d0c1d8::$classMap;
     166            $loader->prefixLengthsPsr4 = ComposerStaticInit8799c650735842202cde6eabb2f6ea6d::$prefixLengthsPsr4;
     167            $loader->prefixDirsPsr4 = ComposerStaticInit8799c650735842202cde6eabb2f6ea6d::$prefixDirsPsr4;
     168            $loader->classMap = ComposerStaticInit8799c650735842202cde6eabb2f6ea6d::$classMap;
    169169
    170170        }, null, ClassLoader::class);
  • viva-com-smart-for-woocommerce/trunk/vendor/composer/installed.json

    r3245677 r3266406  
    3535            },
    3636            "time": "2024-11-26T13:24:01+00:00",
    37             "default-branch": true,
    3837            "type": "composer-plugin",
    3938            "extra": {
  • viva-com-smart-for-woocommerce/trunk/vendor/composer/installed.php

    r3245677 r3266406  
    22    'root' => array(
    33        'name' => 'vivacom/woocommerce',
    4         'pretty_version' => 'dev-main',
    5         'version' => 'dev-main',
    6         'reference' => '024233744bd894eaeb9235d94cb5697a456d9a8a',
     4        'pretty_version' => 'dev-59ed2595eb0bf8bd239d3355027895ba6562b1c1',
     5        'version' => 'dev-59ed2595eb0bf8bd239d3355027895ba6562b1c1',
     6        'reference' => '59ed2595eb0bf8bd239d3355027895ba6562b1c1',
    77        'type' => 'wordpress-plugin',
    88        'install_path' => __DIR__ . '/../../',
     
    2323        ),
    2424        'vivacom/woocommerce' => array(
    25             'pretty_version' => 'dev-main',
    26             'version' => 'dev-main',
    27             'reference' => '024233744bd894eaeb9235d94cb5697a456d9a8a',
     25            'pretty_version' => 'dev-59ed2595eb0bf8bd239d3355027895ba6562b1c1',
     26            'version' => 'dev-59ed2595eb0bf8bd239d3355027895ba6562b1c1',
     27            'reference' => '59ed2595eb0bf8bd239d3355027895ba6562b1c1',
    2828            'type' => 'wordpress-plugin',
    2929            'install_path' => __DIR__ . '/../../',
  • viva-com-smart-for-woocommerce/trunk/vendor_prefixed/vivawallet/composer.json

    r3245677 r3266406  
    22    "name": "vivawallet\/vivawallet-php",
    33    "description": "Package to handle http requests to Viva Wallet APi for native checkout",
    4     "version": "2.2.2",
     4    "version": "2.2.3",
    55    "type": "library",
    66    "require": {
  • viva-com-smart-for-woocommerce/trunk/vendor_prefixed/vivawallet/lib/Application.php

    r3245677 r3266406  
    66{
    77    public const VIVAWALLET_ABBREVIATION = 'VW';
    8     public const SDK_VERSION = '2.2.2';
     8    public const SDK_VERSION = '2.2.3';
    99    public const SOURCE_NAME_FORMAT = 'Viva Wallet For %s - %s';
    1010    public const PARAM_CANCEL_ORDER = 'cancel';
     
    3737        }
    3838    }
    39     public static function getSmartCheckoutUrl(string $ref, string $environment) : string
     39    public static function getSmartCheckoutUrl(array $params, string $environment) : string
    4040    {
    41         return \implode([self::BASE_URLS[$environment]['default'], self::ENDPOINTS['smartCheckout'], '?', \http_build_query(['ref' => $ref])]);
     41        $baseUrl = self::BASE_URLS[$environment]['default'];
     42        $endpoint = self::ENDPOINTS['smartCheckout'];
     43        $filteredParams = \array_filter($params, function ($param) {
     44            return !empty($param);
     45        });
     46        return \implode([$baseUrl, $endpoint, '?', \http_build_query($filteredParams)]);
    4247    }
    4348}
  • viva-com-smart-for-woocommerce/trunk/wc-vivacom-smart.php

    r3245677 r3266406  
    66 *  Author: Viva.com
    77 *  Author URI: https://www.viva.com/
    8  *  Version: 1.0.0
     8 *  Version: 1.0.1
    99 *  Requires Plugins: woocommerce
    1010 *  Requires at least: 6.5
     
    1515 *  License: GPLv2
    1616 *  Domain Path: /languages
     17 *
     18 * @package VivaComSmartForWooCommerce
    1719 */
    1820
    1921if ( ! defined( 'ABSPATH' ) ) {
    20     exit();
     22    exit();
    2123}
    2224/**
    2325 * Instantiate Singleton class
     26 *
    2427 */
    2528if ( ! class_exists( 'WC_Vivacom_Smart' ) ) {
    26 
    27     class  WC_Vivacom_Smart {
    28 
    29         /**
    30          * Instance
    31          *
    32          * @var WC_Vivacom_Smart The reference the *Singleton* instance of this class
    33          */
    34         private static $instance;
    35 
    36         /**
    37          * Get instance
    38          *
    39          * @return WC_Vivacom_Smart The *Singleton* instance.
    40          */
    41         public static function get_instance() : self {
    42             if ( null === self::$instance ) {
    43                 self::$instance = new self();
    44             }
    45             return self::$instance;
    46         }
    47 
    48         /**
    49          * Construct
    50          */
    51         private function __construct() {
    52             add_action( 'plugins_loaded', [$this, 'init']);
    53         }
    54 
    55         /**
    56          * Clone
    57          */
    58         private function __clone() {
    59         }
    60 
    61         /**
    62          * Wakeup
    63          */
    64         public function __wakeup() {
    65         }
    66 
    67         /**
    68          * Init
    69          */
    70         public function init() {
    71             try {
    72                 $this->define_constants();
    73                 $this->validate_setup();
    74                 $this->load_plugin_files();
    75                 $this->setup_options();
    76                 $this->add_hooks();
    77                 $this->add_filters();
    78                 $this->setup_locale();
    79             } catch (Exception $e) {
    80                 $errors = unserialize($e->getMessage());
    81                 add_action( 'admin_notices', function () use ($errors){
    82                     $this->print_notices($errors);
    83                 });
    84                 return;
    85             }
    86         }
    87 
    88         private function validate_setup() {
    89             $errors = [];
    90 
    91             // Woocommerce needs to be active
    92             if ( ! class_exists( 'WooCommerce' ) ) {
    93                 $errors[] = sprintf(
    94                     esc_html__(
    95                         'The Viva.com payment gateway requires WooCommerce. Download link %s here.',
    96                         'viva-com-smart-for-woocommerce'
    97                     ),
    98                     '<a href="https://woocommerce.com/" target="_blank">WooCommerce</a>' );
    99             }
    100 
    101             // WooCommerce needs to adhere to our minimum supported WC versions
    102             if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, WC_VIVA_COM_SMART_MIN_WOO_VERSION, '<' ) ) {
    103                 $errors[] = sprintf(
    104                     esc_html__(
    105                         'The Viva.com payment gateway requires WooCommerce. Download link %s here.',
    106                         'viva-com-smart-for-woocommerce'
    107                     ),
    108                     '<a href="https://woocommerce.com/" target="_blank">WooCommerce</a>' );
    109             }
    110             if ( !empty($errors) ) {
    111                 throw new \Exception(serialize($errors));
    112             }
    113         }
    114 
    115         private function define_constants() : void {
    116             define( 'WC_VIVA_COM_SMART_VERSION', '1.0.0' );
    117             define( 'WC_VIVA_COM_SMART_MIN_PHP_VERSION', '7.3.0' );
    118             define( 'WC_VIVA_COM_SMART_MIN_WOO_VERSION', '3.5.0' );
    119             define( 'WC_VIVA_COM_SMART_MAIN_FILE', __FILE__ );
    120             define( 'WC_VIVA_COM_SMART_PLUGIN_URL', untrailingslashit( plugins_url( basename( plugin_dir_path( __FILE__ ) ), basename( __FILE__ ) ) ) );
    121             define( 'WC_VIVA_COM_SMART_PLUGIN_PATH', untrailingslashit( plugin_dir_path( __FILE__ ) ) );
    122             define( 'WC_VIVA_PREFIXED_DIRECTORY', '/vendor_prefixed' );
    123             define( 'WC_VIVA_COM_SMART_DB_SCHEMA', '1.0');
    124         }
    125 
    126         private function load_plugin_files() : void {
    127             require_once WC_VIVA_COM_SMART_PLUGIN_PATH . '/vendor/autoload.php';
    128 
    129             if ( is_dir( WC_VIVA_COM_SMART_PLUGIN_PATH . WC_VIVA_PREFIXED_DIRECTORY ) ) {
    130                 require_once WC_VIVA_COM_SMART_PLUGIN_PATH . WC_VIVA_PREFIXED_DIRECTORY . '/guzzlehttp/guzzle/src/functions.php';
    131                 require_once WC_VIVA_COM_SMART_PLUGIN_PATH . WC_VIVA_PREFIXED_DIRECTORY . '/symfony/deprecation-contracts/function.php';
    132                 require_once WC_VIVA_COM_SMART_PLUGIN_PATH . WC_VIVA_PREFIXED_DIRECTORY . '/ralouphie/src/getallheaders.php';
    133             }
    134 
    135             require_once WC_VIVA_COM_SMART_PLUGIN_PATH . '/includes/class-wc-vivacom-smart-logger.php';
    136             require_once WC_VIVA_COM_SMART_PLUGIN_PATH . '/includes/class-wc-vivacom-smart-helpers.php';
    137             require_once WC_VIVA_COM_SMART_PLUGIN_PATH . '/includes/class-wc-vivacom-smart.php';
    138             require_once WC_VIVA_COM_SMART_PLUGIN_PATH . '/includes/class-wc-vivacom-smart-endpoints.php';
    139             require_once WC_VIVA_COM_SMART_PLUGIN_PATH . '/includes/class-wc-vivacom-smart-subscriptions.php';
    140         }
    141 
    142         private function setup_options() : void {
    143             $viva_settings = get_option( 'woocommerce_vivacom_smart_settings', [] );
    144             if ( empty( $viva_settings['version'] ) ) {
    145                 $this->update_version_in_db( $viva_settings, false );
    146             } elseif ( WC_VIVA_COM_SMART_VERSION !== $viva_settings['version'] ) {
    147                 $this->update_version_in_db( $viva_settings, true );
    148             }
    149         }
    150 
    151         /**
    152          * Update version in database
    153          *
    154          * @param array $viva_settings viva_settings.
    155          *
    156          * @param bool  $current current.
    157          *
    158          * @return void
    159          */
    160         public function update_version_in_db( $viva_settings, $current ) {
    161             global $wp_version;
    162             $active_plugins = get_option( 'active_plugins' );
    163 
    164             if ( $current ) {
    165                 $message = "Viva.com smart plugin version updated \nNew version: " . WC_VIVA_COM_SMART_VERSION . "\nOld version : " . $viva_settings['version'];
    166             } else {
    167                 $message = "Viva.com smart plugin version updated \nNew version: " . WC_VIVA_COM_SMART_VERSION;
    168             }
    169 
    170             $message .= "\nWordpress Version: " . $wp_version;
    171 
    172             // Check if get_plugins() function exists. This is required on the front end of the site.
    173             if ( ! function_exists( 'get_plugins' ) ) {
    174                 require_once ABSPATH . 'wp-admin/includes/plugin.php';
    175             }
    176 
    177             $all_plugins = get_plugins();
    178 
    179             $message .= "\n Other active plugins: ";
    180 
    181             foreach ( $active_plugins as $active_plugin ) {
    182                 $version  = ! empty( $all_plugins[ $active_plugin ]['Version'] ) ? $all_plugins[ $active_plugin ]['Version'] : 'Unknown Version';
    183                 $message .= "\n " . $all_plugins[ $active_plugin ]['Name'] . ' - Version: ' . $version;
    184             }
    185 
    186             WC_Vivacom_Smart_Logger::log( $message, true );
    187 
    188             $viva_settings['version'] = WC_VIVA_COM_SMART_VERSION;
    189             update_option( 'woocommerce_vivacom_smart_settings', $viva_settings );
    190 
    191         }
    192 
    193         private function add_hooks() : void {
    194             add_action( 'woocommerce_blocks_loaded', [ $this, 'woocommerce_vivacom_smart_woocommerce_blocks_support' ] );
    195             add_action( 'before_woocommerce_init', [ $this, 'woocommerce_vivacom_smart_before_woocommerce_init'] );
    196         }
    197 
    198         /**
    199          * Woocommerce blocks support
    200          */
    201         public function woocommerce_vivacom_smart_woocommerce_blocks_support() : void {
    202             if ( class_exists( 'Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType' ) ) {
    203                 require_once dirname( __FILE__ ) . '/includes/class-wc-vivacom-smart-blocks-support.php';
    204                 add_action(
    205                     'woocommerce_blocks_payment_method_type_registration',
    206                     function( Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
    207                         $payment_method_registry->register( new WC_Vivacom_Smart_Blocks_support );
    208                     }
    209                 );
    210             }
    211         }
    212 
    213         public function woocommerce_vivacom_smart_before_woocommerce_init () : void {
    214             if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
    215                 \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', __FILE__, true );
    216                 \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
    217             }
    218         }
    219 
    220         private function add_filters() : void {
    221             add_filter( 'woocommerce_payment_gateways', [ $this, 'add_gateways' ] );
    222             add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), [ $this, 'plugin_action_links' ] );
    223             add_filter( 'plugin_row_meta', [ $this, 'plugin_row_meta' ], 10, 2 );
    224         }
    225 
    226         /**
    227          * Add gateways
    228          *
    229          * @param array $gateways add vivacom gateways.
    230          *
    231          * @return array
    232          */
    233         public function add_gateways( $gateways ) {
    234             if ( class_exists( 'WC_Subscriptions_Order' ) && function_exists( 'wcs_create_renewal_order' ) ) {
    235                 $gateways[] = 'WC_Vivacom_Smart_Payment_Gateway_Subscriptions';
    236             } else {
    237                 $gateways[] = 'WC_Vivacom_Smart_Payment_Gateway';
    238             }
    239 
    240             return $gateways;
    241         }
    242 
    243         /**
    244          * Add plugin action links.
    245          *
    246          * @param array $links Links.
    247          *
    248          * @return array
    249          */
    250         public function plugin_action_links( $links ) {
    251             $plugin_links = array(
    252                 '<a href="admin.php?page=wc-settings&tab=checkout&section=vivacom_smart">' . esc_html__( 'Settings', 'viva-com-smart-for-woocommerce' ) . '</a>',
    253             );
    254             return array_merge( $plugin_links, $links );
    255         }
    256 
    257         /**
    258          * Add plugin row meta.
    259          *
    260          * @param mixed $links Plugin Row Meta.
    261          * @param mixed $file  Plugin Base file.
    262          *
    263          * @return array
    264          */
    265         public function plugin_row_meta( $links, $file ) {
    266             if ( plugin_basename( __FILE__ ) === $file ) {
    267                 $row_meta = array(
    268                     'docs'    => '<a href="' . esc_url( 'https://docs.woocommerce.com/document/viva-com-smart-for-woocommerce' ) . '" aria-label="' . esc_attr__( 'View Viva.com Smart Checkout plugin documentation', 'viva-com-smart-for-woocommerce' ) . '">' . esc_html__( 'Documentation', 'viva-com-smart-for-woocommerce' ) . '</a>',
    269                     'support' => '<a href="' . esc_url( 'mailto: [email protected]' ) . '" aria-label="' . esc_attr__( 'Get support from Viva.com Team', 'viva-com-smart-for-woocommerce' ) . '">' . esc_html__( 'Get support', 'viva-com-smart-for-woocommerce' ) . '</a>',
    270                 );
    271                 return array_merge( $links, $row_meta );
    272             }
    273             return (array) $links;
    274         }
    275 
    276         public function setup_locale() : void {
    277             add_filter( 'plugin_locale', [ $this, 'woocommerce_vivacom_smart_fix_locale' ], 99, 2 );
    278             load_plugin_textdomain( 'viva-com-smart-for-woocommerce', false, plugin_basename( dirname( __FILE__ ) ) . '/languages' );
    279         }
    280 
    281         /**
    282          * Vivacom_fix_locale
    283          *
    284          * @param string $locale locale.
    285          * @param string $domain domain.
    286          * @return string
    287          */
    288         public function woocommerce_vivacom_smart_fix_locale( $locale, $domain ) {
    289             if ( 'viva-com-smart-for-woocommerce' === $domain ) {
    290                 $locale = substr( $locale, 0, 2 );
    291             }
    292             return $locale;
    293         }
    294 
    295         public function print_notices(array $notices) {
    296             foreach ($notices as $notice) {
    297                 echo '<div class="notice notice-error"><p><strong>' . esc_html( $notice ) . '</strong></p></div>';
    298             }
    299         }
    300 
    301         private function create_orders_table() : void {
    302             $charset_collate = $this->wpdb()->get_charset_collate();
    303             $db_prefix =$this->wpdb()->prefix;
    304 
    305             $sql = "CREATE TABLE IF NOT EXISTS {$db_prefix}viva_com_smart_wc_checkout_orders
     29    /**
     30     * WC_Vivacom_Smart Class
     31     */
     32    class WC_Vivacom_Smart {
     33
     34        /**
     35         * Instance
     36         *
     37         * @var WC_Vivacom_Smart The reference the *Singleton* instance of this class
     38         */
     39        private static $instance;
     40
     41        /**
     42         * Get instance
     43         *
     44         * @return WC_Vivacom_Smart The *Singleton* instance.
     45         */
     46        public static function get_instance(): self {
     47            if ( null === self::$instance ) {
     48                self::$instance = new self();
     49            }
     50            return self::$instance;
     51        }
     52
     53        /**
     54         * Construct
     55         */
     56        private function __construct() {
     57            add_action( 'plugins_loaded', array( $this, 'init' ) );
     58        }
     59
     60        /**
     61         * Clone
     62         */
     63        private function __clone() {
     64        }
     65
     66        /**
     67         * Wakeup
     68         */
     69        public function __wakeup() {
     70        }
     71
     72        /**
     73         * Init
     74         */
     75        public function init() {
     76            try {
     77                $this->define_constants();
     78                $this->validate_setup();
     79                $this->load_plugin_files();
     80                $this->setup_options();
     81                $this->add_hooks();
     82                $this->add_filters();
     83                $this->setup_locale();
     84            } catch ( Exception $e ) {
     85                $errors = unserialize( $e->getMessage() );
     86                add_action(
     87                    'admin_notices',
     88                    function () use ( $errors ) {
     89                        $this->print_notices( $errors );
     90                    }
     91                );
     92                return;
     93            }
     94        }
     95
     96        /**
     97         * Validates the WooCommerce and plugin setup requirements.
     98         *
     99         * @throws \Exception If WooCommerce is not installed, active, or does not meet the minimum version requirement.
     100         */
     101        private function validate_setup() {
     102            $errors = array();
     103
     104            // Woocommerce needs to be active.
     105            if ( ! class_exists( 'WooCommerce' ) ) {
     106                $errors[] = sprintf(
     107                    esc_html__(
     108                        'The Viva.com payment gateway requires WooCommerce. Download link %s here.',
     109                        'viva-com-smart-for-woocommerce'
     110                    ),
     111                    '<a href="https://woocommerce.com/" target="_blank">WooCommerce</a>'
     112                );
     113            }
     114
     115            // WooCommerce needs to adhere to our minimum supported WC versions.
     116            if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, WC_VIVA_COM_SMART_MIN_WOO_VERSION, '<' ) ) {
     117                $errors[] = sprintf(
     118                    esc_html__(
     119                        'The Viva.com payment gateway requires WooCommerce. Download link %s here.',
     120                        'viva-com-smart-for-woocommerce'
     121                    ),
     122                    '<a href="https://woocommerce.com/" target="_blank">WooCommerce</a>'
     123                );
     124            }
     125            if ( ! empty( $errors ) ) {
     126                throw new \Exception( serialize( $errors ) );
     127            }
     128        }
     129
     130        /**
     131         * Defines essential constants for the Viva.com Smart payment gateway.
     132         *
     133         * @return void
     134         */
     135        private function define_constants(): void {
     136            define( 'WC_VIVA_COM_SMART_VERSION', '1.0.1' );
     137            define( 'WC_VIVA_COM_SMART_MIN_PHP_VERSION', '7.3.0' );
     138            define( 'WC_VIVA_COM_SMART_MIN_WOO_VERSION', '3.5.0' );
     139            define( 'WC_VIVA_COM_SMART_MAIN_FILE', __FILE__ );
     140            define( 'WC_VIVA_COM_SMART_PLUGIN_URL', untrailingslashit( plugins_url( basename( plugin_dir_path( __FILE__ ) ), basename( __FILE__ ) ) ) );
     141            define( 'WC_VIVA_COM_SMART_PLUGIN_PATH', untrailingslashit( plugin_dir_path( __FILE__ ) ) );
     142            define( 'WC_VIVA_PREFIXED_DIRECTORY', '/vendor_prefixed' );
     143            define( 'WC_VIVA_COM_SMART_DB_SCHEMA', '1.0' );
     144        }
     145
     146        /**
     147         * Loads the necessary plugin files for Viva.com Smart payment gateway.
     148         *
     149         * @return void
     150         */
     151        private function load_plugin_files(): void {
     152            require_once WC_VIVA_COM_SMART_PLUGIN_PATH . '/vendor/autoload.php';
     153
     154            if ( is_dir( WC_VIVA_COM_SMART_PLUGIN_PATH . WC_VIVA_PREFIXED_DIRECTORY ) ) {
     155                require_once WC_VIVA_COM_SMART_PLUGIN_PATH . WC_VIVA_PREFIXED_DIRECTORY . '/guzzlehttp/guzzle/src/functions.php';
     156                require_once WC_VIVA_COM_SMART_PLUGIN_PATH . WC_VIVA_PREFIXED_DIRECTORY . '/symfony/deprecation-contracts/function.php';
     157                require_once WC_VIVA_COM_SMART_PLUGIN_PATH . WC_VIVA_PREFIXED_DIRECTORY . '/ralouphie/src/getallheaders.php';
     158            }
     159
     160            require_once WC_VIVA_COM_SMART_PLUGIN_PATH . '/includes/class-wc-vivacom-smart-logger.php';
     161            require_once WC_VIVA_COM_SMART_PLUGIN_PATH . '/includes/class-wc-vivacom-smart-helpers.php';
     162            require_once WC_VIVA_COM_SMART_PLUGIN_PATH . '/includes/class-wc-vivacom-smart.php';
     163            require_once WC_VIVA_COM_SMART_PLUGIN_PATH . '/includes/class-wc-vivacom-smart-endpoints.php';
     164            require_once WC_VIVA_COM_SMART_PLUGIN_PATH . '/includes/class-wc-vivacom-smart-subscriptions.php';
     165        }
     166
     167        /**
     168         * Sets up the plugin options and handles version updates.
     169         *
     170         * @return void
     171         */
     172        private function setup_options(): void {
     173            $viva_settings = get_option( 'woocommerce_vivacom_smart_settings', array() );
     174            if ( empty( $viva_settings['version'] ) ) {
     175                $this->update_version_in_db( $viva_settings, false );
     176            } elseif ( WC_VIVA_COM_SMART_VERSION !== $viva_settings['version'] ) {
     177                $this->update_version_in_db( $viva_settings, true );
     178            }
     179        }
     180
     181        /**
     182         * Update version in database
     183         *
     184         * @param array $viva_settings viva_settings.
     185         *
     186         * @param bool  $current current.
     187         *
     188         * @return void
     189         */
     190        public function update_version_in_db( $viva_settings, $current ) {
     191            global $wp_version;
     192            $active_plugins = get_option( 'active_plugins' );
     193
     194            if ( $current ) {
     195                $message = "Viva.com smart plugin version updated \nNew version: " . WC_VIVA_COM_SMART_VERSION . "\nOld version : " . $viva_settings['version'];
     196            } else {
     197                $message = "Viva.com smart plugin version updated \nNew version: " . WC_VIVA_COM_SMART_VERSION;
     198            }
     199
     200            $message .= "\nWordpress Version: " . $wp_version;
     201
     202            // Check if get_plugins() function exists. This is required on the front end of the site.
     203            if ( ! function_exists( 'get_plugins' ) ) {
     204                require_once ABSPATH . 'wp-admin/includes/plugin.php';
     205            }
     206
     207            $all_plugins = get_plugins();
     208
     209            $message .= "\n Other active plugins: ";
     210
     211            foreach ( $active_plugins as $active_plugin ) {
     212                $version  = ! empty( $all_plugins[ $active_plugin ]['Version'] ) ? $all_plugins[ $active_plugin ]['Version'] : 'Unknown Version';
     213                $message .= "\n " . $all_plugins[ $active_plugin ]['Name'] . ' - Version: ' . $version;
     214            }
     215
     216            WC_Vivacom_Smart_Logger::log( $message, true );
     217
     218            $viva_settings['version'] = WC_VIVA_COM_SMART_VERSION;
     219            update_option( 'woocommerce_vivacom_smart_settings', $viva_settings );
     220        }
     221
     222        /**
     223         * Adds custom action hooks for the plugin.
     224         *
     225         * @return void
     226         */
     227        private function add_hooks(): void {
     228            add_action( 'woocommerce_blocks_loaded', array( $this, 'woocommerce_vivacom_smart_woocommerce_blocks_support' ) );
     229            add_action( 'before_woocommerce_init', array( $this, 'woocommerce_vivacom_smart_before_woocommerce_init' ) );
     230        }
     231
     232        /**
     233         * Woocommerce blocks support
     234         */
     235        public function woocommerce_vivacom_smart_woocommerce_blocks_support(): void {
     236            if ( class_exists( 'Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType' ) ) {
     237                require_once __DIR__ . '/includes/class-wc-vivacom-smart-blocks-support.php';
     238                add_action(
     239                    'woocommerce_blocks_payment_method_type_registration',
     240                    function ( Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
     241                        $payment_method_registry->register( new WC_Vivacom_Smart_Blocks_support() );
     242                    }
     243                );
     244            }
     245        }
     246
     247        /**
     248         * Declares compatibility with specific WooCommerce features before WooCommerce initialization.
     249         *
     250         * @return void
     251         */
     252        public function woocommerce_vivacom_smart_before_woocommerce_init(): void {
     253            if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
     254                \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', __FILE__, true );
     255                \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
     256            }
     257        }
     258
     259        /**
     260         * Adds custom filters for the Viva.com Smart payment gateway plugin.
     261         *
     262         * @return void
     263         */
     264        private function add_filters(): void {
     265            add_filter( 'woocommerce_payment_gateways', array( $this, 'add_gateways' ) );
     266            add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'plugin_action_links' ) );
     267            add_filter( 'plugin_row_meta', array( $this, 'plugin_row_meta' ), 10, 2 );
     268        }
     269
     270        /**
     271         * Add gateways
     272         *
     273         * @param array $gateways add vivacom gateways.
     274         *
     275         * @return array
     276         */
     277        public function add_gateways( $gateways ) {
     278            if ( class_exists( 'WC_Subscriptions_Order' ) && function_exists( 'wcs_create_renewal_order' ) ) {
     279                $gateways[] = 'WC_Vivacom_Smart_Payment_Gateway_Subscriptions';
     280            } else {
     281                $gateways[] = 'WC_Vivacom_Smart_Payment_Gateway';
     282            }
     283
     284            return $gateways;
     285        }
     286
     287        /**
     288         * Add plugin action links.
     289         *
     290         * @param array $links Links.
     291         *
     292         * @return array
     293         */
     294        public function plugin_action_links( $links ) {
     295            $plugin_links = array(
     296                '<a href="admin.php?page=wc-settings&tab=checkout&section=vivacom_smart">' . esc_html__( 'Settings', 'viva-com-smart-for-woocommerce' ) . '</a>',
     297            );
     298            return array_merge( $plugin_links, $links );
     299        }
     300
     301        /**
     302         * Add plugin row meta.
     303         *
     304         * @param mixed $links Plugin Row Meta.
     305         * @param mixed $file  Plugin Base file.
     306         *
     307         * @return array
     308         */
     309        public function plugin_row_meta( $links, $file ) {
     310            if ( plugin_basename( __FILE__ ) === $file ) {
     311                $row_meta = array(
     312                    'docs'    => '<a href="' . esc_url( 'https://docs.woocommerce.com/document/viva-com-smart-for-woocommerce' ) . '" aria-label="' . esc_attr__( 'View Viva.com Smart Checkout plugin documentation', 'viva-com-smart-for-woocommerce' ) . '">' . esc_html__( 'Documentation', 'viva-com-smart-for-woocommerce' ) . '</a>',
     313                    'support' => '<a href="' . esc_url( 'mailto: [email protected]' ) . '" aria-label="' . esc_attr__( 'Get support from Viva.com Team', 'viva-com-smart-for-woocommerce' ) . '">' . esc_html__( 'Get support', 'viva-com-smart-for-woocommerce' ) . '</a>',
     314                );
     315                return array_merge( $links, $row_meta );
     316            }
     317            return (array) $links;
     318        }
     319
     320        /**
     321         * Sets up the plugin's locale for translation.
     322         *
     323         * @return void
     324         */
     325        public function setup_locale(): void {
     326            add_filter( 'plugin_locale', array( $this, 'woocommerce_vivacom_smart_fix_locale' ), 99, 2 );
     327            load_plugin_textdomain( 'viva-com-smart-for-woocommerce', false, plugin_basename( __DIR__ ) . '/languages' );
     328        }
     329
     330        /**
     331         * Vivacom_fix_locale
     332         *
     333         * @param string $locale locale.
     334         * @param string $domain domain.
     335         * @return string
     336         */
     337        public function woocommerce_vivacom_smart_fix_locale( $locale, $domain ) {
     338            if ( 'viva-com-smart-for-woocommerce' === $domain ) {
     339                $locale = substr( $locale, 0, 2 );
     340            }
     341            return $locale;
     342        }
     343
     344        /**
     345         * Prints error notices for the plugin.
     346         *
     347         * @param array $notices An array of notice messages to be displayed.
     348         *
     349         * @return void
     350         */
     351        public function print_notices( array $notices ) {
     352            foreach ( $notices as $notice ) {
     353                echo '<div class="notice notice-error"><p><strong>' . esc_html( $notice ) . '</strong></p></div>';
     354            }
     355        }
     356
     357        /**
     358         * Creates the Viva orders table in the WordPress database.
     359         *
     360         * @return void
     361         */
     362        private function create_orders_table(): void {
     363            $charset_collate = $this->wpdb()->get_charset_collate();
     364            $db_prefix       = $this->wpdb()->prefix;
     365
     366            $sql = "CREATE TABLE IF NOT EXISTS {$db_prefix}viva_com_smart_wc_checkout_orders
    306367                    (
    307368                        id int(11) NOT NULL AUTO_INCREMENT,
     
    318379                        INDEX(vivacom_order_code)
    319380                    ) $charset_collate;";
    320             dbDelta( $sql );
    321         }
    322 
    323         private function create_transaction_types_table() : void {
    324             $charset_collate = $this->wpdb()->get_charset_collate();
    325             $db_prefix =$this->wpdb()->prefix;
    326 
    327             $sql = "CREATE TABLE IF NOT EXISTS {$db_prefix}viva_com_smart_wc_checkout_transaction_types
     381            dbDelta( $sql );
     382        }
     383
     384        /**
     385         * Creates the Viva transaction types table in the WordPress database.
     386         *
     387         * @return void
     388         */
     389        private function create_transaction_types_table(): void {
     390            $charset_collate = $this->wpdb()->get_charset_collate();
     391            $db_prefix       = $this->wpdb()->prefix;
     392
     393            $sql = "CREATE TABLE IF NOT EXISTS {$db_prefix}viva_com_smart_wc_checkout_transaction_types
    328394                    (
    329395                        id int(11) NOT NULL AUTO_INCREMENT,
     
    332398                        UNIQUE(name)
    333399                    ) $charset_collate;";
    334             dbDelta( $sql );
    335         }
    336 
    337         private function create_transactions_table() : void {
    338             $charset_collate = $this->wpdb()->get_charset_collate();
    339             $db_prefix =$this->wpdb()->prefix;
    340 
    341             $sql = "CREATE TABLE IF NOT EXISTS {$db_prefix}viva_com_smart_wc_checkout_transactions
     400            dbDelta( $sql );
     401        }
     402
     403        /**
     404         * Creates the Viva transactions table in the WordPress database.
     405         *
     406         * @return void
     407         */
     408        private function create_transactions_table(): void {
     409            $charset_collate = $this->wpdb()->get_charset_collate();
     410            $db_prefix       = $this->wpdb()->prefix;
     411
     412            $sql = "CREATE TABLE IF NOT EXISTS {$db_prefix}viva_com_smart_wc_checkout_transactions
    342413                    (
    343414                        id int(11) NOT NULL AUTO_INCREMENT,
     
    354425                        FOREIGN KEY(transaction_type_id) REFERENCES {$db_prefix}viva_com_smart_wc_checkout_transaction_types (id)
    355426                    ) $charset_collate;";
    356             dbDelta( $sql );
    357         }
    358 
    359         private function create_recurring_table() : void {
    360             $charset_collate = $this->wpdb()->get_charset_collate();
    361             $db_prefix =$this->wpdb()->prefix;
    362 
    363             $sql = "CREATE TABLE IF NOT EXISTS {$db_prefix}viva_com_smart_wc_checkout_recurring
     427            dbDelta( $sql );
     428        }
     429
     430        /**
     431         * Creates the Viva recurring table in the WordPress database.
     432         *
     433         * @return void
     434         */
     435        private function create_recurring_table(): void {
     436            $charset_collate = $this->wpdb()->get_charset_collate();
     437            $db_prefix       = $this->wpdb()->prefix;
     438
     439            $sql = "CREATE TABLE IF NOT EXISTS {$db_prefix}viva_com_smart_wc_checkout_recurring
    364440                    (
    365441                        id int(11) NOT NULL AUTO_INCREMENT,
     
    375451                        FOREIGN KEY(transaction_id) REFERENCES {$db_prefix}viva_com_smart_wc_checkout_transactions (id)
    376452                    ) $charset_collate;";
    377             dbDelta( $sql );
    378         }
    379 
    380         private function insert_transaction_types() : void {
    381             $db_prefix =$this->wpdb()->prefix;
    382 
    383             $transaction_types = $this->wpdb()->get_results(
    384                 "SELECT name FROM {$db_prefix}viva_com_smart_wc_checkout_transaction_types",
    385                 ARRAY_A
    386             );
    387             $missing_types = array_diff(['payment', 'refund', 'preauthorization', 'capture', 'void'], array_column($transaction_types, 'name'));
    388             $insert_types = array_map(function ($value) {
    389                 return ['name' => $value];
    390             }, $missing_types);
    391             foreach ($insert_types as $insert_type) {
    392                 $result = $this->wpdb()->insert(
    393                     "{$db_prefix}viva_com_smart_wc_checkout_transaction_types",
    394                     $insert_type
    395                 );
    396                 if ( false === $result ) {
    397                     WC_Vivacom_Smart_Logger::log( 'Failed to insert transaction types to db.' );
    398                 }
    399             }
    400         }
    401 
    402         private function wpdb() {
    403             global $wpdb;
    404             return $wpdb;
    405         }
    406 
    407         public function activate() : void {
    408             require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    409             $this->create_orders_table();
    410             $this->create_transaction_types_table();
    411             $this->create_transactions_table();
    412             $this->create_recurring_table();
    413             $this->insert_transaction_types();
    414         }
    415 
    416         public function deactivate() : void {
    417 
    418         }
    419 
    420         public static function uninstall() : void {
    421 //            global $wpdb;
    422 //            // Delete all options
    423 //            delete_option('woocommerce_vivacom_smart_settings');
    424 //            delete_transient('viva_com_smart_wc_admin_notice');
    425 //
    426 //            // Delete all tables
    427 //            $db_prefix = $wpdb->prefix;
    428 //            $wpdb->query("DROP TABLE IF EXISTS {$db_prefix}viva_com_smart_wc_checkout_transaction_types");
    429 //            $wpdb->query("DROP TABLE IF EXISTS {$db_prefix}viva_com_smart_wc_checkout_recurring");
    430 //            $wpdb->query("DROP TABLE IF EXISTS {$db_prefix}viva_com_smart_wc_checkout_transactions");
    431 //            $wpdb->query("DROP TABLE IF EXISTS {$db_prefix}viva_com_smart_wc_checkout_orders");
    432         }
    433     }
     453            dbDelta( $sql );
     454        }
     455
     456        /**
     457         * Inserts missing transaction types into the database.
     458         *
     459         * @return void
     460         */
     461        private function insert_transaction_types(): void {
     462            $db_prefix = $this->wpdb()->prefix;
     463
     464            $transaction_types = $this->wpdb()->get_results(
     465                "SELECT name FROM {$db_prefix}viva_com_smart_wc_checkout_transaction_types",
     466                ARRAY_A
     467            );
     468            $missing_types     = array_diff( array( 'payment', 'refund', 'preauthorization', 'capture', 'void' ), array_column( $transaction_types, 'name' ) );
     469            $insert_types      = array_map(
     470                function ( $value ) {
     471                    return array( 'name' => $value );
     472                },
     473                $missing_types
     474            );
     475            foreach ( $insert_types as $insert_type ) {
     476                $result = $this->wpdb()->insert(
     477                    "{$db_prefix}viva_com_smart_wc_checkout_transaction_types",
     478                    $insert_type
     479                );
     480                if ( false === $result ) {
     481                    WC_Vivacom_Smart_Logger::log( 'Failed to insert transaction types to db.' );
     482                }
     483            }
     484        }
     485
     486        /**
     487         * Retrieves the global WordPress database object.
     488         *
     489         * @return wpdb The global WordPress database object.
     490         */
     491        private function wpdb() {
     492            global $wpdb;
     493            return $wpdb;
     494        }
     495
     496        /**
     497         * Activates the plugin and sets up the necessary database tables.
     498         *
     499         * @return void
     500         */
     501        public function activate(): void {
     502            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
     503            $this->create_orders_table();
     504            $this->create_transaction_types_table();
     505            $this->create_transactions_table();
     506            $this->create_recurring_table();
     507            $this->insert_transaction_types();
     508        }
     509
     510        /**
     511         * Deactivates the plugin.
     512         *
     513         * @return void
     514         */
     515        public function deactivate(): void {
     516        }
     517
     518        /**
     519         * Unistall the plugin.
     520         *
     521         * @return void
     522         */
     523        public static function uninstall(): void {
     524            // global $wpdb;
     525            // Delete all options
     526            // delete_option('woocommerce_vivacom_smart_settings');
     527            // delete_transient('viva_com_smart_wc_admin_notice');
     528            //
     529            // Delete all tables
     530            // $db_prefix = $wpdb->prefix;
     531            // $wpdb->query("DROP TABLE IF EXISTS {$db_prefix}viva_com_smart_wc_checkout_transaction_types");
     532            // $wpdb->query("DROP TABLE IF EXISTS {$db_prefix}viva_com_smart_wc_checkout_recurring");
     533            // $wpdb->query("DROP TABLE IF EXISTS {$db_prefix}viva_com_smart_wc_checkout_transactions");
     534            // $wpdb->query("DROP TABLE IF EXISTS {$db_prefix}viva_com_smart_wc_checkout_orders");
     535        }
     536    }
    434537}
    435538
    436539$vivacom = WC_Vivacom_Smart::get_instance();
    437540
    438 register_activation_hook(__FILE__, [ $vivacom, 'activate' ]);
    439 
    440 register_deactivation_hook(__FILE__, [ $vivacom, 'deactivate' ]);
    441 
    442 //register_uninstall_hook(__FILE__, [ WC_Vivacom_Smart::class, 'uninstall' ]);
     541register_activation_hook( __FILE__, array( $vivacom, 'activate' ) );
     542
     543register_deactivation_hook( __FILE__, array( $vivacom, 'deactivate' ) );
     544
     545// register_uninstall_hook(__FILE__, [ WC_Vivacom_Smart::class, 'uninstall' ]);
Note: See TracChangeset for help on using the changeset viewer.