<?php

/**
 * @package Gratify BNPL
 */
/**
 * Plugin Name: Gratify BNPL
 * Plugin URI: https://gratifypay.com
 * Author: Gratify Pay
 * Author URI: https://gratifypay.com
 * Description: Sell more with Gratify Buy Now Pay Later.
 * Version: 1.1.1
 * License: 1.1.1
 * License: GPLv2 or later
 * text-domain: gratify-pay
*/ 

if (!defined('ABSPATH')) {
	exit;
}

if (!class_exists("GratifyPay_Plugin")){
    class GratifyPay_Plugin{
        
        /**
		 * @var		GratifyPay_Plugin		$instance	A static reference to an instance of this class.
		 */
        protected static $instance;

	    /**
		 * @var		int					$version	A reference to the plugin version, which will match
		 *											the value in the comments above.
		 */
		public static $version = '1.1.1';
        
        /**
         * Import required classes.
         * @since   1.0.0
         * @used-by self::init()
         * @used-by self::deactivate_plugin()
         */

        public static function load_classes(){
            require_once dirname(__FILE__) . '/class/Merchant/GratifyPay_Merchant.php';
            if (class_exists("WC_Payment_Gateway")) {
                require_once dirname(__FILE__) . "/class/WC_Gratify_Pay_Gateway.php";
            }
        }

        /**
         * Class constructor. Called when an object of this class is instantiated.
         * 
         * @since   1.0.0
         * @see     GratifyPay_Plugin::init()       For where this class is instantiaed
         * @see     WC_Settings_API::process_admin_options()
         * @uses    self::generate_product_hooks()
         * @uses    self::generate_category_hooks()
         * @uses    WC_Gratify_Pay_Gateway::getInstance()
         */
        public function __construct(){
            $gateway = WC_Gratify_Pay_Gateway::getInstance();

            /**
             * Actions
             */
            add_action('admin_notices', array($gateway, 'render_admin_notices'), 10, 0);
            add_action( 'admin_enqueue_scripts', array($this, 'init_admin_assets'), 10, 0 );
            add_action( "woocommerce_update_options_payment_gateways_{$gateway->id}", array($gateway, 'process_admin_options'), 10, 0 ); # process_admin_options() is defined in WC_Gratify_Pay_Gateway's grandparent class: WC_Settings_API.
			add_action( "woocommerce_update_options_payment_gateways_{$gateway->id}", array($gateway, 'refresh_cached_configuration'), 11, 0 ); # Refresh cached configuration after our gateway settings are saved, but before the cron jobs run.
            add_action( 'woocommerce_cart_totals_after_order_total', array($gateway, 'render_cart_page_elements'), 10, 0 );
            add_action( "wp_enqueue_scripts", array($this, 'init_website_assets'), 10, 0);
            add_action( "woocommerce_api_wc_gateway_gratify_pay", array($gateway, 'capture_payment') );
			add_action( 'wp_ajax_gratify_pay_action', array($gateway, 'reset_settings_api_form_fields'),10,0 );

            /**
             * Filters
             */
            add_filter("plugin_action_links_". plugin_basename( __FILE__ ), array($this, 'filter_action_links'), 10, 1);
            add_filter( 'woocommerce_payment_gateways', array($gateway, 'add_gratifypay_gateway'), 10, 1 );
            add_filter( 'woocommerce_get_price_html', array($gateway, 'filter_woocommerce_get_price_html'), 10, 2 );
			add_filter( 'woocommerce_gateway_icon', array($gateway, 'filter_woocommerce_gateway_icon'), 10, 2 );
			add_filter( 'woocommerce_cart_item_class', array($gateway, 'add_shippable_class_to_cart_item'), 10, 3 );

            /**
			 * Shortcodes.
			 */
			add_shortcode( 'gratifypay_product_logo', array($this, 'shortcode_gratifypay_product_logo') );
			add_shortcode( 'gratifypay_paragraph', array($gateway, 'shortcode_gratifypay_paragraph') );

            $this->generate_product_hooks($gateway);
            $this->generate_category_hooks($gateway);
        }

      
        /**
         * Perform dynamic Product Page Assets hooks processing
         * 
         * @since   1.0.0
         * @param   WC_Gratify_Pay_Gateway    $gateway
         * @uses    WC_Gratify_Pay_Gateway::getSettings
         * @return  bool
         */
        public function generate_product_hooks($gateway){
            $settings = $gateway->getSettings();
            if(!empty($settings['product-pages-hook'])){
                $product_pages_hook = $settings["product-pages-hook"];
                
                if (!empty($settings['product-pages-priority'])) {
					$product_pages_priority = (int) $settings['product-pages-priority'];
				}
				else {
					$product_pages_priority = 10;
				}
                add_action( $product_pages_hook, array($gateway, 'print_info_for_product_detail_page'), $product_pages_priority, 0 );
            }
            return true;
        }

        /**
		 * Perform dynamic Category Page Assets hooks processing
		 *
		 * @since	2.1.0
		 * @param	WC_Gratify_Pay_Gateway		$gateway
		 * @uses	WC_Gratify_Pay_Gateway::getSettings()
		 * @return	bool
		 */
		public function generate_category_hooks($gateway){
			$settings = $gateway->getSettings();
			if (!empty($settings['category-pages-hook'])) {
				$category_pages_hook = $settings['category-pages-hook'];

				if (!empty($settings['category-pages-priority'])) {
					$category_pages_priority = (int) $settings['category-pages-priority'];
				}
				else {
					$category_pages_priority = 10;
				}

				//add the adjusted Product Single Page action
				add_action( $category_pages_hook, array($gateway, 'print_info_for_listed_products'), $category_pages_priority, 0 );
			}

			return true;
		}

        /**
         * Hooked onto the "plugin_action_links_woocommerce-gateway-gratify_pay/woocommerce-gratify_pay.php" Action.
         * 
         * @since   1.0.0
         * @see     self::__construct()     For hook attachment.
         * @param   array $links
         * @return  array
         */

         public function filter_action_links($links){
            $additional_links = array(
				'<a href="' . admin_url( 'admin.php?page=wc-settings&tab=checkout&section=gratify_pay' ) . '">' . __( 'Settings', 'gratify-pay' ) . '</a>',
			);

			return array_merge($additional_links, $links);
         }

        /**
		 * Note: Hooked onto the "wp_enqueue_scripts" Action to avoid the Wordpress Notice warnings
		 *
		 * @since	1.0.0
		 * @see		self::__construct()		For hook attachment.
		 */
         public function init_website_assets(){
             $instance = WC_Gratify_Pay_Gateway::getInstance();
             if($instance->settings['enabled'] == "yes" &&
                function_exists('is_woocommerce') &&
                (is_woocommerce() || is_cart() || is_checkout())
             ){
                    /**
                     * Register & Enqueue JS
                    * Note: Admin assets are registered in self::init_admin_assets()
                    */
                    $plugin_version = self::$version;
                    $ajax_url = admin_url("admin-ajax.php");

                    wp_enqueue_style('tailwind', "https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css", array(), $plugin_version );
                    if(is_checkout()){
                        wp_enqueue_script( 'widget', "https://assets.gratifypay.com/plugin/v-latest/widget.js",  array(), $plugin_version, true );
                        wp_enqueue_style('gp', "https://assets.gratifypay.com/plugin/v-latest/styles.css", array(), $plugin_version );
                    }

                    /**
                     * Register & Enqueue CSS.
                     */
                    wp_enqueue_style( 'gratify-pay_css', plugins_url( 'assets/css/gratifypay.css', __FILE__ ), array(), $plugin_version );
             }
         }

        /**
         * Note: Hooked onto the "admin_enqueue_scripts" Action.
         * 
         * @since   1.0.0
         * @see     self::__construct()     For hook attachment.
         */
        public function init_admin_assets(){
            wp_enqueue_script( 'gratify-pay_admin_js', plugins_url( 'assets/js/gratifypay-admin.js', __FILE__ ), array('jquery'));
            wp_enqueue_script( 'gratifypay-admin1_js', plugins_url( 'assets/js/gratifypay-admin1.js', __FILE__ ), array('jquery'));
        }

        /**
		 * Provide a shortcode for rendering the standard Gratify Pay logo on individual product pages.
		 *
		 * E.g.:
		 * 	- [gratifypay_product_logo] OR [afterpay_product_logo theme="colour"]
		 * 	- [gratifypay_product_logo theme="black"]
		 * 	- [gratifypay_product_logo theme="white"]
		 *
		 * @since	2.0.0
		 * @see		self::__construct()		For shortcode definition.
		 * @param	array	$atts			Array of shortcode attributes.
		 * @uses	shortcode_atts()
		 * @return	string
		 */
        public function shortcode_gratifypay_product_logo($atts) {
			$atts = shortcode_atts( array(
				'theme' => 'colour'
			), $atts );

			if (!in_array($atts['theme'], array('colour', 'black', 'white'))) {
				$atts['theme'] = 'colour';
			}

			$static_url = WC_Gratify_Pay_Gateway::getInstance()->get_static_url();
            $badge_url = WC_Gratify_Pay_Gateway::getInstance()->get_badge_url();
			ob_start();

            // TOOD: Move new logo to app.gratifypay.com
			?><img style="vertical-align:middle;" src="<?php echo $badge_url ?>" width="45" height="30" alt="Gratify Pay" /><?php

			return ob_get_clean();
		}
        
        /**
         * Initialize the class and return an instance.
         * 
         * Note: Hooked onto the "plugins_loaded" Action.
         * 
         * @since   1.0.0
         * @uses    self::load_classes()
         * @return  GratifyPay_Plugin
         * @used-by self::activate_plugin()
         */
        public static function init(){
            self::load_classes();
            if(!class_exists("WC_Gratify_Pay_Gateway")){
                return false;
            }
            if(is_null(self::$instance)){
                self::$instance = new self;
            }
            return self::$instance;
        }

        /**
		 * Callback for when this plugin is activated. 
		 *
		 * @since	1.0.0
		 * @uses	set_transient()
		 * @uses	self::init()
		 */
		public static function activate_plugin()
		{
			if (!current_user_can( 'activate_plugins' )) {
				return;
			}

			if (function_exists('set_transient')) {
				set_transient( 'gratify_pay-admin-activation-notice', true, 300 );
			}

			self::init(); # Can't just use load_classes() here because the cron schedule is setup in the filter, which attaches inside the class constructor. Have to do a full init.
		}

		/**
		 * Callback for when this plugin is deactivated. 
		 *
		 * @since	1.0.0
		 * @uses	self::load_classes()
		 */
		public static function deactivate_plugin()
		{
			if (!current_user_can( 'activate_plugins' )) {
				return;
			}

			self::load_classes();
		}

        /**
		 * Callback for when the plugin is uninstalled. Remove all of its data.
		 *
		 * Note:	This function is called when this plugin is uninstalled.
		 *
		 * @since	1.0.0
		 */
		public static function uninstall_plugin()
		{
			if (!current_user_can( 'activate_plugins' )) {
				return;
			}
		}

    }

    register_activation_hook( __FILE__, array('GratifyPay_Plugin', 'activate_plugin') );
	register_deactivation_hook( __FILE__, array('GratifyPay_Plugin', 'deactivate_plugin') );
	register_uninstall_hook( __FILE__, array('GratifyPay_Plugin', 'uninstall_plugin') );

    add_action( 'plugins_loaded', array('GratifyPay_Plugin', 'init'), 10, 0 );
}