<?php

/*
 * Plugin Name:       Scotiabank Payment Gateway for WooCommerce
 * Plugin URI:        https://wpcompanion.co/scotia-bank-payment-gateway-for-woocommerce/
 * Description:       Enables payments via Scotiabank.
 * Author:            Imanuel Gittens
 * Author URI:        https://wpcompanion.co/
 * Version:           2.3.1
 * License:           GPLv2 or later
 * Requires PHP:      7.4
 * Requires at least: 6.1
 * Tested up to:      6.9.1
 * Text Domain:       ig-wc-scotiabank
 * Domain Path:       languages
 * Network:           false
 * WC requires at least: 3.0
 * WC tested up to     : 10.5.2
 *
 * Scotiabank Payment Gateway for WooCommerce is distributed under the terms of the 
 * GNU General Public License as published by the Free Software Foundation, 
 * either version 2 of the License, or any later version.
 *
 * Scotiabank Payment Gateway for WooCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 */
namespace WPCompanion\ScotiaBank;

defined( 'ABSPATH' ) || exit;
if ( function_exists( __NAMESPACE__ . '\\' . 'wpcsb_scotiabank' ) ) {
    wpcsb_scotiabank()->set_basename( false, __FILE__ );
} else {
    // DO NOT REMOVE THIS IF, IT IS ESSENTIAL FOR THE `function_exists` CALL ABOVE TO PROPERLY WORK.
    if ( !function_exists( __NAMESPACE__ . '\\' . 'wpcsb_scotiabank' ) ) {
        // Create a helper function for easy SDK access.
        function wpcsb_scotiabank() {
            global $wpcsb_scotiabank;
            if ( !isset( $wpcsb_scotiabank ) ) {
                // Include Freemius SDK.
                require_once dirname( __FILE__ ) . '/freemius/start.php';
                $wpcsb_scotiabank = fs_dynamic_init( array(
                    'id'               => '13762',
                    'slug'             => 'ig-wc-scotiabank',
                    'type'             => 'plugin',
                    'public_key'       => 'pk_6da2bab04830f8b07e49b517a8caa',
                    'is_premium'       => false,
                    'premium_suffix'   => 'Professional',
                    'has_addons'       => false,
                    'has_paid_plans'   => true,
                    'is_org_compliant' => false,
                    'menu'             => array(
                        'slug'    => '',
                        'contact' => true,
                        'support' => true,
                        'account' => true,
                    ),
                    'is_live'          => true,
                ) );
            }
            return $wpcsb_scotiabank;
        }

        // Init Freemius.
        wpcsb_scotiabank();
        // Signal that SDK was initiated.
        do_action( 'wpcsb_scotiabank_loaded' );
    }
    if ( !class_exists( 'IG_Scotiabank' ) ) {
        /**
         * Main class.
         *
         */
        final class IG_Scotiabank {
            /**
             * Instance of this class.
             *
             * @access protected
             * @access static
             * @var object
             */
            protected static $instance = null;

            /**
             * Slug, same as Gateway->id
             *
             * @access public
             * @var    string
             */
            public $gateway_slug = 'ig_scotiabank';

            /**
             * The Gateway Name.
             *
             * @access public
             * @var    string
             */
            public $name = 'ScotiaBank';

            /**
             * Return an instance of this class.
             *
             * @return object A single instance of this class.
             */
            public static function get_instance() {
                // If the single instance hasn't been set, set it now.
                if ( null == self::$instance ) {
                    self::$instance = new self();
                }
                return self::$instance;
            }

            /**
             * Initialize the plugin public actions.
             *
             * @access private
             */
            private function __construct() {
                add_action( 'init', array($this, 'load_plugin_textdomain') );
                if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, '3.0', '>=' ) ) {
                    $this->includes();
                    add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array($this, 'action_links') );
                    add_filter( 'woocommerce_payment_gateways', array($this, 'add_gateway') );
                    add_action( 'wp_loaded', array($this, 'scotiabank_return_handler') );
                } else {
                    add_action( 'admin_notices', array($this, 'woocommerce_error_notice') );
                }
                //Load block compatibility
                $this->block_compatiblity();
            }

            public function block_compatiblity() {
                //Mark compatibility with checkout blocks
                add_action( 'before_woocommerce_init', function () {
                    if ( class_exists( '\\Automattic\\WooCommerce\\Utilities\\FeaturesUtil' ) ) {
                        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
                        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', __FILE__, true );
                    }
                } );
                //Load checkout block class
                add_action( 'woocommerce_blocks_loaded', function () {
                    if ( !class_exists( 'Automattic\\WooCommerce\\Blocks\\Payments\\Integrations\\AbstractPaymentMethodType' ) ) {
                        return;
                    }
                    require_once 'includes/class-gateway-block.php';
                    add_action( 'woocommerce_blocks_payment_method_type_registration', function ( \Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
                        $payment_method_registry->register( new Gateway_Block() );
                    } );
                } );
            }

            /**
             * Handle returns from Scotiabank.
             *
             * @access public
             */
            public function scotiabank_return_handler() {
                if ( !isset( $_GET['ig-scotia-return-handler'] ) || $_GET['ig-scotia-return-handler'] != 'yes' ) {
                    return;
                }
                // Let's get order key.
                $order_key = sanitize_text_field( $_GET['key'] );
                if ( $order_key ) {
                    // Load gateways.
                    \WC()->payment_gateways();
                    $available_gateways = \WC()->payment_gateways->get_available_payment_gateways();
                    if ( isset( $available_gateways['ig_scotiabank'] ) ) {
                        $available_gateways['ig_scotiabank']->return_handler( $order_key );
                    }
                }
            }

            /**
             * Plugin action links.
             *
             * @access public
             * @param  mixed $links
             * @return void
             */
            public function action_links( $links ) {
                if ( current_user_can( 'manage_woocommerce' ) ) {
                    $plugin_links = array('<a href="' . admin_url( 'admin.php?page=wc-settings&tab=checkout&section=' . $this->gateway_slug ) . '">' . esc_html__( 'Settings', 'ig-wc-scotiabank' ) . '</a>', '<a href="' . admin_url( 'admin.php?page=ig-wc-scotiabank-account' ) . '">' . esc_html__( 'Account', 'ig-wc-scotiabank' ) . '</a>');
                    return array_merge( $plugin_links, $links );
                }
                return $links;
            }

            /**
             * Load Localization files.
             *
             * @access public
             * @return void
             */
            public function load_plugin_textdomain() {
                load_plugin_textdomain( 'ig-wc-scotiabank', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
            }

            /**
             * Include files.
             *
             * @access private
             * @return void
             */
            private function includes() {
                include_once 'includes/class-scotiabank-fiserv-api.php';
                include_once 'includes/class-gateway.php';
            }

            /**
             * Add the gateway.
             *
             * @access public
             * @param  array $load_gateways WooCommerce payment gateways.
             * @return array $load_gateways WooCommerce payment gateways.
             */
            public function add_gateway( $load_gateways ) {
                $load_gateways[] = __NAMESPACE__ . '\\Gateway';
                return $load_gateways;
            }

            /**
             * WooCommerce Error Notice.
             *
             * @access public
             * @return string
             */
            public function woocommerce_error_notice() {
                echo '
					<div class="error">
						<p>
							<strong>' . esc_html__( 'Scotiabank Payment Gateway', 'ig-wc-scotiabank' ) . '</strong> ' . sprintf( 
                    /* translators: %s is replaced with "WooCommerce" */
                    esc_html__( 'only works with %s 3.0 or later, please install or upgrade your installation!', 'ig-wc-scotiabank' ),
                    '<a href="http://wordpress.org/plugins/woocommerce/">' . esc_html__( 'WooCommerce', 'ig-wc-scotiabank' ) . '</a>'
                 ) . '
						</p>
					</div>';
            }

            /** Helper functions ******************************************************/
            /**
             * Get the plugin url.
             *
             * @access public
             * @return string
             */
            public function plugin_url() {
                return untrailingslashit( plugins_url( '/', __FILE__ ) );
            }

            /**
             * Get the plugin path.
             *
             * @access public
             * @return string
             */
            public function plugin_path() {
                return untrailingslashit( plugin_dir_path( __FILE__ ) );
            }

        }

        add_action( 'plugins_loaded', array(__NAMESPACE__ . '\\IG_Scotiabank', 'get_instance'), 0 );
    }
    /**
     * Returns the main instance of WC_Scotia_bank to prevent the need to use globals.
     *
     * @return 
     */
    function ig_scotiabank() {
        return IG_Scotiabank::get_instance();
    }

}