<?php

/**
 * Plugin Name: SIBS Payment Gateway for WooCommerce
 * Description: WooCommerce with SIBS Payment Gateway
 * Author:      SIBS
 * Author URI:  http://www.sibs.pt/
 * Version:     2.5.0
 * Requires at least: 6.1
 * Requires PHP:      7.4
 * WC requires at least: 7.5
 * WC tested up to: 7.7.0
 * WC Version: 6.7.0.
 */
if (! defined('ABSPATH')) {
    exit; // Prevent direct access
}
require_once plugin_dir_path(__FILE__) . '/vendor/autoload.php';

define('SIBS_VERSION', '2.5.0');
define('SIBS_PLUGIN_FILE', __FILE__);
define('SIBS_PLUGIN_DIR', plugins_url('/', __FILE__));
define('DATE_FORMAT', "Y-m-d\TH:i:s.vP");

use Sibs2\sibsConstants;
use Sibs2\sibsException;
use Sibs2\sibsFunctions;
use Sibs2\sibsGeneralFunctions;
use Sibs2\sibsGeneralModels;
use Sibs2\sibsPaymentGateway;

require_once __DIR__ . '/sibs-install.php';
require_once __DIR__ . '/sibs-additional.php';

register_activation_hook(__FILE__, 'sibs_activation_process');
register_deactivation_hook(__FILE__, 'sibs_deactivation_process');
register_uninstall_hook(__FILE__, 'sibs_uninstallation_process');

add_action('plugins_loaded', 'sibs_stg_init_payment_gateway', 0);
add_action('wp_ajax_registered_payment', 'sibs_get_ajax_registered_payment'); // https://developer.wordpress.org/reference/hooks/wp_ajax_action/
add_action('admin_enqueue_scripts', 'sibs_my_function_to_add_the_js_file'); // https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/
add_action('admin_head', 'sibs_hide_wc_refund_button'); // https://wp-kama.ru/hook/admin_head
add_action('woocommerce_order_item_add_action_buttons', 'sibs_add_admin_buttons');  // https://wp-kama.com/plugin/woocommerce/hook/woocommerce_order_item_add_action_buttons
add_action('wp_ajax_add_button_to_order_admin', 'sibs_ajax_add_button_to_order_admin'); // https://developer.wordpress.org/reference/hooks/wp_ajax_action/
add_action('woocommerce_cancel_unpaid_orders', 'sibs_cancel_onhold_orders'); // https://wp-kama.com/plugin/woocommerce/hook/woocommerce_cancel_unpaid_order
add_action('woocommerce_review_order_before_submit', 'sibs_woocommerce_review_order_before_submit_action'); // https://wp-kama.com/plugin/woocommerce/hook/woocommerce_review_order_before_submit
add_action('woocommerce_checkout_process', 'sibs_woocommerce_checkout_process_action', 10, 1); // https://wp-kama.com/plugin/woocommerce/hook/woocommerce_checkout_process
add_action('wp_footer', 'sibs_footer'); // https://developer.wordpress.org/reference/hooks/wp_footer/

add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'sibs_add_configuration_links'); // https://developer.wordpress.org/reference/hooks/plugin_action_links_plugin_file/
add_filter('woocommerce_thankyou_order_received_text', 'sibs_wpb_thankyou', 10, 2);  // https://wp-kama.com/plugin/woocommerce/hook/woocommerce_thankyou_order_received_text
add_filter('woocommerce_locate_template', 'sibs_override_woocommerce_template', 10, 3); // https://wp-kama.com/plugin/woocommerce/hook/woocommerce_locate_template

function my_admin_scripts()
{
    wp_enqueue_script('sibs_jira_script', sibsConstants::SIBS_REPORT_ISSUE, [], null);
    wp_enqueue_script('sibs_setting_script', plugins_url('/assets/js/sibs-setting.js', __FILE__), [], null);
    wp_enqueue_style('sibs_formpayment_style', plugins_url('/assets/css/formpayment.css', __FILE__), [], null);
    wp_enqueue_style('wp-color-picker');
}

add_action('admin_enqueue_scripts', 'my_admin_scripts');

add_action('wp_enqueue_scripts', 'sibsJsInit');

function sibsJsInit()
{
    wp_enqueue_script('sibs-js-init', plugins_url('/assets/js/sibs-payments.js', __FILE__), ['jquery']);
    //para testes de codigo
    // wp_enqueue_script( 'sibs-js-initsentry', 'https://js.sentry-cdn.com/8e3325386eac452c89fc165f8f65e5e8.min.js',array('jquery'));
}

function ti_custom_javascript()
{
    ?>
        <script>
            var sToken = "<?php echo wp_get_session_token(); ?>";
            var url_site = "<?php echo get_site_url(); ?>";
        </script>
    <?php
}
add_action('wp_head', 'ti_custom_javascript');

/**
 * hook to init sibs gateway.
 */
function sibs_stg_init_payment_gateway()
{
    try {
        // Loads the Sibs language translation strings
        load_plugin_textdomain(sibsConstants::SIBS_TRANSLATE, false, dirname(plugin_basename(__FILE__)) . '/languages/');

        if (! function_exists('mail')) {
            add_action('admin_notices', 'sibs_get_notice_mail_not_found__error'); // https://developer.wordpress.org/reference/hooks/admin_notices/
            // throw new sibsException('Mail function not Found');
        }

        // Notice on admin when init payment gateway
        if (! class_exists('WC_Payment_Gateway')) {
            add_action('admin_notices', 'sibs_get_notice_woocommerce_activation__error'); // https://developer.wordpress.org/reference/hooks/admin_notices/

            throw new sibsException('Woocommerce not Found');
        } else {
            // add_action('admin_notices', 'validate_sibs_term__info'); // https://developer.wordpress.org/reference/hooks/admin_notices/
        }

        $session_class = apply_filters('woocommerce_session_handler', 'WC_Session_Handler');
        wc()->session  = new $session_class();
        wc()->session->init();

        include_once __DIR__ . '/includes/core/class-sibspaymentcore.php';
        include_once __DIR__ . '/includes/core/class-sibserrorhandler.php';
        include_once __DIR__ . '/includes/sibs-admin-page.php';
        include_once __DIR__ . '/includes/sibs-style-page.php';

        function add_sibs_payments($payment_methods)
        {
            $sibs_stg_payment_methods = [
                Gateway_Sibs_STG_CC::class,
                Gateway_Sibs_STG_Blik::class,
                // Gateway_Sibs_STG_Pbl::class,
                Gateway_Sibs_STG_Pblkv::class,
            ];

            return array_merge($payment_methods, $sibs_stg_payment_methods);
        }

        add_filter('woocommerce_payment_gateways', 'add_sibs_payments');

        foreach (glob(__DIR__ . '/includes/gateways/**.php') as $filename) {
            include_once $filename;
        }
    } catch(sibsException $e) {
        $e->getErrorMessage();
    }
}

/**
 * hook to add notice woocommerce activation.
 */
function sibs_get_notice_woocommerce_activation__error()
{
    $pluginName = esc_attr(__('SIBS Payment Gateway for WooCommerce', sibsConstants::SIBS_TRANSLATE));
    $message    = esc_attr(__('BACKEND_GENERAL_PLUGINREQ', sibsConstants::SIBS_TRANSLATE));

    echo "<div id=\"notice\" class=\"notice notice-error\">
        <p>
            <a href=\"http://www.woothemes.com/woocommerce/\" style=\"text-decoration:none\" target=\"_new\">
                WooCommerce
            </a>$message <b>$pluginName</b>
        </p>
    </div>";
}

/**
 * hook to add notice woocommerce activation.
 */
function sibs_get_notice_mail_not_found__error()
{
    $pluginName = esc_attr(__('SIBS Payment Gateway for WooCommerce', sibsConstants::SIBS_TRANSLATE));
    $message    = esc_attr(__('BACKEND_GENERAL_PLUGINMAIL', sibsConstants::SIBS_TRANSLATE));

    echo "<div id=\"notice\" class=\"notice notice-error\">
        <p>
            <b>$pluginName</b> - $message
        </p>
    </div>";
}

/**
 * hook to add validate sibs tems.
 */
function validate_sibs_term__info()
{
    if (! get_option(sibsConstants::SIBS_PLUGIN_PREFIX . '_term')) {
        $admin_url  = esc_attr(admin_url('admin.php?page=wc-settings&tab=' . sibsConstants::SIBS_PLUGIN_PREFIX . '_general_settings'));
        $link       = esc_attr(sibsGeneralFunctions::sibs_translate_sibs_term('SIBS_TT_VERSIONTRACKER'));
        $link_label = esc_attr(sibsGeneralFunctions::sibs_translate_sibs_term('SIBS_BACKEND_BT_ADMIN'));

        echo "<div id=\"notice\" class=\"notice notice-info\">
            <p>
                $link
                <a href=\"$admin_url\">$link_label</a>
            </p>
        </div>";

        add_option(sibsConstants::SIBS_PLUGIN_PREFIX . '_term', true);
    }
}

/**
 * hook to add configuration links.
 */
function sibs_add_configuration_links($links)
{
    $general_settings_url   = esc_attr(admin_url('admin.php?page=sibs'));
    $general_settings_label = esc_attr(__('BACKEND_CH_GENERAL', sibsConstants::SIBS_TRANSLATE));

    // $migration_url   = esc_attr(admin_url('admin.php?page=sibs_migrate'));
    // $migration_label = esc_attr(__('MIGRATE_SIBS', sibsConstants::SIBS_TRANSLATE));

    $payments_settings_url   = esc_attr(admin_url('admin.php?page=wc-settings&tab=checkout'));
    $payments_settings_label = esc_attr(__('Payments', sibsConstants::SIBS_TRANSLATE));

    // $style_settings_url   = esc_attr(admin_url('admin.php?page=sibs_style'));
    // $style_settings_label = esc_attr(__('SIBS_STYLE_GENERAL', sibsConstants::SIBS_TRANSLATE));

    $add_links = [
        "<a href=\"$general_settings_url\">$general_settings_label</a>",
        // "<a href=\"$migration_url\">$migration_label</a>",
        "<a href=\"$payments_settings_url\">$payments_settings_label</a>",
        //  "<a href=\"$style_settings_url\">$style_settings_label</a>",
    ];

    return array_merge($add_links, $links);
}

/**
 * hook to add for thankyou order text.
 */
function sibs_wpb_thankyou($thankyoutext, $order)
{
    if(empty($order)) {
        return '';
    }

    $orderID = $order->get_id();

    //Search if this order is a SIBS order
    $transaction_log = sibsGeneralModels::sibs_get_db_transaction_log($orderID);
    $payment_id      = $transaction_log['payment_id'] ?? null;
    $isSibsOrder     = str_contains($payment_id, sibsConstants::SIBS_PLUGIN_PREFIX);

    if(! $isSibsOrder) {
        return '';
    }

    if(! $payment_id) {
        return '';
    }

    return sibsPaymentGateway::sibs_wpb_thankyou_text($thankyoutext, $order);
}

/**
 * hook to add notice woocommerce activation.
 */
function sibs_get_ajax_registered_payment()
{
    $uid        = sibsGeneralFunctions::sibs_get_request_value('user_id');
    $payment_id = sibsGeneralFunctions::sibs_get_request_value('payment_id');

    switch($payment_id) {
        case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD_SAVED:
            $payment_group = sibsConstants::SIBS_PAYMENT_METHOD_CC;

            break;
        case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DIRECT_DEBIT_SAVED:
            $payment_group = sibsConstants::SIBS_PAYMENT_METHOD_DD;

            break;
        case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAYPAL_SAVED:
            $payment_group = sibsConstants::SIBS_PAYMENT_METHOD_PAYPAL;

            break;
        default:
            $payment_group = '';
    }

    $registered_payment = sibsGeneralModels::sibs_get_payment_information($uid, $payment_group);
    echo wp_json_encode($registered_payment);

    wp_die();
}

/**
 * hook to Override new order email.
 */
function sibs_override_woocommerce_template($template, $template_name, $template_path)
{
    $template_directory = untrailingslashit(__DIR__);
    $path               = "$template_directory/$template_name";

    return file_exists($path) ? $path : $template;
}

/**
 * hook to add the javascript file for capture button.
 */
function sibs_my_function_to_add_the_js_file()
{
    // put script on order admin
    wp_register_script('sibs_button_script', plugin_dir_url(__FILE__) . 'assets/js/sibs-button.js', ['jquery'], '1.0.0', true);
    wp_enqueue_style('sibs_admin_style', plugin_dir_url(__FILE__) . 'assets/css/admin_style.css', [], null);
    wp_enqueue_style('wp-color-picker');
    wp_enqueue_script('iris', admin_url('js/iris.min.js'), ['jquery-ui-draggable', 'jquery-ui-slider', 'jquery-touch-punch'], false, 1);

    // queue script
    wp_enqueue_script('sibs_button_script');

    // send the admin ajax url to the script
    wp_localize_script('sibs_button_script', 'mb_script_var', ['ajaxurl' => admin_url('admin-ajax.php')]);
}

/**
 * hook to hide refund button.
 */
function sibs_hide_wc_refund_button()
{
    global $post;

    if (! current_user_can('administrator') && ! current_user_can('editor')) {
        return;
    }

    if (strpos($_SERVER['REQUEST_URI'], 'post.php?post=') === false) {
        return;
    }

    if (empty($post) || $post->post_type != sibsConstants::WOOCOMMERCE_POST_TYPE_SHOP_ORDER) {
        return;
    }

    $methods_to_hide_refund_buttons = [
        sibsConstants::SIBS_PAYMENT_METHOD_ORDER_BLIK,
    ]; // Async Refunds

    $statuses_to_show_refund_buttons = [
        sibsConstants::WOOCOMMERCE_ORDER_STATUS_PROCESSING,
        sibsConstants::WOOCOMMERCE_ORDER_STATUS_COMPLETED,
    ];

    $order          = new WC_Order($post->ID);
    $payment_status = 'wc-' . $order->get_status();
    $payment_method = $order->get_payment_method();

    $is_refund_status      = in_array($payment_status, $statuses_to_show_refund_buttons);
    $is_not_refund_methods = in_array($payment_method, $methods_to_hide_refund_buttons);

    if ($is_refund_status && ! $is_not_refund_methods) {
        return;
    }

    ?>
    <script>
        jQuery(function () {
            jQuery('.refund-items').hide();
            jQuery('.order_actions option[value=send_email_customer_refunded_order]').remove();
            if (jQuery('#original_post_status').val() == 'wc-refunded') {
                jQuery('#s2id_order_status').html('Refunded');
            } else {
                jQuery('#order_status option[value=wc-refunded]').remove();
            }
        });
    </script>

    <?php
}

/**
 * hook to add buttons on order admin.
 */
function sibs_add_admin_buttons($order)
{
    $sibsOrderData = sibsGeneralModels::sibs_get_db_transaction_log($order->get_id());

    $payment_method = $order->get_payment_method();
    $payment_status = 'wc-' . $order->get_status();
    $payment_type   = isset($sibsOrderData['payment_type']) ? $sibsOrderData['payment_type'] : null;

    // STATUS INQUIRY BUTTON
    //sibsPaymentGateway::sibs_status_inquiry_order_add_button($order);

    // CAPTURE BUTTON FOR AUTHORIZATIONS
    $payments_auth_db = [
        sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD_SAVED,
        sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DIRECT_DEBIT,
        sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DIRECT_DEBIT_SAVED,
        sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAYDIREKT,
        sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD,
    ];

    $statuses_to_show_capture_buttons = [
        sibsConstants::WOOCOMMERCE_ORDER_STATUS_PENDING,
        sibsConstants::SIBS_ORDER_STATUS_AUTHORIZED,
        sibsConstants::SIBS_ORDER_STATUS_PARTIALLY_CAPTURED,
    ];

    $method_has_auth   = in_array($payment_method, $payments_auth_db);
    $is_capture_status = in_array($payment_status, $statuses_to_show_capture_buttons);
    $is_auth           = $payment_type === sibsConstants::SPG_PAYMENT_TYPE_AUTH;

    if ($method_has_auth && $is_capture_status && $is_auth) {
        sibsPaymentGateway::sibs_capture_order_add_button($order);
    }

    // CANCEL AUTHORIZATION BUTTON
    $statuses_to_show_cancel_authorization_buttons = [
        sibsConstants::SIBS_ORDER_STATUS_AUTHORIZED,
        sibsConstants::SIBS_ORDER_STATUS_PARTIALLY_CAPTURED,
    ];
    $is_cancel_authorization_status = in_array($payment_status, $statuses_to_show_cancel_authorization_buttons);

    if ($is_cancel_authorization_status) {
        sibsPaymentGateway::sibs_cancel_authorization_order_add_button($order);
    }

    // REFUND INQUIRY BUTTON FOR ASYNC REFUNDS
    $payments_async_refund_db = [
        sibsConstants::SIBS_PAYMENT_METHOD_ORDER_BLIK,
    ];

    $statuses_to_show_refund_inquiry_buttons = [
        sibsConstants::SIBS_ORDER_STATUS_PENDING_REFUND,
    ];

    $method_is_async_refund   = in_array($payment_method, $payments_async_refund_db);
    $is_refund_inquiry_status = in_array($payment_status, $statuses_to_show_refund_inquiry_buttons);

    if ($method_is_async_refund && $is_refund_inquiry_status) {
        sibsPaymentGateway::sibs_refund_inquiry_order_add_button($order);
    }

    // ASYNC REFUND BUTTON
    $statuses_to_show_async_refund_buttons = [
        sibsConstants::WOOCOMMERCE_ORDER_STATUS_PROCESSING,
        sibsConstants::WOOCOMMERCE_ORDER_STATUS_COMPLETED,
    ];

    $is_async_refund_status = in_array($payment_status, $statuses_to_show_async_refund_buttons);

    if ($method_is_async_refund && $is_async_refund_status) {
        sibsPaymentGateway::sibs_refund_async_order_add_button($order);
    }
}

/**
 * Hook to add button to order admin.
 */
function sibs_ajax_add_button_to_order_admin()
{
    $order_id  = intval($_POST['order_id']);
    $button_id = intval($_POST['button_id']);

    wc_get_logger()->debug('POST: ' . implode('', $_POST), sibsConstants::SIBS_LOG);
    wc_get_logger()->debug("order_id: $order_id", sibsConstants::SIBS_LOG);
    wc_get_logger()->debug("button_id: $button_id", sibsConstants::SIBS_LOG);

    switch($button_id) {
        case 1:
            $back_data = sibsPaymentGateway::check_status($order_id);

            break;
        case 2:
            $back_data = sibsPaymentGateway::process_capture($order_id);

            break;
        case 3:
            $back_data = sibsPaymentGateway::refund_inquiry($order_id);

            break;
        case 4:
            $back_data = sibsPaymentGateway::cancel_authorization($order_id);

            break;
        case 5:
            $back_data = sibsPaymentGateway::async_refund($order_id);

            break;
        default:
            $back_data['msg']   = __('Function not recognized', sibsConstants::SIBS_TRANSLATE);
            $back_data['error'] = 1;
    }
    wp_send_json($back_data);
}

/**
 * Hook to cancel old onhold orders.
 */
function sibs_cancel_onhold_orders()
{
    wc_get_logger()->debug('sibs cancel order inicio', sibsConstants::SIBS_CRON_LOG);

    $held_duration = get_option('woocommerce_hold_stock_minutes');
    $manage_stock  = get_option('woocommerce_manage_stock');

    if ($held_duration < 1 || $manage_stock !== 'yes') {
        return;
    }

    $seconds_delay = $held_duration * 60;
    $today         = strtotime(date('Y-m-d H:i:s'));

    // Get unpaid orders
    $unpaid_orders = (array) wc_get_orders([
        'limit'        => -1,
        'status'       => sibsConstants::WOOCOMMERCE_ORDER_STATUS_ON_HOLD,
        'date_created' => '<' . ($today - $seconds_delay),
    ]);

    if (sizeof($unpaid_orders) > 0) {
        $cancelled_text = __('The order was cancelled due to no payment from customer.', sibsConstants::SIBS_TRANSLATE);

        // Loop through orders
        foreach ($unpaid_orders as $unpaid_order) {
            $unpaid_order_id = wc_print_r($unpaid_order->get_id(), true);
            wc_get_logger()->debug("sibs cancel on-hold order id: $unpaid_order_id", sibsConstants::SIBS_CRON_LOG);

            $payments_method_on_hold_to_cancel = [
                sibsConstants::SIBS_PAYMENT_METHOD_ORDER_BLIK,
                sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK,
                sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK_KEVIN,
            ];

            if (in_array($unpaid_order->get_payment_method(), $payments_method_on_hold_to_cancel)) {
                try {
                    $unpaid_order->update_status(sibsConstants::WOOCOMMERCE_ORDER_STATUS_CANCELLED, $cancelled_text);
                } catch (Throwable $t) {
                    wc_get_logger()->critical($t->getMessage(), sibsConstants::SIBS_CRON_LOG);
                }
            }
        }
    }

    wp_clear_scheduled_hook('woocommerce_cancel_unpaid_orders');
    wp_schedule_single_event(time() + (absint($held_duration) * 60), 'woocommerce_cancel_unpaid_orders');
}

/**
 * Hook to render before submit payment form action.
 *
 * @return void
 */
function sibs_woocommerce_review_order_before_submit_action()
{
    $settings = get_option('woocommerce_' . sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD . '_settings');
    $oneclick = $settings['tokenization'] ?? null;

    if ($oneclick === sibsConstants::SIBS_TOKEN_ONECLICK && get_current_user_id()) {
        $termsAndConditionsLinkLabel = __('SIBS terms of service', sibsConstants::SIBS_TRANSLATE);
        $termsAndConditionsLink      = "<a href='javascript:void(0)'  id='opener' >{$termsAndConditionsLinkLabel}</a>";
        $termsAndConditionsLink .= '<script type="text/javascript">jQuery( "#opener" ).on( "click", function() {jQuery( "#dialog-message" ).dialog( "open" );});</script>';

        $oneclickExplanationLinkLabel = __('OneClick', sibsConstants::SIBS_TRANSLATE);
        $oneclickExplanationLink      = "<a href='javascript:void(0)'  id='opener__oneclick_definition_page' >{$oneclickExplanationLinkLabel}</a>";
        $oneclickExplanationLink .= '<script type="text/javascript">jQuery( "#opener__oneclick_definition_page" ).on( "click", function() {jQuery( "#oneclick_definition_page" ).dialog( "open" );});</script>';

        $checkoutLabel = sprintf(
            __('I agree to the %s and will adhere to them unconditionally for %s payment.', sibsConstants::SIBS_TRANSLATE),
            $termsAndConditionsLink,
            $oneclickExplanationLink,
        );

        $oneclick_payment_methods = [
            sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD,
        ];

        $paymentMethodValue    = WC()->checkout->get_value('payment_method');
        $customerAcceptorValue = WC()->checkout->get_value(sibsConstants::SIBS_PLUGIN_PREFIX . '_oneclick_customer_acceptor');

        woocommerce_form_field(sibsConstants::SIBS_PLUGIN_PREFIX . '_oneclick_customer_acceptor', [
            'id'                   => sibsConstants::SIBS_PLUGIN_PREFIX . '_oneclick_terms_of_service',
            'type'                 => 'checkbox',
            'label'                => $checkoutLabel,
            'class'                => in_array($paymentMethodValue, $oneclick_payment_methods) ? 'm-fadeIn' : 'm-fadeOut',
            'required'             => false,
        ], $customerAcceptorValue);
    }
}

/**
 * Hook to execute on process checkout action.
 *
 * @return void
 */
function sibs_woocommerce_checkout_process_action()
{
    WC()->session->__unset(sibsConstants::SIBS_PLUGIN_PREFIX . '_oneclick_customer_acceptor');
    $oneclick_customer_acceptor = ! empty(sibsGeneralFunctions::sibs_get_request_value(sibsConstants::SIBS_PLUGIN_PREFIX . '_oneclick_customer_acceptor'));
    WC()->session->set(sibsConstants::SIBS_PLUGIN_PREFIX . '_oneclick_customer_acceptor', $oneclick_customer_acceptor);
}

/**
 * Hook to put script on woocommerce footer.
 *
 * @return void
 */
function sibs_footer()
{
    if (! is_checkout()) {
        return;
    }

    $settings = get_option('woocommerce_' . sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD . '_settings');
    $oneclick = $settings['tokenization'];

    if ($oneclick !== sibsConstants::SIBS_TOKEN_ONECLICK) {
        return;
    }
    ?>

    <style type="text/css">
        .m-fadeOut {
            visibility: hidden;
            opacity: 0;
            height: 0;
            padding: 0;
            margin: 0;
            border: 0;
            transition: visibility 0s linear 300ms, opacity 0ms;
        }
        .m-fadeIn {
            visibility: visible;
            opacity: 1;
            transition: visibility 0s linear 0s, opacity 300ms;
        }
    
    </style>    

    <?php if(get_current_user_id()):?>
    <script type="text/javascript">
        function oneclick_show_or_hide() {
            let oneclick_payment_methods = [
                "<?= sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD ?>"
            ];

            let selected_payment_method = jQuery("input[name=payment_method]:checked").val();
            let sibs_terms_checkbox = document.getElementById("<?= sibsConstants::SIBS_PLUGIN_PREFIX . '_oneclick_terms_of_service' ?>_field");

            if (oneclick_payment_methods.includes(selected_payment_method)) {
                sibs_terms_checkbox.classList.remove("m-fadeOut");
                sibs_terms_checkbox.classList.add("m-fadeIn");
            } else {
                sibs_terms_checkbox.classList.remove("m-fadeIn");
                sibs_terms_checkbox.classList.add("m-fadeOut");
            }
            
        }

        jQuery(window).on("load", function() {
            jQuery("form.checkout").on("change", "input[name=payment_method]", function(e) {
                e.preventDefault();
                oneclick_show_or_hide();

            });
            var wWidth = jQuery(window).width();
            var dWidth = wWidth * 0.8;
            var wHeight = jQuery(window).height();
            var dHeight = wHeight * 0.8;
            var $link = jQuery(this);

            jQuery( "#dialog-message" ).dialog({
                    autoOpen: false,
                    width: dWidth,
                    height: dHeight,
                    open: function() {
                        jQuery(".ui-dialog-buttonpane").hide();
                    },
                    buttons: {
                        Ok: function() {
                            jQuery( this ).dialog( "close" );
                        }
                    }
            });
            jQuery( "#oneclick_definition_page" ).dialog({
                    autoOpen: false,
                    width: dWidth,
                    height: dHeight,
                    open: function() {
                        jQuery(".ui-dialog-buttonpane").hide();
                    },
                    buttons: {
                        Ok: function() {
                            jQuery( this ).dialog( "close" );
                        }
                    }
            });
        });
    </script>
<?php endif; ?>


<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<style type="text/css">
    #dialog-message{
        z-index: 999999;
        height: 100%;
    }
    .no-close .ui-dialog-titlebar-close {
        display: none;
    }
    .ui-dialog .ui-dialog-content {
         padding: 0px !important;   
    }
</style>

<div id="dialog-message" title="<?php echo __('SIBS terms of service', sibsConstants::SIBS_TRANSLATE)?>" style="display: none;">
    <?php
        $lang    = sibsFunctions::get_language();
    $pdf         = "sibs_terms_and_conditions_{$lang}.pdf";
    $siteUrl     = untrailingslashit(plugins_url('/', __FILE__));
    $pdfUrl      = "{$siteUrl}/assets/files/$pdf";
    ?>
    <embed src="<?php echo $pdfUrl; ?>" frameborder="0" width="100%" style="float:left; position:relative; height:100%;">
</div>
<div id="oneclick_definition_page" title="<?php echo __('OneClick Definition Page', sibsConstants::SIBS_TRANSLATE); ?>" style="display: none;">
    <?php
    echo '<p>' . __('If you activate OneClick, we will verify your card and you will see a transaction for 0 PLN on your account.', sibsConstants::SIBS_TRANSLATE) . __('Please note that your bank may require additional authorization.', sibsConstants::SIBS_TRANSLATE) . '</p> <p>' . __('With OneClick activated, we will not ask you to enter your card details for future payments.', sibsConstants::SIBS_TRANSLATE) . '</p>';
    ?>
</div>


<?php
}
?>