<?php
/**
 * Plugin Name: Approve Orders
 * Plugin URI: https://neebplugins.com/plugin/approve-orders
 * Description: Adds an order approval, cancellation workflow to your WooCommerce store.
 * Version: 1.0.7
 * Author: NeeB Plugins
 * Author URI: https://neebplugins.com
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: approve-orders
 * Domain Path: /languages
 * Requires PHP: 7.4
 * Requires at least: 6.2
 * WC requires at least: 8.2
 * WC tested up to: 10.1
 * Requires Plugins: woocommerce
 *
 * @package Approve_Orders
 */

use ApproveOrders\Backend as AOFWC_Backend;
use ApproveOrders\Frontend as AOFWC_Frontend;
use ApproveOrders\Rest_API as AOFWC_Rest_API;
use ApproveOrders\Modules\Rules as AOFWC_Rules;
use ApproveOrders\Compatibility\PreOrderBlocksSupport as AOFWC_BlocksSupport;
use ApproveOrders\Traits\Get_Instance;

// Exit if accessed directly.
if ( ! defined( 'WPINC' ) ) {
	exit;
}

// Your code starts here.

defined( 'AOFWC_VERSION' ) || define( 'AOFWC_VERSION', '1.0.7' );
defined( 'AOFWC_FILE' ) || define( 'AOFWC_FILE', __FILE__ );
defined( 'AOFWC_BASE' ) || define( 'AOFWC_BASE', plugin_basename( AOFWC_FILE ) );
defined( 'AOFWC_DIR' ) || define( 'AOFWC_DIR', plugin_dir_path( AOFWC_FILE ) );
defined( 'AOFWC_URL' ) || define( 'AOFWC_URL', plugins_url( '/', AOFWC_FILE ) );
defined( 'AOFWC_PLUGIN_SLUG' ) || define( 'AOFWC_PLUGIN_SLUG', 'aofwc-settings' );
defined( 'AOFWC_KB_URL' ) || define( 'AOFWC_KB_URL', 'https://neebplugins.com/docs/approve-orders/' );
defined( 'AOFWC_UPGRADE_URL' ) || define( 'AOFWC_UPGRADE_URL', 'https://neebplugins.com/plugin/approve-orders/#try-now' );

// Include dependencies
if ( file_exists( AOFWC_DIR . 'vendor/autoload.php' ) ) {
	require_once AOFWC_DIR . 'vendor/autoload.php';
} else {
	wp_die( 'Plugin dependencies not installed!!!' );
}

if ( ! function_exists( 'ao_fs' ) ) {
	// Create a helper function for easy SDK access.
	function ao_fs() {
		global $ao_fs;

		if ( ! isset( $ao_fs ) ) {

			// Freemius SDK loaded via composer.

			$ao_fs = fs_dynamic_init(
				array(
					'id'                             => '16430',
					'slug'                           => 'approve-orders',
					'type'                           => 'plugin',
					'public_key'                     => 'pk_99df04bd377ed9db2761480450c5b',
					'is_premium'                     => true,
					'has_addons'                     => true,
					'has_paid_plans'                 => true,
					'is_org_compliant'               => true,
					'has_affiliation'                => false,
					'trial'                          => array(
						'days'               => 7,
						'is_require_payment' => false,
					),
					'menu'                           => array(
						'slug'       => 'approve-orders',
						'first-path' => 'admin.php?page=approve-orders',
						'support'    => false,
						'contact'    => true,
					),
					'is_live'                        => true,
					'anonymous_mode'                 => true,
					// Bundle Details
					'bundle_id'                      => 18627,
					'bundle_public_key'              => 'pk_39c816010c77cc3631117080aaac2',
					'bundle_license_auto_activation' => true,
				)
			);
		}

		return $ao_fs;
	}

	// Init Freemius.
	ao_fs();
	// Signal that SDK was initiated.
	do_action( 'ao_fs_loaded' );

	function aofwc_plugin_icon() {
		return AOFWC_DIR . 'assets/img/icon.png';
	}

	ao_fs()->add_filter( 'plugin_icon', 'aofwc_plugin_icon' );

	function ao_fs_submenu_visibility_handler( $is_visible, $id ) {
		// phpcs:ignore These are the options for $id: "support", "contact", "addons", "pricing"
		if ( 'addons' === $id ) {
			$is_visible = ao_fs()->is_paying_or_trial();
		}

		return $is_visible;
	}

	// Change Pricing URL
	ao_fs()->add_filter(
		'pricing_url',
		function ( $url ) {
			$url = AOFWC_UPGRADE_URL;
			return esc_url( $url );
		}
	);

	ao_fs()->add_filter( 'is_submenu_visible', 'ao_fs_submenu_visibility_handler', 10, 2 );
}

/**
 * The main plugin class for Approve Orders.
 */
final class ApproveOrders {

	use Get_Instance;

	/**
	 * Initialize the plugin.
	 */
	public function __construct() {

		// Hook into the 'wp' action to load the frontend class
		add_action( 'init', array( $this, 'load_plugin' ) );

		// Hook into the 'plugins_loaded' action to load the backend class
		add_action( 'plugins_loaded', array( $this, 'load_backend' ) );

		// WooCommerce Compatibilities
		add_action( 'before_woocommerce_init', array( $this, 'hpos_blocks_compatible' ) );

		// Plugin action links
		add_action( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'action_links' ) );
		// Load wc email classes on woocommerce_init
		add_action( 'woocommerce_init', array( $this, 'load_wc_email_class' ) );
		// Pre Plugin Activate Check
		add_action( 'pre_plugin_activate', array( $this, 'prevent_plugin_activation_on_multisite' ) );
		// Hook the custom function to the 'woocommerce_blocks_loaded' action
		add_action( 'woocommerce_blocks_loaded', array( $this, 'approve_order_payment_method_type' ) );
		// Add WooCommerce Account end point
		add_action( 'init', array( $this, 'my_account_endpoint' ) );
		add_filter( 'query_vars', array( $this, 'add_query_vars' ) );
	}

	/**
	 * Load the backend class.
	 */
	public function load_backend() {
		// Run plugin if the site is not Multisite
		if ( ! is_multisite() ) {
			// Initialize the back-end functionality
			$backend = new AOFWC_Backend();
			$backend->init();

			// Init API
			AOFWC_Rest_API::get_instance();

			add_filter(
				'woocommerce_payment_gateways',
				function ( $gateways ) {
					$gateways[] = 'ApproveOrders\Modules\PrePayGateway';
					return $gateways;
				}
			);

		} else {
			add_action( 'admin_notices', array( $this, 'multisite_admin_notification' ) );
		}
	}

	/**
	 * Load the frontend class.
	 */
	public function load_plugin() {
		// Run plugin if the site is not Multisite
		if ( ! is_multisite() ) {
			// Initialize the front-end functionality
			$frontend = new AOFWC_Frontend();
			$frontend->init();
		}
	}

	/**
	 * Load the HPOS Compatibility class.
	 */
	public function hpos_blocks_compatible() {
		// Define WooCommerce Compatibilities Here
		if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
			// HPOS Compatibility
			\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', AOFWC_FILE, true );
			// Checkout Block Compatibility
			\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', __FILE__, true );
		}
	}

	/**
	 * Plugin Action links
	 */
	public function action_links( $links ) {
		$links = array_merge(
			array(
				'<a href="' . esc_url( admin_url( 'admin.php?page=approve-orders' ) ) . '">' . esc_html( 'Settings', 'approve-orders' ) . '</a>',
				'<a target="blank" href="' . esc_url( 'https://neebplugins.com/support/' ) . '">' . __( 'Support Desk', 'approve-orders' ) . '</a>',
			),
			$links
		);
		return $links;
	}

	/**
	 * Load WC Email Classes
	 */
	public function load_wc_email_class() {
		if ( ! class_exists( 'WC_Email' ) ) {
			include_once WC()->plugin_path() . '/includes/emails/class-wc-email.php'; // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingCustomFunction
		}
	}

	/**
	 * Multisite admin notification
	 */
	public function multisite_admin_notification() {
		?>
		<div class="notice notice-error">
			<p><?php esc_html_e( 'Multisite Not Supported, Please deactivate Approve Orders plugin', 'approve-orders' ); ?> .</p>
		</div>
		<?php
	}

	/**
	 * Prevent plugin activation on multisite
	 *
	 * @param string $plugin The plugin being activated.
	 * @param bool   $network_wide Whether the activation is network-wide.
	 * @return void
	 * @since 1.0.0
	 * @access public
	 */
	public static function prevent_plugin_activation_on_multisite() {

		// Flush rewrite rules once on plugin activation.
		flush_rewrite_rules(); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.flush_rewrite_rules_flush_rewrite_rules

		if ( ! ao_fs()->is_paying() ) { // phpcs:ignore
			if ( is_multisite() ) {
				wp_die( 'The "Approve Orders" plugin is not supported on multisite' );
			}
		}
	}

	/**
	 * Approve order payment method type
	 *
	 * @return void
	 * @since 1.0.4
	 * @access public
	 */
	public function approve_order_payment_method_type() {
		// Check if the required class exists
		if ( ! class_exists( 'Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType' ) ) {
			return;
		}

		// Hook the registration function to the 'woocommerce_blocks_payment_method_type_registration' action
		add_action(
			'woocommerce_blocks_payment_method_type_registration',
			function ( Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
				// Register an instance of Pre Order Gateway
				$payment_method_registry->register( new AOFWC_BlocksSupport() );
			}
		);
	}

	/**
	 * Front Process Rules
	 */
	public function front_process_rules( $data_source, $rules = array() ) {

		if ( empty( $rules ) ) {
			$rules = AOFWC_Rest_API::get_instance()->fetch_rules( 0 );
		}

		$processed_rules = AOFWC_Rules::get_instance()->process_rules( $data_source, $rules );

		return $processed_rules;
	}

	/**
	 * Add WooCommerce Account end point
	 *
	 * @param void
	 * @return void
	 *
	 * @since 1.0.4
	 */
	public function my_account_endpoint() {
		add_rewrite_endpoint( 'aofwc-mark', EP_ROOT | EP_PAGES );
	}

	/**
	 * Add query vars
	 *
	 * @param array $vars The list of available payment gateways.
	 * @return array The list of available payment gateways with the PreOrderPay gateway added.
	 *
	 * @since 1.0.4
	 */
	public function add_query_vars( $vars ) {
		$vars[] = 'aofwc-mark';
		return $vars;
	}
}

// Run plugin instance
$plugin_instance = ApproveOrders::get_instance();

register_activation_hook( __FILE__, array( $plugin_instance, 'prevent_plugin_activation_on_multisite' ) );

if ( ! function_exists( 'aofwc_process_rules' ) ) {
	function aofwc_process_rules( $data_source, $rules = array() ) {
		return ApproveOrders::get_instance()->front_process_rules( $data_source, $rules );
	}
}

