<?php
/**
 * File: class-base.php
 *
 * The main plugin file for Wooecho Rewards. This file initializes the Wooecho Rewards plugin.
 *
 * @package ECRE
 * @since 1.0.0
 */

namespace ECRE;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit();

/**
 * The main plugin class for Wooecho Rewards.
 *
 * @since 1.0.0
 */
if ( ! class_exists( 'ECHO_REWARDS' ) ) {
	/**
	 * Sets up and initializes the Wooecho Rewards plugin. This is the main initiation class.
	 *
	 * @since 1.0.0
	 */
	//phpcs:ignore
	final class ECHO_REWARDS {
		/**
		 * Singleton instance of the class.
		 *
		 * @var null|self
		 */
		private static $instance = null;

		/**
		 * Indicates whether the user has a professional (pro) account.
		 *
		 * @var bool
		 */
		public $is_pro = false;

		/**
		 * Indicates whether the current version is the latest professional version.
		 *
		 * @var bool
		 */
		public $is_pro_latest = false;

		/**
		 * Holds the settings configuration for the ECRE order tracking system.
		 *
		 * This property stores various settings retrieved from the database,
		 * such as email templates, discount configurations, and tracking options.
		 *
		 * @var array
		 */
		public $erce_settings = array();

		/**
		 * The default plugin settings used for order tracking behavior.
		 *
		 * @var array
		 */
		public $default_settings = array();

		/**
		 * Indicates whether WooCommerce is activated.
		 *
		 * @var bool
		 */
		public $is_woocommerce_activate = false;

		/**
		 * Class constructor.
		 *
		 * @since 1.0.0
		 */
		private function __construct() {
			register_activation_hook( ECRE_FILE, array( $this, 'ecre_activate' ) );
			$this->erce_settings = get_option( 'ecre_settings', array() );
		}

		/**
		 * Initializes a singleton instance of the plugin.
		 *
		 * @return \ECRE The singleton instance of the Wooecho Rewards plugin.
		 *
		 * @since 1.0.0
		 */
		public static function init() {
			if ( null === self::$instance || ! self::$instance instanceof self ) {
				self::$instance = new self();

				self::$instance->init_plugin();
			}

			return self::$instance;
		}

		/**
		 * Initialize the plugin and set up its components, including assets, admin, and frontend.
		 *
		 * @return void
		 *
		 * @since 1.0.0
		 */
		public function init_plugin() {

			$plugin_list = get_option( 'active_plugins' );

			if ( is_multisite() ) {
				$network_active_plugins = get_site_option( 'active_sitewide_plugins', array() );
				$plugin_list            = array_merge( $plugin_list, array_keys( $network_active_plugins ) );
			}

			$ecre_pro_path    = 'echo-rewards-pro/echo-rewards.php';
			$woocommerce_free = 'woocommerce/woocommerce.php';

			if ( in_array( $woocommerce_free, $plugin_list, true ) ) {
				$this->is_woocommerce_activate = true;
				$this->default_settings        = ecre_default_settings();
			} else {
				// WooCommerce is not installed or activated.
				add_action( 'admin_notices', array( $this, 'ecre_woocommerce_notice' ) );
			}

			add_action( 'init', array( $this, 'ecre_appsero_init_tracker' ) );
			add_action( 'init', array( $this, 'init_classes' ) );
			$this->ecre_wppool_sdk_init();
			add_filter( 'plugin_action_links', array( $this, 'ecre_add_settings_link' ), 11, 2 );

			// Include the base class, which sets up and initializes the plugin.
			add_action( 'admin_init', array( $this, 'ecre_redirect_after_activation' ), 9 );
			add_action( 'init', array( $this, 'ecre_localization_setup' ) );
		}

		/**
		 * Initializes necessary classes based on the current context.
		 *
		 * This method initializes various classes required for different components
		 * of the Echo Rewards plugin, including assets, Ajax handling, admin or frontend
		 * components, coupon generation, string management, and notices.
		 *
		 * @return void
		 */
		public function init_classes() {

			if ( function_exists( 'echo_rewards_pro' ) ) {
				$this->is_pro = echo_rewards_pro()->license_status;
			}

			$plugin_list      = get_option( 'active_plugins' );
			$ecre_pro_path    = 'echo-rewards-pro/echo-rewards.php';
			$is_pro_latest    = false;
			$is_pro_activated = false;

			if ( in_array( $ecre_pro_path, $plugin_list, true ) ) {
				$is_pro_latest    = true;
				$is_pro_activated = true;
			}

			new Ecre_Assets( $this->is_pro, $this->erce_settings, $this->is_woocommerce_activate );

			// Initialize Ajax component for asynchronous actions.
			if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
				new Ecre_Ajax( $this->is_pro, $this->erce_settings );
			}

			new Ecre_Background_Processor();

			new Ecre_Migration_Handler();

			// Depending on context, initialize the Admin or Frontend components.
			if ( is_admin() || defined( 'DOING_CRON' ) ) {
				new Ecre_Admin( $this->erce_settings, $this->is_pro, $this->is_woocommerce_activate );
			}

			if ( $this->is_woocommerce_activate ) {

				if ( ! is_admin() ) {
					if ( ! $is_pro_latest && $is_pro_activated ) {
						return;
					} else {
						new Ecre_Frontend( $this->is_pro, $this->erce_settings, $this->default_settings );
					}
				}

				new Ecre_Order_Tracking( $this->is_pro, $this->default_settings );

				// Initialize referral system classes.
				new Ecre_Tables();

				if ( ! $is_pro_latest && $is_pro_activated ) {
					add_action( 'admin_notices', array( $this, 'echo_rewards_latest_version_notice' ) );
					return;
				}

				$enable_referral_link = isset( $this->erce_settings['enableReferralLink'] ) ? $this->erce_settings['enableReferralLink'] : 'false';

				if ( $enable_referral_link ) {
					new Ecre_ReferralLink();
				}

				new Ecre_Generate_Coupon( $this->erce_settings, $this->is_pro );
				new Ecre_Strings();

				//new Ecre_Notice();

				new Ecre_Shortcodes();

				// Initialize coupon sync handler for manual coupon edits.
				if ( class_exists( '\ECRE\Ecre_Coupon_Sync_Handler' ) ) {
					new Ecre_Coupon_Sync_Handler();
				}

				// If settings are empty, initialize with default settings.
				if ( empty( $this->erce_settings ) ) {
					update_option( 'ecre_settings', ecre_default_settings() );
				}
			}
		}

		/**
		 * Initialize the plugin tracker
		 *
		 * @return void
		 */
		public function ecre_appsero_init_tracker() {
			if ( ! class_exists( '\ECRE\Appsero\Client' ) ) {
				require_once __DIR__ . '/includes/Appsero/Client.php';
			}

			$client = new \ECRE\Appsero\Client( 'ba83e16a-3ead-44a2-8f7a-9232889f1e64', 'EchoRewards', ECRE_FILE );

			// Active insights.
			$client->insights()->init();
		}

		/**
		 * Initialize the wppool sdk
		 *
		 * @return void
		 */
		public function ecre_wppool_sdk_init() {
			// Require WPPOOL SDK files.
			if ( file_exists( ECRE_PATH . '/includes/wppool/class-plugin.php' ) ) {
				require_once ECRE_PATH . '/includes/wppool/class-plugin.php';
			}

			if ( function_exists( 'wppool_plugin_init' ) ) {
				$ecre_free_plugin = wppool_plugin_init( 'echo_rewards', plugin_dir_url( ECRE_FILE ) . '/includes/wppool/background-image.png' );

				if ( $ecre_free_plugin && is_object( $ecre_free_plugin ) && method_exists( $ecre_free_plugin, 'set_campaign' ) ) {
					$to       = '2025-12-04 16:00:00';
					$from     = '2025-11-17 16:00:00';
					$cta_text = 'Grab Your Deals';

					$campain_image = plugin_dir_url( ECRE_FILE ) . '/includes/wppool/bfcm.png';

					$button_link = 'https://lnk.wppool.dev/wLYGc5W';
					$ecre_free_plugin->set_campaign( $campain_image, $to, $from, $cta_text, $button_link );
				}
			}
		}

		/**
		 * Add a settings link beside the plugin deactivate button.
		 *
		 * @param array  $actions    An array of plugin action links.
		 * @param string $plugin_file Path to the main plugin file.
		 * @return array
		 */
		public function ecre_add_settings_link( $actions, $plugin_file ) {
			// Check if the current plugin is the one you want.
			if ( 'echo-rewards/echo-rewards.php' === $plugin_file ) {
				$settings_link = '<a href="' . admin_url( 'admin.php?page=echo-rewards' ) . '">' . esc_html__( 'Settings', 'echo-rewards' ) . '</a>';

				// Check if the "Settings" link is not already present in actions.
				if ( ! in_array( $settings_link, $actions, true ) ) {
					array_push( $actions, $settings_link ); // Add your settings link.
				}
			}

			return $actions;
		}

		/**
		 * Perform tasks upon plugin activation.
		 *
		 * @return void
		 *
		 * @since 1.0.0
		 */
		public function ecre_activate() {
			if ( is_multisite() ) {
				// Get all sites in the network.
				$sites = get_sites();

				foreach ( $sites as $site ) {
					switch_to_blog( $site->blog_id );
					update_option( 'redirect_to_ecre_page', absint( 1 ) );
					// Review notice options after installation of 7 days.
					// add_option( 'ecre_review_notice', 0 );
					// add_option( 'ecre_deafult_review_notice_interval', ( time() + 7 * 24 * 60 * 60 ) );.

					// Upgrade notice options.
					// add_option( 'ecre_upgrade_notice', 0 );
					// add_option( 'ecre_deafult_upgrade_notice_interval', ( time() + 10 * 24 * 60 * 60 ) );.

					// Affiliate notice options.
					// add_option( 'ecre_affiliate_notice', 0 );
					// add_option( 'ecre_deafult_affiliate_notice_interval', ( time() + 14 * 24 * 60 * 60 ) );.

					restore_current_blog();
				}
			} else {

				// Review notice options after installation of 7 days.
				// add_option( 'ecre_review_notice', 0 );
				// add_option( 'ecre_deafult_review_notice_interval', ( time() + 7 * 24 * 60 * 60 ) );.

				// Upgrade notice options.
				// add_option( 'ecre_upgrade_notice', 0 );
				// add_option( 'ecre_deafult_upgrade_notice_interval', ( time() + 10 * 24 * 60 * 60 ) );.

				// Affiliate notice options.
				// add_option( 'ecre_affiliate_notice', 0 );
				// add_option( 'ecre_deafult_affiliate_notice_interval', ( time() + 14 * 24 * 60 * 60 ) );.
				update_option( 'redirect_to_ecre_page', absint( 1 ) );
			}

			// If settings are empty, initialize with default settings.
			if ( empty( $this->erce_settings ) ) {
				update_option( 'ecre_settings', ecre_default_settings() );
			}

			// Record first install version if not already recorded.
			if ( ! get_option( 'ecre_first_install_version' ) ) {
				add_option( 'ecre_first_install_version', ECRE_VERSION );
				add_option( 'ecre_install_date', current_time( 'mysql' ) );
			}

			// Always update current version.
			update_option( 'ecre_current_version', ECRE_VERSION );
		}

		/**
		 * Initialize plugin for localization
		 *
		 * @return void
		 * @since 1.2.0
		 */
		public function ecre_localization_setup() {
			load_plugin_textdomain( 'echo-rewards', false, ECRE_PATH . '/languages/' );
		}

		/**
		 * Redirect to the desired page upon activation.
		 *
		 * @return void
		 *
		 * @since 1.0.0
		 */
		public function ecre_redirect_after_activation() {
			$redirect_to_ecre_page = get_option( 'redirect_to_ecre_page', 0 );

			if ( 1 === absint( $redirect_to_ecre_page ) ) {
				update_option( 'redirect_to_ecre_page', absint( 0 ) );
				wp_safe_redirect( admin_url( 'admin.php?page=echo-rewards' ) );
				exit;
			}
		}

		/**
		 * Displays admin notices related to Echo Rewards and WooCommerce.
		 *
		 * This function checks whether WooCommerce is installed and activated.
		 * If not, it displays an error notice prompting the user to install & activate WooCommerce to enable Echo Rewards functionality.
		 * If installed but not activated, it displays a warning notice asking the user to activate WooCommerce
		 * to enable the full functionality of Echo Rewards.
		 *
		 * @return void
		 */
		public function ecre_woocommerce_notice() {
			$woocommerce_plugin_path = WP_PLUGIN_DIR . '/woocommerce/woocommerce.php';

			if ( ! file_exists( $woocommerce_plugin_path ) ) {
				?>
			<div class="notice notice-error is-dismissible">
				<p><?php esc_html_e( 'EchoRewards depends on WooCommerce. Please ', 'echo-rewards' ); ?>
					<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'update.php?action=install-plugin&plugin=woocommerce' ), 'install-plugin_woocommerce' ) ); ?>">
						<?php esc_html_e( 'install & activate WooCommerce', 'echo-rewards' ); ?>
					</a>
					<?php esc_html_e( 'to enable EchoRewards functionality.', 'echo-rewards' ); ?>
				</p>
			</div>

				<?php
			} else {
				?>
			<div class="notice notice-warning is-dismissible">
				<p>
				<?php
					esc_html_e( 'WooCommerce is installed but not yet activated. To utilize EchoRewards, please activate WooCommerce.', 'echo-rewards' );
				?>
				</p>
			</div>
				<?php
			}
		}

		/**
		 * Echo rewards free latest version missing notice.
		 *
		 * @return void
		 *
		 * @since 1.0.0
		 */
		public function echo_rewards_latest_version_notice() {
			// Check if we're on the specific admin page.
			$current_screen = get_current_screen();
			if ( isset( $current_screen->id ) && 'toplevel_page_echo-rewards' === $current_screen->id ) {
				return;
			}

			$notice = sprintf(
				// Translators: 1: Echo Rewards free plugin, 2: download link.
				__( 'You are using an older version of the %1$s which may cause compatibility issues. Please <a href="%2$s" target="_blank" style="font-weight:bold; color:#0073aa;">download the latest Pro plugin</a> and enjoy all the new features and benefits.', 'echo-rewards' ),
				'Echo Rewards Pro plugin',
				'https://wppool.dev/account-login/'
			);

			printf( '<div class="notice notice-error is-dismissible"><p>%s</p></div>', wp_kses_post( $notice ) );
		}
	}
}
