<?php
/**
 * AI Marketing Expert Plugin Notice
 *
 * Displays a benefit-driven admin notice to promote the AI Marketing Expert plugin.
 * One-click install + activate via AJAX. Persistent dismiss.
 *
 * @package Ai_Blog
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class AI_Blog_Marketing_Notice
 */
class AI_Blog_Marketing_Notice {

	/**
	 * Plugin slug.
	 *
	 * @var string
	 */
	private $plugin_slug = 'ai-marketing-expert';

	/**
	 * Plugin file path.
	 *
	 * @var string
	 */
	private $plugin_file = 'ai-marketing-expert/ai-marketing-expert.php';

	/**
	 * Transient name for dismiss.
	 *
	 * @var string
	 */
	private $dismiss_option = 'ai_blog_marketing_notice_dismissed';

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'admin_notices', array( $this, 'render_notice' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'wp_ajax_ai_blog_install_marketing_plugin', array( $this, 'ajax_install_plugin' ) );
		add_action( 'wp_ajax_ai_blog_dismiss_marketing_notice', array( $this, 'ajax_dismiss_notice' ) );
	}

	/**
	 * Check if notice should display.
	 *
	 * @return bool
	 */
	private function should_display() {
		// Don't display if already dismissed.
		if ( get_user_meta( get_current_user_id(), $this->dismiss_option, true ) ) {
			return false;
		}

		// Don't display if plugin is already active.
		if ( $this->is_plugin_active() ) {
			return false;
		}

		return true;
	}

	/**
	 * Check if the plugin is active.
	 *
	 * @return bool
	 */
	private function is_plugin_active() {
		if ( ! function_exists( 'is_plugin_active' ) ) {
			include_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		// Check active_plugins option directly for reliability.
		$active_plugins = get_option( 'active_plugins', array() );
		return in_array( $this->plugin_file, $active_plugins, true );
	}

	/**
	 * Check if WooCommerce is active.
	 *
	 * @return bool
	 */
	private function is_woocommerce_active() {
		return class_exists( 'WooCommerce' );
	}

	/**
	 * Get benefit text based on WooCommerce status.
	 *
	 * @return string HTML string with check icons.
	 */
	private function get_benefit_text() {
		$check = '<span class="ai-blog-check-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20 6 9 17 4 12"/></svg></span>';

		$highlights = $check . ' Free API   ' . $check . ' Free SMTP   ' . $check . ' Unlimited Mail Sent';

		if ( $this->is_woocommerce_active() ) {
			return 'Boost your WooCommerce sales with AI-powered marketing automation. ' . $highlights . ' — all on autopilot.';
		}

		return 'All-in-one AI marketing suite for your WordPress site. ' . $highlights . ' — everything you need to grow.';
	}

	/**
	 * Get benefit title based on WooCommerce status.
	 *
	 * @return string
	 */
	private function get_benefit_title() {
		if ( $this->is_woocommerce_active() ) {
			return __(
				'Increase Your Sales with AI Marketing',
				'ai-blog'
			);
		}

		return __(
			'Grow Your Traffic with AI Marketing',
			'ai-blog'
		);
	}

	/**
	 * Check if the plugin is installed (file exists but may not be active).
	 *
	 * @return bool
	 */
	private function is_plugin_installed() {
		return file_exists( WP_PLUGIN_DIR . '/' . $this->plugin_file );
	}

	/**
	 * Enqueue notice assets.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_assets( $hook ) {
		// Don't load on login, install, or upgrade pages.
		if ( in_array( $hook, array( 'login.php', 'update-core.php' ), true ) ) {
			return;
		}

		wp_enqueue_style(
			'ai-blog-marketing-notice',
			get_template_directory_uri() . '/assets/css/admin-marketing-notice.css',
			array(),
			AI_BLOG_VERSION
		);

		wp_enqueue_script(
			'ai-blog-marketing-notice',
			get_template_directory_uri() . '/assets/js/admin-marketing-notice.js',
			array( 'jquery' ),
			AI_BLOG_VERSION,
			true
		);

		wp_localize_script(
			'ai-blog-marketing-notice',
			'aiBlogMarketingNotice',
			array(
				'ajaxurl'      => admin_url( 'admin-ajax.php' ),
				'nonce'        => wp_create_nonce( 'ai_blog_marketing_notice_nonce' ),
				'installing'   => __( 'Installing...', 'ai-blog' ),
				'activating'   => __( 'Activating...', 'ai-blog' ),
				'installed'    => __( 'Plugin Installed!', 'ai-blog' ),
				'error'        => __( 'Something went wrong. Please try again.', 'ai-blog' ),
				'pluginSlug'   => $this->plugin_slug,
			)
		);
	}

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

		$benefit_title   = $this->get_benefit_title();
		$benefit_text    = $this->get_benefit_text();
		$is_woocommerce  = $this->is_woocommerce_active();
		$admin_name      = wp_get_current_user()->display_name;
		?>
		<div class="ai-blog-marketing-notice" id="ai-blog-marketing-notice">
			<button class="ai-blog-notice-close" id="ai-blog-notice-close" aria-label="<?php esc_attr_e( 'Dismiss', 'ai-blog' ); ?>">&times;</button>
			<div class="ai-blog-notice-top">
				<span class="ai-blog-notice-greeting"><?php printf( esc_html__( 'Hello, %s', 'ai-blog' ), esc_html( $admin_name ) ); ?> <span class="ai-blog-wave">&#x1F44B;</span></span>
			</div>
			<h3 class="ai-blog-notice-title">
				<span class="ai-blog-notice-rocket">&#x1F680;</span>
				<?php echo esc_html( $benefit_title ); ?>
			</h3>
			<p class="ai-blog-notice-text"><?php echo wp_kses_post( $benefit_text ); ?></p>
			<div class="ai-blog-notice-highlight">
				<span class="ai-blog-highlight-item">
					<span class="ai-blog-highlight-icon">&#x1F4E7;</span>
					<?php esc_html_e( 'Free API & SMTP', 'ai-blog' ); ?>
				</span>
				<span class="ai-blog-highlight-divider">|</span>
				<span class="ai-blog-highlight-item">
					<span class="ai-blog-highlight-icon">&#x2705;</span>
					<?php esc_html_e( 'Unlimited Mail Sent', 'ai-blog' ); ?>
				</span>
				<span class="ai-blog-highlight-divider">|</span>
				<span class="ai-blog-highlight-item">
					<span class="ai-blog-highlight-icon">&#x1F680;</span>
					<?php esc_html_e( 'One-Click Setup', 'ai-blog' ); ?>
				</span>
			</div>
			<div class="ai-blog-notice-modules">
				<span class="ai-blog-module">&#x1F4E7; <?php esc_html_e( 'Email Marketing', 'ai-blog' ); ?></span>
				<span class="ai-blog-module">&#x1F4DD; <?php esc_html_e( 'Content Generator', 'ai-blog' ); ?></span>
				<span class="ai-blog-module">&#x1F310; <?php esc_html_e( 'SEO Analyzer', 'ai-blog' ); ?></span>
				<span class="ai-blog-module">&#x1F916; <?php esc_html_e( 'AI Chatbot', 'ai-blog' ); ?></span>
				<span class="ai-blog-module">&#x1F517; <?php esc_html_e( 'Social Media', 'ai-blog' ); ?></span>
			</div>
			<div class="ai-blog-notice-buttons">
				<?php if ( $this->is_plugin_installed() ) : ?>
					<button class="ai-blog-btn ai-blog-btn-primary" id="ai-blog-install-plugin" data-slug="<?php echo esc_attr( $this->plugin_slug ); ?>" data-action="activate">
						<span class="ai-blog-btn-label">&#x1F525; <?php esc_html_e( 'Activate Now & Get Free Setup', 'ai-blog' ); ?></span>
						<span class="ai-blog-btn-loading"><span class="ai-blog-spinner"></span> <?php esc_html_e( 'Activating...', 'ai-blog' ); ?></span>
					</button>
				<?php else : ?>
					<button class="ai-blog-btn ai-blog-btn-primary" id="ai-blog-install-plugin" data-slug="<?php echo esc_attr( $this->plugin_slug ); ?>" data-action="install">
						<span class="ai-blog-btn-label">&#x1F525; <?php esc_html_e( 'Install & Activate Free', 'ai-blog' ); ?></span>
						<span class="ai-blog-btn-loading"><span class="ai-blog-spinner"></span> <?php esc_html_e( 'Installing...', 'ai-blog' ); ?></span>
					</button>
				<?php endif; ?>
				<button class="ai-blog-btn ai-blog-btn-text" id="ai-blog-dismiss-notice"><?php esc_html_e( 'Maybe Later', 'ai-blog' ); ?></button>
			</div>
			<p class="ai-blog-notice-trust">&#x1F6E1; <?php esc_html_e( 'Trusted by WordPress Community', 'ai-blog' ); ?></p>
		</div>
		<?php
	}

	/**
	 * AJAX handler: Install and/or activate the plugin.
	 */
	public function ajax_install_plugin() {
		check_ajax_referer( 'ai_blog_marketing_notice_nonce', 'nonce' );

		if ( ! current_user_can( 'install_plugins' ) || ! current_user_can( 'activate_plugins' ) ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission to install plugins.', 'ai-blog' ) ) );
		}

		$slug   = sanitize_text_field( wp_unslash( $_POST['slug'] ?? '' ) );
		$action = sanitize_text_field( wp_unslash( $_POST['action_type'] ?? 'install' ) );

		if ( $this->plugin_slug !== $slug ) {
			wp_send_json_error( array( 'message' => __( 'Invalid plugin slug.', 'ai-blog' ) ) );
		}

		$plugin_installed = file_exists( WP_PLUGIN_DIR . '/' . $this->plugin_file );

		// If action is "activate" and plugin is installed — just activate.
		if ( 'activate' === $action && $plugin_installed ) {
			$result = activate_plugin( $this->plugin_file );

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

			wp_send_json_success( array( 'message' => __( 'Plugin activated successfully!', 'ai-blog' ) ) );
		}

		// If already installed and active.
		if ( $plugin_installed && is_plugin_active( $this->plugin_file ) ) {
			wp_send_json_success( array( 'message' => __( 'Plugin is already active.', 'ai-blog' ) ) );
		}

		// If already installed but not active — activate.
		if ( $plugin_installed ) {
			$result = activate_plugin( $this->plugin_file );

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

			wp_send_json_success( array( 'message' => __( 'Plugin activated successfully!', 'ai-blog' ) ) );
		}

		// Install the plugin from WordPress.org.
		include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
		include_once ABSPATH . 'wp-admin/includes/plugin-install.php';

		// Get plugin info from WordPress.org.
		$api = plugins_api(
			'plugin_information',
			array(
				'slug'   => $slug,
				'fields' => array(
					'short_description' => false,
					'sections'          => false,
					'requires'          => false,
					'rating'            => false,
					'ratings'           => false,
					'downloaded'        => false,
					'last_updated'      => false,
					'added'             => false,
					'tags'              => false,
					'compatibility'     => false,
					'homepage'          => false,
					'donate_link'       => false,
				),
			)
		);

		if ( is_wp_error( $api ) ) {
			wp_send_json_error( array( 'message' => __( 'Could not fetch plugin information from WordPress.org.', 'ai-blog' ) ) );
		}

		// Create a silent upgrader skin to suppress output.
		$skin = new class extends WP_Upgrader_Skin {
			public function feedback( $string, ...$args ) {}
			public function header() {}
			public function footer() {}
			public function error( $errors ) {
				return $errors;
			}
		};
		$upgrader = new Plugin_Upgrader( $skin );

		// Install the plugin.
		$install = $upgrader->install( $api->download_link );

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

		if ( ! $install ) {
			wp_send_json_error( array( 'message' => __( 'Plugin installation failed.', 'ai-blog' ) ) );
		}

		// Activate the plugin.
		$activate = activate_plugin( $this->plugin_file, '', false, true );

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

		wp_send_json_success( array( 'message' => __( 'Plugin installed and activated successfully!', 'ai-blog' ) ) );
	}

	/**
	 * AJAX handler: Dismiss the notice.
	 */
	public function ajax_dismiss_notice() {
		check_ajax_referer( 'ai_blog_marketing_notice_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission.', 'ai-blog' ) ) );
		}

		update_user_meta( get_current_user_id(), $this->dismiss_option, true );

		wp_send_json_success( array( 'message' => __( 'Notice dismissed.', 'ai-blog' ) ) );
	}
}

// Initialize the notice.
new AI_Blog_Marketing_Notice();

// Debug: reset notice by visiting ?reset_ai_blog_notice=1
if ( isset( $_GET['reset_ai_blog_notice'] ) && current_user_can( 'manage_options' ) ) {
	delete_option( 'ai_blog_marketing_notice_dismissed' );
	wp_safe_redirect( remove_query_arg( 'reset_ai_blog_notice' ) );
	exit;
}
