<?php
/**
 * @wordpress-plugin
 * Plugin Name: Svea Stand Alone for WooCommerce
 * Description: Supercharge your WooCommerce Store with powerful features to pay via Svea Credit card, Invoice, Part Payment, Trustly, Swish, MobilePay and Vipps.
 * Version: 4.0.5
 * Author: The Generation
 * Author URI: https://thegeneration.se/
 * Domain Path: /languages
 * Text Domain: svea-webpay-for-woocommerce
 *
 * WC tested up to: 8.2.1
 */

namespace Svea_Webpay_For_Woocommerce;

/**
 * Exit if accessed directly
 */
if ( ! defined( 'ABSPATH' ) ) exit;

// Define the plugin base directory
if ( ! defined( 'WC_SVEAWEBPAY_GATEWAY_PLUGIN_DIR' ) ) {
	define( 'WC_SVEAWEBPAY_GATEWAY_PLUGIN_DIR', __DIR__ );
}

if ( ! class_exists( 'Plugin' ) ) :

	/**
	 * Main plugin class
	 */
	class Plugin {

		/**
		 * Plugin version, used for cache-busting of style and script file references.
		 *
		 * @var     string
		 */
		const VERSION = '4.0.5';

		/**
		 * Plugin slug
		 *
		 * @var     string
		 */
		const PLUGIN_SLUG = 'svea-webpay-for-woocommerce';

		/**
		 * Description
		 *
		 * @var string
		 */
		public $plugin_description;

		/**
		 * I18n class
		 *
		 * @var I18n
		 */
		public $i18n;

		/**
		 * Scripts class
		 *
		 * @var Scripts
		 */
		public $scripts;

		/**
		 * Ajax functions
		 *
		 * @var Ajax_Functions
		 */
		public $ajax_functions;

		/**
		 * Admin functions
		 *
		 * @var Admin_Functions
		 */
		public $admin_functions;

		/**
		 * Cron functions
		 *
		 * @var Cron_Functions
		 */
		public $cron_functions;

		/**
		 * Order functions
		 *
		 * @var Order_Functions
		 */
		public $order_functions;

		/**
		 * Shortcodes
		 *
		 * @var Shortcodes
		 */
		public $shortcodes;

		/**
		 * General class constructor where we'll setup our actions, hooks, and shortcodes.
		 */
		public function __construct() {
			$this->load_dependencies();
			$this->init_modules();
			/**
			 * Define the plugin base url
			 */
			if ( ! defined( 'WC_SVEAWEBPAY_GATEWAY_PLUGIN_URL' ) ) {
				define( 'WC_SVEAWEBPAY_GATEWAY_PLUGIN_URL', plugins_url( '/', __FILE__ ) );
			}

			register_activation_hook( __FILE__, [ $this, 'plugin_activation' ] );
			register_deactivation_hook( __FILE__, [ $this, 'plugin_deactivation' ] );

			/**
			 * Check if woocommerce is activated, else display a message and deactivate the plugin
			 */
			if ( ! self::is_woocommerce_installed() ) {
				// phpcs:ignore
				if ( isset( $_GET['action'] ) && ! in_array( $_GET['action'], [ 'activate-plugin', 'upgrade-plugin', 'activate', 'do-plugin-upgrade' ], true ) ) {
					return;
				}

				$notices = get_option( 'sveawebpay_deferred_admin_notices', [] );
				$notices[] = [
					'type'    => 'error',
					'message' => __( 'WooCommerce Svea Stand Alone Gateway has been deactivated because WooCommerce is not installed. Please install WooCommerce and re-activate.', 'svea-webpay-for-woocommerce' ),
				];

				update_option( 'sveawebpay_deferred_admin_notices', $notices );
				add_action( 'admin_init', [ $this, 'deactivate_gateway' ] );
				return;
			}

			add_action( 'admin_notices', [ $this, 'check_compatibility' ] );

			add_filter( 'woocommerce_payment_gateways', [ $this, 'woocommerce_add_gateway_svea_gateway' ] );

			add_action( 'admin_init', [ $this, 'check_plugin_updates' ] );

			add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), [ $this, 'settings_link' ] );
		}

		/**
		 * Load plugin dependencies
		 *
		 * @return void
		 */
		public function load_dependencies() {
			// Load the Svea integration package.
			require_once WC_SVEAWEBPAY_GATEWAY_PLUGIN_DIR . '/vendor/autoload.php';
		}

		/**
		 * Initialize the modules
		 *
		 * @return void
		 */
		public function init_modules() {
			$this->i18n = new I18n();
			$this->i18n->init();

			$this->scripts = new Scripts();
			$this->scripts->init();

			$this->ajax_functions = new Ajax_Functions();
			$this->ajax_functions->init();

			$this->admin_functions = new Admin_Functions();
			$this->admin_functions->init();

			$this->cron_functions = new Cron_Functions();
			$this->cron_functions->init();

			$this->order_functions = new Order_Functions();
			$this->order_functions->init();

			$this->shortcodes = new Shortcodes();
			$this->shortcodes->init();
		}

		/**
		 * Load plugin description for translations
		 *
		 * @return void
		 */
		public function load_plugin_description() {
			$this->plugin_description = __( 'Supercharge your WooCommerce Store with powerful features to pay via Svea Credit card, Direct Bank Payment, Invoice and Part Payment.', 'svea-webpay-for-woocommerce' );
		}

		/**
		 * Check and set the plugin version if it has been updated
		 *
		 * @return void
		 */
		public function check_plugin_updates() {
			$svea_db_version = get_option( 'sveawebpay_plugin_version', false );

			/**
			 * See if the version has been changed
			 */
			if ( ! $svea_db_version || $svea_db_version !== self::VERSION ) {
				// Run plugin update function here
				update_option( 'sveawebpay_plugin_version', self::VERSION );
			}
		}

		/**
		 * Check if WooCommerce is installed and activated
		 *
		 * @return  boolean     whether or not WooCommerce is installed
		 */
		public static function is_woocommerce_installed() {
			/**
			 * Get a list of active plugins
			 */
			$active_plugins = apply_filters( 'active_plugins', get_option( 'active_plugins' ) );

			$is_woocommerce_installed = false;

			/**
			 * Loop through the active plugins
			 */
			foreach ( $active_plugins as $plugin ) {
				/**
				 * If the plugin name matches WooCommerce
				 * it means that WooCommerce is active
				 */
				if ( preg_match( '/.+\/woocommerce\.php/', $plugin ) ) {
					$is_woocommerce_installed = true;
					break;
				}
			}

			return $is_woocommerce_installed;
		}

		/**
		 * Check compatibility with PHP- and WooCommerce-versions
		 *
		 * @return void
		 */
		public function check_compatibility() {
			/**
			 * Only display message if the current user is administrator
			 */
			if ( ! current_user_can( 'manage_options' ) ) {
				return;
			}

			/**
			 * Required modules by the Svea Stand Alone Integration package
			 */
			if ( ! extension_loaded( 'soap' ) || ! class_exists( 'SoapClient' ) ) {
				printf(
					'<div class="error"><h3>Svea Stand Alone</h3><p>' .
					esc_html__( 'The PHP Module <strong>Soap</strong> is not enabled. Svea Stand Alone requires this module to be enabled for it to function properly. Talk to your web host and make sure it is enabled.', 'svea-webpay-for-woocommerce' ) .
					'</p></div>'
				);
			}

			/**
			 * Versions that are tested with this module.
			 * Remember to test this with each new version.
			 */
			$php_version = '7.4.0';

			if ( version_compare( PHP_VERSION, $php_version, '<' ) ) {
				printf(
					'<div class="error"><h3>Svea Stand Alone</h3><p>' .
					// translators: %1$s is the current PHP version, %2$s is the supported PHP-version
					esc_html__( 'Your PHP version is <strong>%1$s</strong>, lower than the supported version for Svea Stand Alone for WooCommerce, <strong>%2$s</strong>. The integration might not work as expected.', 'svea-webpay-for-woocommerce' ) .
					'</p></div>',
					esc_html( PHP_VERSION ),
					esc_html( $php_version )
				);
			}
		}

		/**
		 * Handles plugin activation
		 *
		 * @return void
		 */
		public function plugin_activation() {
			require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );

			if ( ! self::is_woocommerce_installed() ) {

				$notices = get_option( 'sveawebpay_deferred_admin_notices', [] );
				$notices[] = [
					'type'    => 'error',
					'message' => esc_html__( 'WooCommerce Svea Stand Alone Gateway has been deactivated because WooCommerce is not installed. Please install WooCommerce and re-activate.' ),
				];

				update_option( 'sveawebpay_deferred_admin_notices', $notices );
				add_action( 'admin_init', [ &$this, 'deactivate_gateway' ] );
			}

			$notices = get_option( 'sveawebpay_deferred_admin_notices', [] );
			$notices[] = [
				'type'    => 'updated',
				'message' => __( 'WooCommerce Svea Stand Alone Payment Gateway has now been activated, you can configure the different gateways', 'svea-webpay-for-woocommerce' ) .
				' <a href="' . admin_url( 'admin.php?page=wc-settings&tab=checkout&section=wc_gateway_svea_card' ) . '">' . __( 'on this page', 'svea-webpay-for-woocommerce' ) .
				'</a>. ' . __( 'If you don\'t have a contract with Svea Stand Alone please contact them', 'svea-webpay-for-woocommerce' ) .
				' <a href="https://www.svea.com/se/sv/foretag/betallosningar/betallosningar-for-e-handel/" target="_BLANK" rel="noopener">' . __( 'here', 'svea-webpay-for-woocommerce' ) . '</a>.',
			];

			update_option( 'sveawebpay_deferred_admin_notices', $notices );
			update_option( 'sveawebpay_plugin_version', self::VERSION );
		}

		/**
		 * Handles plugin de-activation
		 *
		 * @TODO
		 * @return  void
		 */
		public function plugin_deactivation() { }

		/**
		 * Deactivate the WooCommerce Svea Stand Alone Gateway
		 *
		 * @return  void
		 */
		public function deactivate_gateway() {
			if ( ! function_exists( 'deactivate_plugins' ) ) {
				return;
			}

			deactivate_plugins( plugin_basename( __FILE__ ) );
		}

		/**
		 * Add settings link on the plugin page.
		 *
		 * @param array $links associative array of links
		 * @return array associative array of links
		 */
		public function settings_link( $links ) {
			$settings_link =
			'<a href="admin.php?page=wc-settings&tab=checkout&section=sveawebpay_card">' .
				__( 'Settings', 'svea-webpay-for-woocommerce' ) .
			'</a>';
			array_unshift( $links, $settings_link );
			return $links;
		}

		/**
		 * Add the payment Gateways to WooCommerce
		 *
		 * @param array $methods    associative array with payment gateways
		 * @return array associative array with payment gateways
		 */
		public function woocommerce_add_gateway_svea_gateway( $methods ) {
			// Hosted gateways
			$methods[] = __NAMESPACE__ . '\\Gateways\\WC_Gateway_Svea_Card';
			$methods[] = __NAMESPACE__ . '\\Gateways\\WC_Gateway_Svea_Swish';
			$methods[] = __NAMESPACE__ . '\\Gateways\\WC_Gateway_Svea_Mobilepay';
			$methods[] = __NAMESPACE__ . '\\Gateways\\WC_Gateway_Svea_Vipps';
			$methods[] = __NAMESPACE__ . '\\Gateways\\WC_Gateway_Svea_Trustly';

			// WebService gateways
			$methods[] = __NAMESPACE__ . '\\Gateways\\WC_Gateway_Svea_Invoice';
			$methods[] = __NAMESPACE__ . '\\Gateways\\WC_Gateway_Svea_Part_Pay';

			return $methods;
		}
	}

	if ( ! function_exists( 'svea_webpay' ) ) {
		/**
		 * Svea checkout instance
		 *
		 * @return Plugin
		 */
		function svea_webpay() {
			static $instance;

			if ( $instance === null ) {
				$instance = new Plugin();
			}

			return $instance;
		}
	}

	// Enable HPOS
	add_action(
		'before_woocommerce_init',
		function() {
			if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
				\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
			}
		}
	);

	svea_webpay();

endif;
