<?php
/**
 * Elementor Requirement Notice
 *
 * Shows a professional admin notice when Elementor is not installed or not active.
 * Provides AJAX-powered one-click install / activate.
 *
 * @since      1.0.0
 * @package    captain-widgets-kit
 * @subpackage captain-widgets-kit/includes/notices
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'Captwiki_Elementor_Notice' ) ) {

	/**
	 * Class Captwiki_Elementor_Notice
	 *
	 * @since 1.0.0
	 */
	class Captwiki_Elementor_Notice {

		/**
		 * Elementor plugin file slug.
		 *
		 * @var string
		 */
		const ELEMENTOR_PLUGIN = 'elementor/elementor.php';

		/**
		 * Transient key used to dismiss the notice.
		 *
		 * @var string
		 */
		const DISMISS_KEY = 'captwiki_elementor_notice_dismissed';

		/**
		 * Singleton instance.
		 *
		 * @var self
		 */
		private static $instance;

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

		/**
		 * Constructor — register all hooks.
		 */
		public function __construct() {
			add_action( 'admin_notices', array( $this, 'render_notice' ) );
			add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
			add_action( 'wp_ajax_captwiki_elementor_install', array( $this, 'ajax_install_elementor' ) );
			add_action( 'wp_ajax_captwiki_elementor_activate', array( $this, 'ajax_activate_elementor' ) );
			add_action( 'wp_ajax_captwiki_dismiss_elementor_notice', array( $this, 'ajax_dismiss_notice' ) );
		}

		/**
		 * Check whether Elementor is active.
		 *
		 * @return bool
		 */
		private function is_elementor_active() {
			return defined( 'ELEMENTOR_VERSION' ) || is_plugin_active( self::ELEMENTOR_PLUGIN );
		}

		/**
		 * Check whether Elementor is installed (but maybe not active).
		 *
		 * @return bool
		 */
		private function is_elementor_installed() {
			$plugins = get_plugins();
			return isset( $plugins[ self::ELEMENTOR_PLUGIN ] );
		}

		/**
		 * Enqueue notice CSS + JS only when the notice will be shown.
		 */
		public function enqueue_assets() {
			if ( $this->is_elementor_active() ) {
				return;
			}
			if ( get_transient( self::DISMISS_KEY . '_' . get_current_user_id() ) ) {
				return;
			}

			$base_url = plugin_dir_url( __FILE__ ) . 'resources/';

			wp_enqueue_style(
				'captwiki-el-notice',
				$base_url . 'notice.css',
				array(),
				CAPTWIKI_VERSION
			);

			wp_enqueue_script(
				'captwiki-el-notice',
				$base_url . 'notice.js',
				array( 'jquery' ),
				CAPTWIKI_VERSION,
				true
			);

			wp_localize_script(
				'captwiki-el-notice',
				'captwiki_notice_data',
				array(
					'ajax_url'  => admin_url( 'admin-ajax.php' ),
					'nonce'     => wp_create_nonce( 'captwiki_elementor_notice_nonce' ),
					'error_msg' => esc_html__( 'Something went wrong. Please try manually.', 'captain-widgets-kit' ),
				)
			);
		}

		/**
		 * Render the admin notice HTML.
		 */
		public function render_notice() {
			if ( $this->is_elementor_active() ) {
				return;
			}

			// Respect per-user dismissal.
			if ( get_transient( self::DISMISS_KEY . '_' . get_current_user_id() ) ) {
				return;
			}

			$is_installed = $this->is_elementor_installed();

			if ( $is_installed ) {
				if ( ! current_user_can( 'activate_plugins' ) ) {
					return;
				}
				$btn_label  = esc_html__( 'Activate Elementor', 'captain-widgets-kit' );
				$btn_action = 'activate';
				$desc       = esc_html__( 'Elementor is installed but not active. Captain Widgets Kit needs Elementor to work. Click the button to activate it instantly.', 'captain-widgets-kit' );
			} else {
				if ( ! current_user_can( 'install_plugins' ) ) {
					return;
				}
				$btn_label  = esc_html__( 'Install & Activate Elementor', 'captain-widgets-kit' );
				$btn_action = 'install';
				$desc       = esc_html__( 'Captain Widgets Kit requires Elementor to function. Elementor is a free page builder — click the button to install and activate it automatically.', 'captain-widgets-kit' );
			}
			?>
			<div class="captwiki-el-notice-wrap">
				<div class="captwiki-el-notice notice">
					<div class="captwiki-el-notice-icon">
						<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
							<path d="M32 4C16.536 4 4 16.536 4 32s12.536 28 28 28 28-12.536 28-28S47.464 4 32 4zm-4 42V28h8v18h-8zm0-22v-8h8v8h-8z"/>
						</svg>
					</div>

					<div class="captwiki-el-notice-body">
						<p class="captwiki-el-notice-title">
							<?php esc_html_e( 'Elementor Required — Captain Widgets Kit', 'captain-widgets-kit' ); ?>
						</p>
						<p class="captwiki-el-notice-desc">
							<?php echo esc_html( $desc ); ?>
						</p>
						<div class="captwiki-el-notice-actions">
							<button
								type="button"
								class="captwiki-el-btn captwiki-el-btn--primary captwiki-el-action-btn"
								data-action="<?php echo esc_attr( $btn_action ); ?>"
							>
								<span class="captwiki-el-btn-text"><?php echo esc_html( $btn_label ); ?></span>
								<span class="captwiki-el-btn-spinner" style="display:none;"></span>
							</button>

							<button type="button" class="captwiki-el-dismiss-btn">
								<?php esc_html_e( 'Dismiss', 'captain-widgets-kit' ); ?>
							</button>
						</div>
					</div>
				</div>
			</div>
			<?php
		}

		/**
		 * AJAX — Install Elementor via WordPress Plugin API.
		 */
		public function ajax_install_elementor() {
			check_ajax_referer( 'captwiki_elementor_notice_nonce', 'nonce' );

			if ( ! current_user_can( 'install_plugins' ) ) {
				wp_send_json_error( array( 'message' => esc_html__( 'Permission denied.', 'captain-widgets-kit' ) ) );
			}

			include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
			include_once ABSPATH . 'wp-admin/includes/plugin-install.php';
			include_once ABSPATH . 'wp-admin/includes/plugin.php';

			// Fetch plugin info from WordPress.org API.
			$api = plugins_api(
				'plugin_information',
				array(
					'slug'   => 'elementor',
					'fields' => array(
						'sections'     => false,
						'tags'         => false,
						'screenshots'  => false,
					),
				)
			);

			if ( is_wp_error( $api ) ) {
				wp_send_json_error( array( 'message' => $api->get_error_message() ) );
			}

			// Use a silent skin so no HTML output leaks into our JSON.
			$skin     = new WP_Ajax_Upgrader_Skin();
			$upgrader = new Plugin_Upgrader( $skin );
			$result   = $upgrader->install( $api->download_link );

			if ( is_wp_error( $result ) ) {
				wp_send_json_error( array( 'message' => $result->get_error_message() ) );
			}

			if ( is_wp_error( $skin->result ) ) {
				wp_send_json_error( array( 'message' => $skin->result->get_error_message() ) );
			}

			// Activate immediately after install.
			$activate = activate_plugin( self::ELEMENTOR_PLUGIN, '', false, true );

			if ( is_wp_error( $activate ) ) {
				// Installed but could not activate — next request will show activate flow.
				wp_send_json_error( array( 'message' => $activate->get_error_message() ) );
			}

			wp_send_json_success(
				array( 'message' => esc_html__( 'Elementor installed & activated! Reloading…', 'captain-widgets-kit' ) )
			);
		}

		/**
		 * AJAX — Activate an already-installed Elementor.
		 */
		public function ajax_activate_elementor() {
			check_ajax_referer( 'captwiki_elementor_notice_nonce', 'nonce' );

			if ( ! current_user_can( 'activate_plugins' ) ) {
				wp_send_json_error( array( 'message' => esc_html__( 'Permission denied.', 'captain-widgets-kit' ) ) );
			}

			include_once ABSPATH . 'wp-admin/includes/plugin.php';

			if ( ! $this->is_elementor_installed() ) {
				wp_send_json_error( array( 'message' => esc_html__( 'Elementor is not installed.', 'captain-widgets-kit' ) ) );
			}

			$activate = activate_plugin( self::ELEMENTOR_PLUGIN, '', false, true );

			if ( is_wp_error( $activate ) ) {
				wp_send_json_error( array( 'message' => $activate->get_error_message() ) );
			}

			wp_send_json_success(
				array( 'message' => esc_html__( 'Elementor activated successfully! Reloading…', 'captain-widgets-kit' ) )
			);
		}

		/**
		 * AJAX — Dismiss the notice for 30 days for the current user.
		 */
		public function ajax_dismiss_notice() {
			check_ajax_referer( 'captwiki_elementor_notice_nonce', 'nonce' );

			set_transient(
				self::DISMISS_KEY . '_' . get_current_user_id(),
				true,
				30 * DAY_IN_SECONDS
			);

			wp_send_json_success();
		}
	}

	Captwiki_Elementor_Notice::get_instance();
}
