<?php
/**
 * Kkart setup
 *
 * @package Kkart
 * @since   3.2.0
 */

defined( 'ABSPATH' ) || exit;

use Automattic\Kkart\Proxies\LegacyProxy;

/**
 * Main Kkart Class.
 *
 * @class Kkart
 */
final class Kkart {

	/**
	 * Kkart version.
	 *
	 * @var string
	 */
	public $version = '4.8.0';

	/**
	 * Kkart Schema version.
	 *
	 * @since 4.3 started with version string 430.
	 *
	 * @var string
	 */
	public $db_version = '430';

	/**
	 * The single instance of the class.
	 *
	 * @var Kkart
	 * @since 2.1
	 */
	protected static $_instance = null;

	/**
	 * Session instance.
	 *
	 * @var KKART_Session|KKART_Session_Handler
	 */
	public $session = null;

	/**
	 * Query instance.
	 *
	 * @var KKART_Query
	 */
	public $query = null;

	/**
	 * Product factory instance.
	 *
	 * @var KKART_Product_Factory
	 */
	public $product_factory = null;

	/**
	 * Countries instance.
	 *
	 * @var KKART_Countries
	 */
	public $countries = null;

	/**
	 * Integrations instance.
	 *
	 * @var KKART_Integrations
	 */
	public $integrations = null;

	/**
	 * Cart instance.
	 *
	 * @var KKART_Cart
	 */
	public $cart = null;

	/**
	 * Customer instance.
	 *
	 * @var KKART_Customer
	 */
	public $customer = null;

	/**
	 * Order factory instance.
	 *
	 * @var KKART_Order_Factory
	 */
	public $order_factory = null;

	/**
	 * Structured data instance.
	 *
	 * @var KKART_Structured_Data
	 */
	public $structured_data = null;

	/**
	 * Array of deprecated hook handlers.
	 *
	 * @var array of KKART_Deprecated_Hooks
	 */
	public $deprecated_hook_handlers = array();

	/**
	 * Main Kkart Instance.
	 *
	 * Ensures only one instance of Kkart is loaded or can be loaded.
	 *
	 * @since 2.1
	 * @static
	 * @see KKART()
	 * @return Kkart - Main instance.
	 */
	public static function instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	/**
	 * Cloning is forbidden.
	 *
	 * @since 2.1
	 */
	public function __clone() {
		kkart_doing_it_wrong( __FUNCTION__, __( 'Cloning is forbidden.', 'kkart' ), '2.1' );
	}

	/**
	 * Unserializing instances of this class is forbidden.
	 *
	 * @since 2.1
	 */
	public function __wakeup() {
		kkart_doing_it_wrong( __FUNCTION__, __( 'Unserializing instances of this class is forbidden.', 'kkart' ), '2.1' );
	}

	/**
	 * Auto-load in-accessible properties on demand.
	 *
	 * @param mixed $key Key name.
	 * @return mixed
	 */
	public function __get( $key ) {
		if ( in_array( $key, array( 'payment_gateways', 'shipping', 'mailer', 'checkout' ), true ) ) {
			return $this->$key();
		}
	}

	/**
	 * Kkart Constructor.
	 */
	public function __construct() {
		$this->define_constants();
		$this->define_tables();
		$this->includes();
		$this->init_hooks();
	}

	/**
	 * When WP has loaded all plugins, trigger the `kkart_loaded` hook.
	 *
	 * This ensures `kkart_loaded` is called only after all other plugins
	 * are loaded, to avoid issues caused by plugin directory naming changing
	 * the load order. See #21524 for details.
	 *
	 * @since 3.6.0
	 */
	public function on_plugins_loaded() {
		do_action( 'kkart_loaded' );
	}

	/**
	 * Hook into actions and filters.
	 *
	 * @since 2.3
	 */
	private function init_hooks() {
		register_activation_hook( KKART_PLUGIN_FILE, array( 'KKART_Install', 'install' ) );
		register_shutdown_function( array( $this, 'log_errors' ) );

		add_action( 'plugins_loaded', array( $this, 'on_plugins_loaded' ), -1 );
		add_action( 'admin_notices', array( $this, 'build_dependencies_notice' ) );
		add_action( 'after_setup_theme', array( $this, 'setup_environment' ) );
		add_action( 'after_setup_theme', array( $this, 'include_template_functions' ), 11 );
		add_action( 'init', array( $this, 'init' ), 0 );
		add_action( 'init', array( 'KKART_Shortcodes', 'init' ) );
		add_action( 'init', array( 'KKART_Emails', 'init_transactional_emails' ) );
		add_action( 'init', array( $this, 'add_image_sizes' ) );
		add_action( 'init', array( $this, 'load_rest_api' ) );
		add_action( 'switch_blog', array( $this, 'wpdb_table_fix' ), 0 );
		add_action( 'activated_plugin', array( $this, 'activated_plugin' ) );
		add_action( 'deactivated_plugin', array( $this, 'deactivated_plugin' ) );
	}

	/**
	 * Ensures fatal errors are logged so they can be picked up in the status report.
	 *
	 * @since 3.2.0
	 */
	public function log_errors() {
		$error = error_get_last();
		if ( $error && in_array( $error['type'], array( E_ERROR, E_PARSE, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR ), true ) ) {
			$logger = kkart_get_logger();
			$logger->critical(
				/* translators: 1: error message 2: file name and path 3: line number */
				sprintf( __( '%1$s in %2$s on line %3$s', 'kkart' ), $error['message'], $error['file'], $error['line'] ) . PHP_EOL,
				array(
					'source' => 'fatal-errors',
				)
			);
			do_action( 'kkart_shutdown_error', $error );
		}
	}

	/**
	 * Define KKART Constants.
	 */
	private function define_constants() {
		$upload_dir = wp_upload_dir( null, false );

		$this->define( 'KKART_ABSPATH', dirname( KKART_PLUGIN_FILE ) . '/' );
		$this->define( 'KKART_PLUGIN_BASENAME', plugin_basename( KKART_PLUGIN_FILE ) );
		$this->define( 'KKART_VERSION', $this->version );
		$this->define( 'KKART_VERSION', $this->version );
		$this->define( 'KKART_ROUNDING_PRECISION', 6 );
		$this->define( 'KKART_DISCOUNT_ROUNDING_MODE', 2 );
		$this->define( 'KKART_TAX_ROUNDING_MODE', 'yes' === get_option( 'kkart_prices_include_tax', 'no' ) ? 2 : 1 );
		$this->define( 'KKART_DELIMITER', '|' );
		$this->define( 'KKART_LOG_DIR', $upload_dir['basedir'] . '/kkart-logs/' );
		$this->define( 'KKART_SESSION_CACHE_GROUP', 'kkart_session_id' );
		$this->define( 'KKART_TEMPLATE_DEBUG_MODE', false );
		$this->define( 'KKART_NOTICE_MIN_PHP_VERSION', '7.2' );
		$this->define( 'KKART_NOTICE_MIN_WP_VERSION', '5.1' );
		$this->define( 'KKART_PHP_MIN_REQUIREMENTS_NOTICE', 'wp_php_min_requirements_' . KKART_NOTICE_MIN_PHP_VERSION . '_' . KKART_NOTICE_MIN_WP_VERSION );
	}

	/**
	 * Register custom tables within $wpdb object.
	 */
	private function define_tables() {
		global $wpdb;

		// List of tables without prefixes.
		$tables = array(
			'payment_tokenmeta'      => 'kkart_payment_tokenmeta',
			'order_itemmeta'         => 'kkart_order_itemmeta',
			'kkart_product_meta_lookup' => 'kkart_product_meta_lookup',
			'kkart_tax_rate_classes'    => 'kkart_tax_rate_classes',
			'kkart_reserved_stock'      => 'kkart_reserved_stock',
		);

		foreach ( $tables as $name => $table ) {
			$wpdb->$name    = $wpdb->prefix . $table;
			$wpdb->tables[] = $table;
		}
	}

	/**
	 * Define constant if not already set.
	 *
	 * @param string      $name  Constant name.
	 * @param string|bool $value Constant value.
	 */
	private function define( $name, $value ) {
		if ( ! defined( $name ) ) {
			define( $name, $value );
		}
	}

	/**
	 * Returns true if the request is a non-legacy REST API request.
	 *
	 * Legacy REST requests should still run some extra code for backwards compatibility.
	 *
	 * @todo: replace this function once core WP function is available: https://core.trac.wordpress.org/ticket/42061.
	 *
	 * @return bool
	 */
	public function is_rest_api_request() {
		if ( empty( $_SERVER['REQUEST_URI'] ) ) {
			return false;
		}

		$rest_prefix         = trailingslashit( rest_get_url_prefix() );
		$is_rest_api_request = ( false !== strpos( $_SERVER['REQUEST_URI'], $rest_prefix ) ); // phpcs:disable WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

		return apply_filters( 'kkart_is_rest_api_request', $is_rest_api_request );
	}

	/**
	 * Load REST API.
	 */
	public function load_rest_api() {
		\Automattic\Kkart\RestApi\Server::instance()->init();
	}

	/**
	 * What type of request is this?
	 *
	 * @param  string $type admin, ajax, cron or frontend.
	 * @return bool
	 */
	private function is_request( $type ) {
		switch ( $type ) {
			case 'admin':
				return is_admin();
			case 'ajax':
				return defined( 'DOING_AJAX' );
			case 'cron':
				return defined( 'DOING_CRON' );
			case 'frontend':
				return ( ! is_admin() || defined( 'DOING_AJAX' ) ) && ! defined( 'DOING_CRON' ) && ! $this->is_rest_api_request();
		}
	}

	/**
	 * Include required core files used in admin and on the frontend.
	 */
	public function includes() {
		/**
		 * Class autoloader.
		 */
		include_once KKART_ABSPATH . 'includes/class-kkart-autoloader.php';

		/**
		 * Interfaces.
		 */
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-abstract-order-data-store-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-coupon-data-store-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-customer-data-store-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-customer-download-data-store-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-customer-download-log-data-store-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-object-data-store-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-order-data-store-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-order-item-data-store-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-order-item-product-data-store-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-order-item-type-data-store-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-order-refund-data-store-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-payment-token-data-store-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-product-data-store-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-product-variable-data-store-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-shipping-zone-data-store-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-logger-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-log-handler-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-webhooks-data-store-interface.php';
		include_once KKART_ABSPATH . 'includes/interfaces/class-kkart-queue-interface.php';

		/**
		 * Core traits.
		 */
		include_once KKART_ABSPATH . 'includes/traits/trait-kkart-item-totals.php';

		/**
		 * Abstract classes.
		 */
		include_once KKART_ABSPATH . 'includes/abstracts/abstract-kkart-data.php';
		include_once KKART_ABSPATH . 'includes/abstracts/abstract-kkart-object-query.php';
		include_once KKART_ABSPATH . 'includes/abstracts/abstract-kkart-payment-token.php';
		include_once KKART_ABSPATH . 'includes/abstracts/abstract-kkart-product.php';
		include_once KKART_ABSPATH . 'includes/abstracts/abstract-kkart-order.php';
		include_once KKART_ABSPATH . 'includes/abstracts/abstract-kkart-settings-api.php';
		include_once KKART_ABSPATH . 'includes/abstracts/abstract-kkart-shipping-method.php';
		include_once KKART_ABSPATH . 'includes/abstracts/abstract-kkart-payment-gateway.php';
		include_once KKART_ABSPATH . 'includes/abstracts/abstract-kkart-integration.php';
		include_once KKART_ABSPATH . 'includes/abstracts/abstract-kkart-log-handler.php';
		include_once KKART_ABSPATH . 'includes/abstracts/abstract-kkart-deprecated-hooks.php';
		include_once KKART_ABSPATH . 'includes/abstracts/abstract-kkart-session.php';
		include_once KKART_ABSPATH . 'includes/abstracts/abstract-kkart-privacy.php';

		/**
		 * Core classes.
		 */
		include_once KKART_ABSPATH . 'includes/kkart-core-functions.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-datetime.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-post-types.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-install.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-geolocation.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-download-handler.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-comments.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-post-data.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-ajax.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-emails.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-data-exception.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-query.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-meta-data.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-order-factory.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-order-query.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-product-factory.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-product-query.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-payment-tokens.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-shipping-zone.php';
		include_once KKART_ABSPATH . 'includes/gateways/class-kkart-payment-gateway-cc.php';
		include_once KKART_ABSPATH . 'includes/gateways/class-kkart-payment-gateway-echeck.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-countries.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-integrations.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-cache-helper.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-https.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-deprecated-action-hooks.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-deprecated-filter-hooks.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-background-emailer.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-discounts.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-cart-totals.php';
		include_once KKART_ABSPATH . 'includes/customizer/class-kkart-shop-customizer.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-regenerate-images.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-privacy.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-structured-data.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-shortcodes.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-logger.php';
		include_once KKART_ABSPATH . 'includes/queue/class-kkart-action-queue.php';
		include_once KKART_ABSPATH . 'includes/queue/class-kkart-queue.php';
		include_once KKART_ABSPATH . 'includes/admin/marketplace-suggestions/class-kkart-marketplace-updater.php';

		/**
		 * Data stores - used to store and retrieve CRUD object data from the database.
		 */
		include_once KKART_ABSPATH . 'includes/class-kkart-data-store.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-data-store-wp.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-coupon-data-store-cpt.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-product-data-store-cpt.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-product-grouped-data-store-cpt.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-product-variable-data-store-cpt.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-product-variation-data-store-cpt.php';
		include_once KKART_ABSPATH . 'includes/data-stores/abstract-kkart-order-item-type-data-store.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-order-item-data-store.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-order-item-coupon-data-store.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-order-item-fee-data-store.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-order-item-product-data-store.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-order-item-shipping-data-store.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-order-item-tax-data-store.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-payment-token-data-store.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-customer-data-store.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-customer-data-store-session.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-customer-download-data-store.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-customer-download-log-data-store.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-shipping-zone-data-store.php';
		include_once KKART_ABSPATH . 'includes/data-stores/abstract-kkart-order-data-store-cpt.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-order-data-store-cpt.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-order-refund-data-store-cpt.php';
		include_once KKART_ABSPATH . 'includes/data-stores/class-kkart-webhook-data-store.php';

		/**
		 * REST API.
		 */
		include_once KKART_ABSPATH . 'includes/legacy/class-kkart-legacy-api.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-api.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-rest-authentication.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-rest-exception.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-auth.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-register-wp-admin-settings.php';

		/**
		 * KKARTCOM Site.
		 */
		include_once KKART_ABSPATH . 'includes/wccom-site/class-kkart-wccom-site.php';

		/**
		 * Libraries and packages.
		 */
		include_once KKART_ABSPATH . 'packages/action-scheduler/action-scheduler.php';

		if ( defined( 'WP_CLI' ) && WP_CLI ) {
			include_once KKART_ABSPATH . 'includes/class-kkart-cli.php';
		}

		if ( $this->is_request( 'admin' ) ) {
			include_once KKART_ABSPATH . 'includes/admin/class-kkart-admin.php';
		}

		if ( $this->is_request( 'frontend' ) ) {
			$this->frontend_includes();
		}

		if ( $this->is_request( 'cron' ) && 'yes' === get_option( 'kkart_allow_tracking', 'no' ) ) {
			include_once KKART_ABSPATH . 'includes/class-kkart-tracker.php';
		}

		$this->theme_support_includes();
		$this->query = new KKART_Query();
		$this->api   = new KKART_API();
		$this->api->init();
	}

	/**
	 * Include classes for theme support.
	 *
	 * @since 3.3.0
	 */
	private function theme_support_includes() {
		if ( kkart_is_wp_default_theme_active() ) {
			switch ( get_template() ) {
				case 'twentyten':
					include_once KKART_ABSPATH . 'includes/theme-support/class-kkart-twenty-ten.php';
					break;
				case 'twentyeleven':
					include_once KKART_ABSPATH . 'includes/theme-support/class-kkart-twenty-eleven.php';
					break;
				case 'twentytwelve':
					include_once KKART_ABSPATH . 'includes/theme-support/class-kkart-twenty-twelve.php';
					break;
				case 'twentythirteen':
					include_once KKART_ABSPATH . 'includes/theme-support/class-kkart-twenty-thirteen.php';
					break;
				case 'twentyfourteen':
					include_once KKART_ABSPATH . 'includes/theme-support/class-kkart-twenty-fourteen.php';
					break;
				case 'twentyfifteen':
					include_once KKART_ABSPATH . 'includes/theme-support/class-kkart-twenty-fifteen.php';
					break;
				case 'twentysixteen':
					include_once KKART_ABSPATH . 'includes/theme-support/class-kkart-twenty-sixteen.php';
					break;
				case 'twentyseventeen':
					include_once KKART_ABSPATH . 'includes/theme-support/class-kkart-twenty-seventeen.php';
					break;
				case 'twentynineteen':
					include_once KKART_ABSPATH . 'includes/theme-support/class-kkart-twenty-nineteen.php';
					break;
				case 'twentytwenty':
					include_once KKART_ABSPATH . 'includes/theme-support/class-kkart-twenty-twenty.php';
					break;
				case 'twentytwentyone':
					include_once KKART_ABSPATH . 'includes/theme-support/class-kkart-twenty-twenty-one.php';
					break;
			}
		}
	}

	/**
	 * Include required frontend files.
	 */
	public function frontend_includes() {
		include_once KKART_ABSPATH . 'includes/kkart-cart-functions.php';
		include_once KKART_ABSPATH . 'includes/kkart-notice-functions.php';
		include_once KKART_ABSPATH . 'includes/kkart-template-hooks.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-template-loader.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-frontend-scripts.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-form-handler.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-cart.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-tax.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-shipping-zones.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-customer.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-embed.php';
		include_once KKART_ABSPATH . 'includes/class-kkart-session-handler.php';
	}

	/**
	 * Function used to Init Kkart Template Functions - This makes them pluggable by plugins and themes.
	 */
	public function include_template_functions() {
		include_once KKART_ABSPATH . 'includes/kkart-template-functions.php';
	}

	/**
	 * Init Kkart when WordPress Initialises.
	 */
	public function init() {
		// Before init action.
		do_action( 'before_kkart_init' );

		// Set up localisation.
		$this->load_plugin_textdomain();

		// Load class instances.
		$this->product_factory                     = new KKART_Product_Factory();
		$this->order_factory                       = new KKART_Order_Factory();
		$this->countries                           = new KKART_Countries();
		$this->integrations                        = new KKART_Integrations();
		$this->structured_data                     = new KKART_Structured_Data();
		$this->deprecated_hook_handlers['actions'] = new KKART_Deprecated_Action_Hooks();
		$this->deprecated_hook_handlers['filters'] = new KKART_Deprecated_Filter_Hooks();

		// Classes/actions loaded for the frontend and for ajax requests.
		if ( $this->is_request( 'frontend' ) ) {
			kkart_load_cart();
		}

		$this->load_webhooks();

		// Init action.
		do_action( 'kkart_init' );
	}

	/**
	 * Load Localisation files.
	 *
	 * Note: the first-loaded translation file overrides any following ones if the same translation is present.
	 *
	 * Locales found in:
	 *      - WP_LANG_DIR/kkart/kkart-LOCALE.mo
	 *      - WP_LANG_DIR/plugins/kkart-LOCALE.mo
	 */
	public function load_plugin_textdomain() {
		if ( function_exists( 'determine_locale' ) ) {
			$locale = determine_locale();
		} else {
			// @todo Remove when start supporting WP 5.0 or later.
			$locale = is_admin() ? get_user_locale() : get_locale();
		}

		$locale = apply_filters( 'plugin_locale', $locale, 'kkart' );

		unload_textdomain( 'kkart' );
		load_textdomain( 'kkart', WP_LANG_DIR . '/kkart/kkart-' . $locale . '.mo' );
		load_plugin_textdomain( 'kkart', false, plugin_basename( dirname( KKART_PLUGIN_FILE ) ) . '/i18n/languages' );
	}

	/**
	 * Ensure theme and server variable compatibility and setup image sizes.
	 */
	public function setup_environment() {
		/**
		 * KKART_TEMPLATE_PATH constant.
		 *
		 * @deprecated 2.2 Use KKART()->template_path() instead.
		 */
		$this->define( 'KKART_TEMPLATE_PATH', $this->template_path() );

		$this->add_thumbnail_support();
	}

	/**
	 * Ensure post thumbnail support is turned on.
	 */
	private function add_thumbnail_support() {
		if ( ! current_theme_supports( 'post-thumbnails' ) ) {
			add_theme_support( 'post-thumbnails' );
		}
		add_post_type_support( 'product', 'thumbnail' );
	}

	/**
	 * Add KKART Image sizes to WP.
	 *
	 * As of 3.3, image sizes can be registered via themes using add_theme_support for kkart
	 * and defining an array of args. If these are not defined, we will use defaults. This is
	 * handled in kkart_get_image_size function.
	 *
	 * 3.3 sizes:
	 *
	 * kkart_thumbnail - Used in product listings. We assume these work for a 3 column grid layout.
	 * kkart_single - Used on single product pages for the main image.
	 *
	 * @since 2.3
	 */
	public function add_image_sizes() {
		$thumbnail         = kkart_get_image_size( 'thumbnail' );
		$single            = kkart_get_image_size( 'single' );
		$gallery_thumbnail = kkart_get_image_size( 'gallery_thumbnail' );

		add_image_size( 'kkart_thumbnail', $thumbnail['width'], $thumbnail['height'], $thumbnail['crop'] );
		add_image_size( 'kkart_single', $single['width'], $single['height'], $single['crop'] );
		add_image_size( 'kkart_gallery_thumbnail', $gallery_thumbnail['width'], $gallery_thumbnail['height'], $gallery_thumbnail['crop'] );

		/**
		 * Legacy image sizes.
		 *
		 * @deprecated 3.3.0 These sizes will be removed in 4.6.0.
		 */
		add_image_size( 'shop_catalog', $thumbnail['width'], $thumbnail['height'], $thumbnail['crop'] );
		add_image_size( 'shop_single', $single['width'], $single['height'], $single['crop'] );
		add_image_size( 'shop_thumbnail', $gallery_thumbnail['width'], $gallery_thumbnail['height'], $gallery_thumbnail['crop'] );
	}

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

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

	/**
	 * Get the template path.
	 *
	 * @return string
	 */
	public function template_path() {
		return apply_filters( 'kkart_template_path', 'kkart/' );
	}

	/**
	 * Get Ajax URL.
	 *
	 * @return string
	 */
	public function ajax_url() {
		return admin_url( 'admin-ajax.php', 'relative' );
	}

	/**
	 * Return the KKART API URL for a given request.
	 *
	 * @param string    $request Requested endpoint.
	 * @param bool|null $ssl     If should use SSL, null if should auto detect. Default: null.
	 * @return string
	 */
	public function api_request_url( $request, $ssl = null ) {
		if ( is_null( $ssl ) ) {
			$scheme = wp_parse_url( home_url(), PHP_URL_SCHEME );
		} elseif ( $ssl ) {
			$scheme = 'https';
		} else {
			$scheme = 'http';
		}

		if ( strstr( get_option( 'permalink_structure' ), '/index.php/' ) ) {
			$api_request_url = trailingslashit( home_url( '/index.php/kkart-api/' . $request, $scheme ) );
		} elseif ( get_option( 'permalink_structure' ) ) {
			$api_request_url = trailingslashit( home_url( '/kkart-api/' . $request, $scheme ) );
		} else {
			$api_request_url = add_query_arg( 'kkart-api', $request, trailingslashit( home_url( '', $scheme ) ) );
		}

		return esc_url_raw( apply_filters( 'kkart_api_request_url', $api_request_url, $request, $ssl ) );
	}

	/**
	 * Load & enqueue active webhooks.
	 *
	 * @since 2.2
	 */
	private function load_webhooks() {

		if ( ! is_blog_installed() ) {
			return;
		}

		/**
		 * Hook: kkart_load_webhooks_limit.
		 *
		 * @since 3.6.0
		 * @param int $limit Used to limit how many webhooks are loaded. Default: no limit.
		 */
		$limit = apply_filters( 'kkart_load_webhooks_limit', null );

		kkart_load_webhooks( 'active', $limit );
	}

	/**
	 * Initialize the customer and cart objects and setup customer saving on shutdown.
	 *
	 * @since 3.6.4
	 * @return void
	 */
	public function initialize_cart() {
		// Cart needs customer info.
		if ( is_null( $this->customer ) || ! $this->customer instanceof KKART_Customer ) {
			$this->customer = new KKART_Customer( get_current_user_id(), true );
			// Customer should be saved during shutdown.
			add_action( 'shutdown', array( $this->customer, 'save' ), 10 );
		}
		if ( is_null( $this->cart ) || ! $this->cart instanceof KKART_Cart ) {
			$this->cart = new KKART_Cart();
		}
	}

	/**
	 * Initialize the session class.
	 *
	 * @since 3.6.4
	 * @return void
	 */
	public function initialize_session() {
		// Session class, handles session data for users - can be overwritten if custom handler is needed.
		$session_class = apply_filters( 'kkart_session_handler', 'KKART_Session_Handler' );
		if ( is_null( $this->session ) || ! $this->session instanceof $session_class ) {
			$this->session = new $session_class();
			$this->session->init();
		}
	}

	/**
	 * Set tablenames inside WPDB object.
	 */
	public function wpdb_table_fix() {
		$this->define_tables();
	}

	/**
	 * Ran when any plugin is activated.
	 *
	 * @since 3.6.0
	 * @param string $filename The filename of the activated plugin.
	 */
	public function activated_plugin( $filename ) {
		include_once dirname( __FILE__ ) . '/admin/helper/class-kkart-helper.php';

		KKART_Helper::activated_plugin( $filename );
	}

	/**
	 * Ran when any plugin is deactivated.
	 *
	 * @since 3.6.0
	 * @param string $filename The filename of the deactivated plugin.
	 */
	public function deactivated_plugin( $filename ) {
		include_once dirname( __FILE__ ) . '/admin/helper/class-kkart-helper.php';

		KKART_Helper::deactivated_plugin( $filename );
	}

	/**
	 * Get queue instance.
	 *
	 * @return KKART_Queue_Interface
	 */
	public function queue() {
		return KKART_Queue::instance();
	}

	/**
	 * Get Checkout Class.
	 *
	 * @return KKART_Checkout
	 */
	public function checkout() {
		return KKART_Checkout::instance();
	}

	/**
	 * Get gateways class.
	 *
	 * @return KKART_Payment_Gateways
	 */
	public function payment_gateways() {
		return KKART_Payment_Gateways::instance();
	}

	/**
	 * Get shipping class.
	 *
	 * @return KKART_Shipping
	 */
	public function shipping() {
		return KKART_Shipping::instance();
	}

	/**
	 * Email Class.
	 *
	 * @return KKART_Emails
	 */
	public function mailer() {
		return KKART_Emails::instance();
	}

	/**
	 * Check if plugin assets are built and minified
	 *
	 * @return bool
	 */
	public function build_dependencies_satisfied() {
		// Check if we have compiled CSS.
		if ( ! file_exists( KKART()->plugin_path() . '/assets/css/admin.css' ) ) {
			return false;
		}

		// Check if we have minified JS.
		if ( ! file_exists( KKART()->plugin_path() . '/assets/js/admin/kkart_admin.min.js' ) ) {
			return false;
		}

		return true;
	}

	/**
	 * Output a admin notice when build dependencies not met.
	 *
	 * @return void
	 */
	public function build_dependencies_notice() {
		if ( $this->build_dependencies_satisfied() ) {
			return;
		}

		$message_one = __( 'You have installed a development version of Kkart which requires files to be built and minified. From the plugin directory, run <code>grunt assets</code> to build and minify assets.', 'kkart' );
		$message_two = sprintf(
			/* translators: 1: URL of WordPress.org Repository 2: URL of the GitHub Repository release page */
			__( 'Or you can download a pre-built version of the plugin from the <a href="%1$s">WordPress.org repository</a> or by visiting <a href="%2$s">the releases page in the GitHub repository</a>.', 'kkart' ),
			'https://wordpress.org/plugins/kkart/',
			'https://github.com/kkart/kkart/releases'
		);
		printf( '<div class="error"><p>%s %s</p></div>', $message_one, $message_two ); /* WPCS: xss ok. */
	}

	/**
	 * Is the Kkart Admin actively included in the Kkart core?
	 * Based on presence of a basic KKART Admin function.
	 *
	 * @return boolean
	 */
	public function is_kkart_admin_active() {
		return function_exists( 'kkart_admin_url' );
	}

	/**
	 * Call a user function. This should be used to execute any non-idempotent function, especially
	 * those in the `includes` directory or provided by WordPress.
	 *
	 * This method can be useful for unit tests, since functions called using this method
	 * can be easily mocked by using KKART_Unit_Test_Case::register_legacy_proxy_function_mocks.
	 *
	 * @param string $function_name The function to execute.
	 * @param mixed  ...$parameters The parameters to pass to the function.
	 *
	 * @return mixed The result from the function.
	 *
	 * @since 4.4
	 */
	public function call_function( $function_name, ...$parameters ) {
		return kkart_get_container()->get( LegacyProxy::class )->call_function( $function_name, ...$parameters );
	}

	/**
	 * Call a static method in a class. This should be used to execute any non-idempotent method in classes
	 * from the `includes` directory.
	 *
	 * This method can be useful for unit tests, since methods called using this method
	 * can be easily mocked by using KKART_Unit_Test_Case::register_legacy_proxy_static_mocks.
	 *
	 * @param string $class_name The name of the class containing the method.
	 * @param string $method_name The name of the method.
	 * @param mixed  ...$parameters The parameters to pass to the method.
	 *
	 * @return mixed The result from the method.
	 *
	 * @since 4.4
	 */
	public function call_static( $class_name, $method_name, ...$parameters ) {
		return kkart_get_container()->get( LegacyProxy::class )->call_static( $class_name, $method_name, ...$parameters );
	}

	/**
	 * Gets an instance of a given legacy class.
	 * This must not be used to get instances of classes in the `src` directory.
	 *
	 * This method can be useful for unit tests, since objects obtained using this method
	 * can be easily mocked by using KKART_Unit_Test_Case::register_legacy_proxy_class_mocks.
	 *
	 * @param string $class_name The name of the class to get an instance for.
	 * @param mixed  ...$args Parameters to be passed to the class constructor or to the appropriate internal 'get_instance_of_' method.
	 *
	 * @return object The instance of the class.
	 * @throws \Exception The requested class belongs to the `src` directory, or there was an error creating an instance of the class.
	 *
	 * @since 4.4
	 */
	public function get_instance_of( string $class_name, ...$args ) {
		return kkart_get_container()->get( LegacyProxy::class )->get_instance_of( $class_name, ...$args );
	}
}
