<?php
/**
 * Main Plugin class for Ask Any.
 *
 * This class serves as the main orchestrator for the plugin,
 * initializing all components and managing their lifecycle.
 *
 * @package Askany
 * @since 1.0.0
 */

namespace Askany;

use ask\askany\ask_fs;

/**
 * Main Plugin class for Ask Any.
 *
 * @package Askany
 * @since 1.0.0
 */
class Plugin {
	/**
	 * Plugin instance.
	 *
	 * @var Plugin
	 */
	private static $instance = null;
	/**
	 * Database instance.
	 *
	 * @var Database
	 */
	private $database;
	/**
	 * API Manager instance.
	 *
	 * @var ApiManager
	 */
	private $api_manager;
	/**
	 * Content Indexer instance.
	 *
	 * @var ContentIndexer
	 */
	private $content_indexer;
	/**
	 * PDF Handler instance.
	 *
	 * @var PdfHandler
	 */
	private $pdf_handler;
	/**
	 * PDF Upload Handler instance.
	 *
	 * @var PDFUploadHandler
	 */
	private $pdf_upload;
	/**
	 * Admin Pages instance.
	 *
	 * @var AdminPages
	 */
	private $admin_pages;
	/**
	 * Ajax Handler instance.
	 *
	 * @var AjaxHandler
	 */
	private $ajax_handler;
	/**
	 * Assets Manager instance.
	 *
	 * @var AssetsManager
	 */
	private $assets_manager;
	/**
	 * Shortcode Handler instance.
	 *
	 * @var ShortcodeHandler
	 */
	private $shortcode_handler;
	/**
	 * Encryption Handler instance.
	 *
	 * @var EncryptionHandler
	 */
	private $encryption_handler;
	/**
	 * External Sources Handler instance.
	 *
	 * @var ExternalSourcesHandler
	 */
	private $external_sources_handler;
	/**
	 * SSE Handler instance.
	 *
	 * @var SSEHandler
	 */
	private $sse_handler;

	/**
	 * Slack Notifier instance.
	 *
	 * @var SlackNotifier
	 */
	private $slack_notifier;

	/**
	 * WooCommerce Handler instance.
	 *
	 * @var WooCommerceHandler
	 */
	private $woocommerce_handler;

	/**
	 * News Handler instance.
	 *
	 * @var NewsHandler
	 */
	private $news_handler;

	/**
	 * Get plugin instance.
	 *
	 * @return Plugin Plugin instance.
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor for Plugin.
	 *
	 * Initializes all plugin components.
	 */
	private function __construct() {
		$this->init_components();
	}

	/**
	 * Initialize plugin components.
	 *
	 * @return void
	 */
	private function init_components() {
		// Initialize components with their dependencies.
		$this->database = new Database();
		$this->api_manager = new ApiManager();
		$this->content_indexer = new ContentIndexer($this->database);
		$this->pdf_handler = new PdfHandler($this->database);
		$this->pdf_upload = new PDFUploadHandler($this->database, $this->pdf_handler);
		$this->encryption_handler = new EncryptionHandler();
		$this->external_sources_handler = new ExternalSourcesHandler($this->database);
		$this->sse_handler = new SSEHandler($this->database);
		$this->slack_notifier = new SlackNotifier($this->api_manager);
		$this->woocommerce_handler = new WooCommerceHandler($this->database);
		$this->news_handler = new NewsHandler();
		$this->admin_pages = new AdminPages($this->api_manager, $this->database, $this->content_indexer, $this->pdf_handler, $this->external_sources_handler);
		$this->ajax_handler = new AjaxHandler($this, $this->api_manager, $this->content_indexer, $this->pdf_handler, $this->database, $this->slack_notifier);
		$this->assets_manager = new AssetsManager();
		$this->shortcode_handler = new ShortcodeHandler($this->api_manager);

		// Initialize each component.
		$this->api_manager->init();
		$this->content_indexer->init();
		$this->pdf_handler->init();
		$this->pdf_upload->init();
		$this->external_sources_handler->init();
		$this->sse_handler->init();
		$this->slack_notifier->init();
		$this->admin_pages->init();
		$this->ajax_handler->init();
		$this->assets_manager->init();
		$this->shortcode_handler->init();
	}

	/**
	 * Initialize the plugin.
	 *
	 * @return void
	 */
	public function init() {
		// Register activation/deactivation hooks.
		register_activation_hook(ASKANY_PLUGIN_FILE, array( $this->database, 'activate' ));
		register_deactivation_hook(ASKANY_PLUGIN_FILE, array( $this->database, 'deactivate' ));
		// Register uninstall hook.
		register_uninstall_hook( ASKANY_PLUGIN_FILE, array( __CLASS__, 'uninstall' ) );

		// Add plugin action links.
		add_filter( 'plugin_action_links_' . ASKANY_PLUGIN_BASENAME, array( $this, 'add_plugin_action_links' ) );

		// Add plugin row meta.
		add_filter( 'plugin_row_meta', array( $this, 'add_plugin_row_meta' ), 10, 2 );

		// Add floating widget to footer if enabled.
		add_action('wp_footer', array( $this, 'add_floating_widget' ));
	}

	/**
	 * Add plugin action links.
	 *
	 * @param array $links Plugin action links.
	 * @return array Modified plugin action links.
	 */
	public function add_plugin_action_links( $links ) {
		$plugin_links = array(
			'<a href="' . admin_url( 'admin.php?page=askany-settings' ) . '">' . esc_html__( 'AI Assistant', 'askany' ) . '</a>',
		);
		return array_merge( $plugin_links, $links );
	}

	/**
	 * Add plugin row meta.
	 *
	 * @param array  $links Plugin row meta.
	 * @param string $file  Plugin file.
	 * @return array Modified plugin row meta.
	 */
	public function add_plugin_row_meta( $links, $file ) {
		if ( ASKANY_PLUGIN_BASENAME === $file ) {
			$row_meta = array(
				'docs' => '<a href="' . esc_url( 'https://wpazleen.com/docs/' ) . '" target="_blank" aria-label="' . esc_attr__( 'Documentation', 'askany' ) . '">' . esc_html__( 'Documentation', 'askany' ) . '</a>',
				'support' => '<a href="' . esc_url( 'https://wordpress.org/support/plugin/askany/' ) . '" target="_blank" aria-label="' . esc_attr__( 'Support forum', 'askany' ) . '">' . esc_html__( 'Support', 'askany' ) . '</a>',
				'review' => '<a href="' . esc_url( 'https://wordpress.org/plugins/askany/#reviews' ) . '" target="_blank" aria-label="' . esc_attr__( 'Review forum', 'askany' ) . '">' . esc_html__( '⭐⭐⭐⭐⭐', 'askany' ) . '</a>',
			);
			return array_merge( $links, $row_meta );
		}
		return $links;
	}

	/**
	 * Add floating widget to the footer.
	 *
	 * This method checks if the floating widget is enabled and
	 * renders the chat interface accordingly.
	 *
	 * @return void
	 */
	public function add_floating_widget() {
		// Get settings.
		$settings = $this->api_manager->get_settings();

		// Check if floating widget is enabled and API is enabled.
		if ( ! $settings['floating_widget_enabled'] || ! $settings['api_enabled'] ) {
			return;
		}

		// Get the position from settings and sanitize it.
		$position = sanitize_text_field(wp_unslash($settings['widget_position']));

		// Render the chat interface with floating widget settings.
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Output is escaped in the render_chat_interface method
		echo $this->shortcode_handler->render_chat_interface(array(
			'position' => esc_attr($position),
			'theme' => 'light',
		));
	}


	/**
	 * Uninstall callback to clean up plugin data.
	 *
	 * @return void
	 */
	public static function uninstall() {
		// Delete plugin data.
		$database = new Database();
		$database->drop_tables();

		// Delete plugin settings.
		delete_option('askany_settings');
	}


	/**
	 * Check if the pro version is installed
	 *
	 * @return bool
	 */
	public function check_pro_plugin_exists(): bool {
		return file_exists( WP_PLUGIN_DIR . '/askany-pro/askany-pro.php' );
	}

	/**
	 * Check if the pro version is active
	 *
	 * @return bool
	 */
	public function is_pro_active() {
		// Check if Pro plugin file exists and is active
		if ( ! $this->check_pro_plugin_exists() ) {
			return false;
		}

		// Check if Pro plugin is actually activated
		if ( ! is_plugin_active( 'askany-pro/askany-pro.php' ) ) {
			return false;
		}

		// Check if Pro class exists
		if ( ! class_exists( 'AskanyPro' ) ) {
			return false;
		}

		// Check Freemius premium status
		if ( function_exists( 'ask_fs' ) ) {
			return ask_fs()->can_use_premium_code__premium_only();
		}

		return false;
	}

	/**
	 * Get Freemius instance
	 *
	 * @return object|null Freemius instance or null
	 */
	public function get_freemius_instance() {
		return askany_get_freemius_instance();
	}

	/**
	 * Get WooCommerce Handler instance.
	 *
	 * @return WooCommerceHandler WooCommerce Handler instance.
	 */
	public function get_woocommerce_handler() {
		return $this->woocommerce_handler;
	}

	/**
	 * Get News Handler instance.
	 *
	 * @return NewsHandler News Handler instance.
	 */
	public function get_news_handler() {
		return $this->news_handler;
	}

}
