<?php
/**
 * Admin App Class
 *
 * Manages the main admin page with React SPA application
 *
 * @package SmartyPress_AI_Engine
 * @since 1.0.0
 */

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

/**
 * Admin App class
 */
class SmartyPress_AI_Admin_App {

	/**
	 * Page slug
	 *
	 * @var string
	 */
	private $page_slug = 'smartypress-ai';

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'add_menu_page' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'admin_notices', array( $this, 'show_api_key_notice' ) );
		add_action( 'admin_notices', array( $this, 'show_permalink_notice' ) );
		add_action( 'admin_notices', array( $this, 'show_review_notice' ), 5 );
		add_action( 'wp_ajax_smartypress_ai_dismiss_review_notice', array( $this, 'ajax_dismiss_review_notice' ) );
		add_action( 'admin_notices', array( $this, 'show_yandex_reauth_notice' ), 4 );
		add_action( 'wp_ajax_smartypress_ai_dismiss_yandex_reauth_notice', array( $this, 'ajax_dismiss_yandex_reauth_notice' ) );
		add_action( 'admin_head', array( $this, 'hide_other_plugin_notices' ), 1 );
		add_action( 'admin_head', array( $this, 'add_menu_icon_styles' ) );
		add_action( 'admin_head-edit.php', array( $this, 'add_ai_buttons_to_post_list' ) );
		add_action( 'admin_head-upload.php', array( $this, 'add_ai_button_to_media_library' ) );
		add_filter( 'script_loader_tag', array( $this, 'add_module_type' ), 10, 2 );
	}

	/**
	 * Hide admin notices from other plugins and core on this plugin's pages.
	 */
	public function hide_other_plugin_notices() {
		$screen = get_current_screen();
		if ( ! $screen || strpos( $screen->id, 'smartypress-ai' ) === false ) {
			return;
		}
		remove_all_actions( 'admin_notices' );
		remove_all_actions( 'all_admin_notices' );
		?>
		<style>
			#wpbody-content > .notice,
			#wpbody-content > .update-nag,
			#wpbody-content > .updated,
			.wrap > .notice,
			.wrap > .updated,
			.wrap > .update-nag {
				display: none !important;
				visibility: hidden !important;
			}
		</style>
		<?php
	}

	/**
	 * Add menu page
	 */
	public function add_menu_page() {
		// Get menu icon URL
		$icon_url = SMARTYPRESS_AI_PLUGIN_URL . 'assets/images/menu-icon-icon35x35.png';

		// Main menu page
		add_menu_page(
			__( 'SmartyPress AI', 'smartypress-ai-engine' ),
			__( 'SmartyPress AI', 'smartypress-ai-engine' ),
			'manage_options',
			$this->page_slug,
			array( $this, 'render_page' ),
			$icon_url,
			100
		);

		// Submenu: Dashboard (first item, same as main menu)
		add_submenu_page(
			$this->page_slug,
			__( 'Dashboard', 'smartypress-ai-engine' ),
			__( 'Dashboard', 'smartypress-ai-engine' ),
			'manage_options',
			$this->page_slug,
			array( $this, 'render_page' )
		);

		// Submenu: Components
		add_submenu_page(
			$this->page_slug,
			__( 'Components', 'smartypress-ai-engine' ),
			__( 'Components', 'smartypress-ai-engine' ),
			'manage_options',
			$this->page_slug . '#/components',
			array( $this, 'render_page' )
		);

		// Submenu: Settings
		add_submenu_page(
			$this->page_slug,
			__( 'Settings', 'smartypress-ai-engine' ),
			__( 'Settings', 'smartypress-ai-engine' ),
			'manage_options',
			$this->page_slug . '#/settings',
			array( $this, 'render_page' )
		);

		// Submenu: module routes (from config, only enabled modules)
		$module_routes = $this->get_admin_routes();
		foreach ( $module_routes as $route ) {
			$menu_title = $route['menu_title'] ?? $route['title'] ?? '';
			if ( empty( $menu_title ) ) {
				continue;
			}
			add_submenu_page(
				$this->page_slug,
				$route['title'] ?? $menu_title,
				$menu_title,
				'manage_options',
				$this->page_slug . '#' . $route['path'],
				array( $this, 'render_page' )
			);
		}
	}

	/**
	 * Get admin routes for React app and menu
	 *
	 * Aggregates routes from config (for enabled modules) and filter.
	 * Config is primary; filter can override or add (e.g. third-party modules).
	 *
	 * @return array List of route configs.
	 */
	private function get_admin_routes() {
		global $smartypress_ai_plugin;
		$module_manager = $smartypress_ai_plugin ? $smartypress_ai_plugin->get_module_manager() : null;
		if ( ! $module_manager ) {
			return array();
		}

		$config_routes = $module_manager->get_admin_routes_from_config();
		$filter_routes = apply_filters( 'smartypress_ai_admin_routes', array() );

		// Index by path: config first, then filter overrides (only for enabled modules)
		$routes_by_path = array();
		foreach ( $config_routes as $route ) {
			$routes_by_path[ $route['path'] ] = $route;
		}
		foreach ( $filter_routes as $route ) {
			$module = $route['module'] ?? null;
			if ( $module && ! $module_manager->is_module_enabled( $module ) ) {
				continue;
			}
			$routes_by_path[ $route['path'] ] = $route;
		}

		return array_values( $routes_by_path );
	}

	/**
	 * Enqueue scripts
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_scripts( $hook ) {
		// Only load on our admin page
		if ( strpos( $hook, $this->page_slug ) === false ) {
			return;
		}

		// Get routes (from config + filter, filtered by enabled modules)
		$routes = $this->get_admin_routes();

		// Get modules info
		global $smartypress_ai_plugin;
		$module_manager = $smartypress_ai_plugin ? $smartypress_ai_plugin->get_module_manager() : null;
		$modules_info   = $module_manager ? $module_manager->get_available_modules_info() : array();

		// Get settings
		$settings = get_option( 'smartypress_ai_settings', array() );

		// Enqueue compiled React app
		$asset_file = SMARTYPRESS_AI_PLUGIN_DIR . '/includes/admin/assets/dist/admin-app.asset.php';
		$js_file = SMARTYPRESS_AI_PLUGIN_DIR . '/includes/admin/assets/dist/admin-app.js';

		if ( file_exists( $asset_file ) ) {
			$asset = require $asset_file;
		} else {
			$asset = array(
				'dependencies' => array( 'react', 'react-dom', 'wp-api-fetch', 'wp-components', 'wp-element', 'wp-i18n' ),
				'version'      => SMARTYPRESS_AI_VERSION,
			);
		}

		// Use file modification time for cache busting
		$js_version = file_exists( $js_file ) ? filemtime( $js_file ) : $asset['version'];

		wp_enqueue_script(
			'smartypress-ai-admin-app',
			SMARTYPRESS_AI_PLUGIN_URL . 'includes/admin/assets/dist/admin-app.js',
			$asset['dependencies'],
			$js_version,
			true
		);

		// Set script translations for JavaScript localization
		wp_set_script_translations(
			'smartypress-ai-admin-app',
			'smartypress-ai-engine',
			SMARTYPRESS_AI_PLUGIN_DIR . 'languages'
		);


		// Check if admin-app.css exists, otherwise use style.css
		$css_file = SMARTYPRESS_AI_PLUGIN_DIR . '/includes/admin/assets/dist/admin-app.css';
		if ( ! file_exists( $css_file ) ) {
			$css_file = SMARTYPRESS_AI_PLUGIN_DIR . '/includes/admin/assets/dist/style.css';
			$css_url  = SMARTYPRESS_AI_PLUGIN_URL . '/includes/admin/assets/dist/style.css';
		} else {
			$css_url = SMARTYPRESS_AI_PLUGIN_URL . '/includes/admin/assets/dist/admin-app.css';
		}

		if ( file_exists( $css_file ) ) {
			// Use file modification time for cache busting
			$css_version = filemtime( $css_file );
			
			wp_enqueue_style(
				'smartypress-ai-admin-app',
				$css_url,
				array( 'wp-components' ),
				$css_version
			);
		}

		// Always load module assets so that enabling a module via the
		// Components page works without a full page reload.
		$this->enqueue_content_generator_assets( $settings );
		$this->enqueue_image_generator_assets( $settings );

		wp_localize_script(
			'smartypress-ai-admin-app',
			'smartypressAIAdmin',
			array(
				'apiUrl'       => rest_url( 'smartypress/v1/' ),
				'nonce'        => wp_create_nonce( 'wp_rest' ),
				'pluginUrl'    => SMARTYPRESS_AI_PLUGIN_URL,
				'pluginName'   => __( 'SmartyPress AI', 'smartypress-ai-engine' ),
				'pluginVersion' => SMARTYPRESS_AI_VERSION,
				'pluginLogo'   => SMARTYPRESS_AI_PLUGIN_URL . 'assets/images/logo-icon40x40.png',
				'routes'       => $routes,
				'modules'      => $modules_info,
				'settings'     => $settings,
				'providers'    => array_keys( SmartyPress_AI_Providers::get_all() ),
				'providerModels' => $this->get_provider_models(),
				'imageAltProviderModels' => $this->get_image_alt_provider_models(),
				'adminUrl'     => admin_url( 'admin.php?page=' . $this->page_slug ),
				'postEditUrl'  => admin_url( 'post.php' ),
				'isRuLocale'   => ( get_locale() === 'ru_RU' ),
				'locale'       => get_locale(),
				'localeDefaultLanguage' => smartypress_ai_get_language_by_locale(),
				'postTypes'   => array_map(
					function( $post_type ) {
						return array(
							'name'  => $post_type->name,
							'label' => $post_type->label,
						);
					},
					get_post_types( array( 'public' => true ), 'objects' )
				),
			)
		);
	}

	/**
	 * Get available models for each provider
	 *
	 * @return array Provider models.
	 */
	private function get_provider_models() {
		$provider_models = array();
		$providers = SmartyPress_AI_Providers::get_all();

		foreach ( $providers as $provider_name => $provider ) {
			if ( method_exists( $provider, 'get_available_models' ) ) {
				$provider_models[ $provider_name ] = $provider->get_available_models();
			}
		}

		return $provider_models;
	}

	/**
	 * Get providers that support image analysis for ALT generation.
	 *
	 * @return array Vision-capable text models grouped by provider.
	 */
	private function get_image_alt_provider_models() {
		$provider_models = array();
		$providers       = SmartyPress_AI_Providers::get_all();

		foreach ( $providers as $provider_name => $provider ) {
			if ( ! method_exists( $provider, 'describe_image_with_prompt' ) || ! method_exists( $provider, 'get_available_models' ) ) {
				continue;
			}

			$models = $this->filter_image_alt_models( $provider_name, $provider->get_available_models() );
			if ( ! empty( $models ) ) {
				$provider_models[ $provider_name ] = $models;
			}
		}

		return $provider_models;
	}

	/**
	 * Keep only models that can analyze image input and return text metadata.
	 *
	 * @param string $provider_name Provider name.
	 * @param array  $models        Provider models.
	 * @return array
	 */
	private function filter_image_alt_models( $provider_name, array $models ) {
		if ( 'openai' === $provider_name ) {
			$vision_models = array( 'gpt-5.3-codex', 'gpt-5.2', 'gpt-5.1', 'gpt-5', 'gpt-4.1', 'gpt-4o', 'gpt-4o-mini', 'gpt-4o-2024-11-20' );
			return array_intersect_key( $models, array_flip( $vision_models ) );
		}

		if ( 'openrouter' === $provider_name ) {
			return array_filter(
				$models,
				function( $model ) {
					$capabilities = is_array( $model['capabilities'] ?? null ) ? $model['capabilities'] : array();
					return ! empty( $capabilities['image_input'] ) && ! empty( $capabilities['text_output'] );
				}
			);
		}

		if ( 'anthropic' === $provider_name ) {
			return array_filter(
				$models,
				function( $model ) {
					$capabilities = is_array( $model['capabilities'] ?? null ) ? $model['capabilities'] : array();
					return ! empty( $capabilities['image_input'] ) && ! empty( $capabilities['text_output'] );
				}
			);
		}

		return array();
	}

	/**
	 * Get available image models for configured providers.
	 *
	 * @return array Image models grouped by provider.
	 */
	private function get_image_provider_models() {
		$image_models = array();
		$providers    = SmartyPress_AI_Providers::get_available_providers();

		foreach ( $providers as $provider_name => $provider ) {
			if ( method_exists( $provider, 'get_available_image_models' ) ) {
				$models = $provider->get_available_image_models();
				if ( ! empty( $models ) ) {
					$image_models[ $provider_name ] = $models;
				}
			}
		}

		return $image_models;
	}

	/**
	 * Enqueue content-generator module assets.
	 *
	 * Always loaded on the plugin admin page so the module UI is available
	 * immediately after activation without a full page reload.
	 *
	 * @param array $settings Plugin settings.
	 */
	private function enqueue_content_generator_assets( $settings ) {
		$content_gen_dir = SMARTYPRESS_AI_PLUGIN_DIR . 'includes/modules/content-generator/assets/dist/';
		$content_gen_url = SMARTYPRESS_AI_PLUGIN_URL . 'includes/modules/content-generator/assets/dist/';
		global $smartypress_ai_plugin;

		$module_manager = $smartypress_ai_plugin ? $smartypress_ai_plugin->get_module_manager() : null;
		$modules_info   = $module_manager ? $module_manager->get_available_modules_info() : array();

		$cg_js_file = $content_gen_dir . 'content-generator.js';
		if ( ! file_exists( $cg_js_file ) ) {
			return;
		}

		// Load content generator script
		$cg_asset_file = $content_gen_dir . 'content-generator.asset.php';
		if ( file_exists( $cg_asset_file ) ) {
			$cg_asset = require $cg_asset_file;
		} else {
			$cg_asset = array(
				'dependencies' => array( 'react', 'react-dom', 'wp-api-fetch', 'wp-components', 'wp-element', 'wp-i18n' ),
				'version'      => SMARTYPRESS_AI_VERSION,
			);
		}

		$cg_css_file    = $content_gen_dir . 'content-generator.css';
		$cg_js_version  = filemtime( $cg_js_file );
		$cg_css_version = file_exists( $cg_css_file ) ? filemtime( $cg_css_file ) : SMARTYPRESS_AI_VERSION;

		wp_enqueue_script(
			'smartypress-ai-content-generator',
			$content_gen_url . 'content-generator.js',
			array_merge( $cg_asset['dependencies'], array( 'react', 'react-dom' ) ),
			$cg_js_version,
			true
		);

		// Set script translations for content generator
		wp_set_script_translations(
			'smartypress-ai-content-generator',
			'smartypress-ai-engine',
			SMARTYPRESS_AI_PLUGIN_DIR . 'languages'
		);

		if ( file_exists( $cg_css_file ) ) {
			wp_enqueue_style(
				'smartypress-ai-content-generator',
				$content_gen_url . 'content-generator.css',
				array( 'wp-components' ),
				$cg_css_version
			);
		}

		// Get post types
		$post_types = get_post_types( array( 'public' => true ), 'objects' );

		wp_localize_script(
			'smartypress-ai-content-generator',
			'smartypressAISingle',
			array(
				'restUrl'        => rest_url( 'smartypress/v1/' ),
				'nonce'          => wp_create_nonce( 'wp_rest' ),
				'pluginUrl'      => SMARTYPRESS_AI_PLUGIN_URL . 'includes/modules/content-generator/',
				'settings'       => $settings,
				'modules'        => $modules_info,
				'postTypes'      => array_map(
					function( $post_type ) {
						return array(
							'name'  => $post_type->name,
							'label' => $post_type->label,
						);
					},
					$post_types
				),
				'providers'      => array_keys( SmartyPress_AI_Providers::get_all() ),
				'providerModels' => $this->get_provider_models(),
				'isRuLocale'     => ( get_locale() === 'ru_RU' ),
				'locale'         => get_locale(),
				'localeDefaultLanguage' => smartypress_ai_get_language_by_locale(),
			)
		);

		wp_localize_script(
			'smartypress-ai-content-generator',
			'smartypressAIBulk',
			array(
				'restUrl'        => rest_url( 'smartypress/v1/' ),
				'nonce'          => wp_create_nonce( 'wp_rest' ),
				'pluginUrl'      => SMARTYPRESS_AI_PLUGIN_URL . 'includes/modules/content-generator/',
				'settings'       => $settings,
				'modules'        => $modules_info,
				'postTypes'      => array_map(
					function( $post_type ) {
						return array(
							'name'  => $post_type->name,
							'label' => $post_type->label,
						);
					},
					$post_types
				),
				'providers'      => array_keys( SmartyPress_AI_Providers::get_all() ),
				'providerModels' => $this->get_provider_models(),
				'isRuLocale'     => ( get_locale() === 'ru_RU' ),
				'locale'         => get_locale(),
				'localeDefaultLanguage' => smartypress_ai_get_language_by_locale(),
				'strings'        => array(
					'generating' => __( 'Generating posts...', 'smartypress-ai-engine' ),
					'completed'  => __( 'Generation completed!', 'smartypress-ai-engine' ),
					'error'      => __( 'Error occurred during generation', 'smartypress-ai-engine' ),
				),
			)
		);
	}

	/**
	 * Enqueue image-generator module assets.
	 *
	 * Always loaded on the plugin admin page so the module UI is available
	 * immediately after activation without a full page reload.
	 *
	 * @param array $settings Plugin settings.
	 */
	private function enqueue_image_generator_assets( $settings ) {
		$ig_dir = SMARTYPRESS_AI_PLUGIN_DIR . 'includes/modules/image-generator/assets/dist/';
		$ig_url = SMARTYPRESS_AI_PLUGIN_URL . 'includes/modules/image-generator/assets/dist/';

		$ig_js_file = $ig_dir . 'image-generator.js';
		if ( ! file_exists( $ig_js_file ) ) {
			return;
		}

		$ig_asset_file = $ig_dir . 'image-generator.asset.php';
		if ( file_exists( $ig_asset_file ) ) {
			$ig_asset = require $ig_asset_file;
		} else {
			$ig_asset = array(
				'dependencies' => array( 'react', 'react-dom', 'wp-api-fetch', 'wp-components', 'wp-element', 'wp-i18n' ),
				'version'      => SMARTYPRESS_AI_VERSION,
			);
		}

		$ig_css_file    = $ig_dir . 'image-generator.css';
		$ig_js_version  = filemtime( $ig_js_file );
		$ig_css_version = file_exists( $ig_css_file ) ? filemtime( $ig_css_file ) : SMARTYPRESS_AI_VERSION;

		wp_enqueue_script(
			'smartypress-ai-image-generator',
			$ig_url . 'image-generator.js',
			array_merge( $ig_asset['dependencies'], array( 'react', 'react-dom' ) ),
			$ig_js_version,
			true
		);

		// Set script translations for image generator
		wp_set_script_translations(
			'smartypress-ai-image-generator',
			'smartypress-ai-engine',
			SMARTYPRESS_AI_PLUGIN_DIR . 'languages'
		);

		if ( file_exists( $ig_css_file ) ) {
			wp_enqueue_style(
				'smartypress-ai-image-generator',
				$ig_url . 'image-generator.css',
				array( 'wp-components' ),
				$ig_css_version
			);
		}

		$available_providers = SmartyPress_AI_Providers::get_available_providers();

		wp_localize_script(
			'smartypress-ai-image-generator',
			'smartypressAIImageGenerator',
			array(
				'restUrl'        => rest_url( 'smartypress/v1/' ),
				'nonce'          => wp_create_nonce( 'wp_rest' ),
				'pluginUrl'      => SMARTYPRESS_AI_PLUGIN_URL . 'includes/modules/image-generator/',
				'settings'       => $settings,
				'imageModels'    => $this->get_image_provider_models(),
				'providerModels' => $this->get_provider_models(),
				'providers'      => array_keys( $available_providers ),
				'isRuLocale'     => ( get_locale() === 'ru_RU' ),
			)
		);
	}

	/**
	 * Add type="module" attribute to admin app script (if needed)
	 * For IIFE format, type="module" is not required
	 *
	 * @param string $tag    The script tag.
	 * @param string $handle The script handle.
	 * @return string Modified script tag.
	 */
	public function add_module_type( $tag, $handle ) {
		// IIFE format doesn't need type="module"
		// But if we switch to ES modules, uncomment this:
		/*
		if ( 'smartypress-ai-admin-app' === $handle ) {
			if ( strpos( $tag, 'type=' ) === false ) {
				$tag = str_replace( '<script ', '<script type="module" ', $tag );
			}
		}
		*/
		return $tag;
	}

	/**
	 * Render page
	 */
	/**
	 * Add custom styles for menu icon
	 */
	/**
	 * Add custom styles for menu icon
	 */
	public function add_menu_icon_styles() {
		?>
		<style>
			#toplevel_page_smartypress-ai .wp-menu-image img {
				width: 22px !important;
				height: 22px !important;
				padding: 4px 0 0 !important;
				object-fit: contain;
			}
			/* Active/selected state - white filter */
			#toplevel_page_smartypress-ai.wp-has-current-submenu .wp-menu-image img,
			#toplevel_page_smartypress-ai.current .wp-menu-image img {
				filter: brightness(0) invert(1);
			}
			/* Hover state only - change icon */
			#toplevel_page_smartypress-ai:hover .wp-menu-image img {
				content: url('<?php echo esc_url( SMARTYPRESS_AI_PLUGIN_URL . 'assets/images/menu-icon-icon35x35_2.png' ); ?>');
				filter: none;
			}
		</style>
		<?php
	}

	/**
	 * Render admin page
	 */
	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		?>
		<div class="wrap">
			<div id="smartypress-ai-admin-root"></div>
		</div>
		<?php
	}

	/**
	 * Add AI generation buttons next to "Add New" on post/page list screens
	 */
	public function add_ai_buttons_to_post_list() {
		$screen = get_current_screen();

		// Only for post and page list screens
		if ( ! $screen || ! in_array( $screen->post_type, array( 'post', 'page' ), true ) ) {
			return;
		}

		$post_type   = $screen->post_type;
		$button_text = ( 'post' === $post_type )
			? __( 'Create Post via AI', 'smartypress-ai-engine' )
			: __( 'Create Page via AI', 'smartypress-ai-engine' );

		$target_url = admin_url( 'admin.php?page=smartypress-ai#/content-generation' );

		?>
		<style>
			.smartypress-ai-add-button {
				position: relative;
				display: inline-flex;
				align-items: center;
				gap: 6px;
				background: transparent;
				border: none;
				padding: 6px 14px;
				font-size: 13px;
				font-weight: 600;
				color: #1e1e1e;
				cursor: pointer;
				white-space: nowrap;
				text-decoration: none;
				line-height: 1.4;
				border-radius: 4px;
				transition: background 0.2s ease;
				margin-left: 8px;
			}

			.smartypress-ai-add-button::before {
				content: '';
				position: absolute;
				inset: 0;
				border-radius: 4px;
				padding: 2px;
				background: linear-gradient(90deg, #2271B1, #E84393, #2271B1, #E84393);
				background-size: 200% 100%;
				animation: smartypress-border-flow 4s ease-in-out infinite;
				-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
				-webkit-mask-composite: xor;
				mask-composite: exclude;
				z-index: -1;
			}

			.smartypress-ai-add-button:hover {
				background: rgba(34, 113, 177, 0.08);
			}

			.smartypress-ai-add-button-icon {
				width: 16px;
				height: 16px;
				flex-shrink: 0;
			}

			@keyframes smartypress-border-flow {
				0%, 100% { background-position: 0% 50%; }
				50% { background-position: 100% 50%; }
			}
		</style>
		<script>
		jQuery(document).ready(function($) {
			var buttonHtml = '<a href="<?php echo esc_url( $target_url ); ?>" class="smartypress-ai-add-button">' +
				'<svg class="smartypress-ai-add-button-icon" width="16" height="16" viewBox="0 0 1000 1000" fill="none" xmlns="http://www.w3.org/2000/svg">' +
				'<path d="M825 788a38 38 0 0 0 38-38 63 63 0 0 1 62-62 38 38 0 0 0 0-75 63 63 0 0 1-62-63 38 38 0 0 0-75 0 63 63 0 0 1-63 63 38 38 0 0 0 0 75 63 63 0 0 1 63 62 38 38 0 0 0 37 38z m0-132a137 137 0 0 0-6-6 135 135 0 0 0 6-6 137 137 0 0 0 6 6 134 134 0 0 0-6 6z m-450 32a38 38 0 0 0 38-38 263 263 0 0 1 262-262 38 38 0 0 0 0-75 263 263 0 0 1-262-263 38 38 0 0 0-75 0 263 263 0 0 1-263 263 38 38 0 0 0 0 75 263 263 0 0 1 263 262 38 38 0 0 0 37 38z m0-193a337 337 0 0 0-145-145 338 338 0 0 0 145-145 337 337 0 0 0 145 145 337 337 0 0 0-145 145z m450-307a38 38 0 0 0 38-38 63 63 0 0 1 62-62 38 38 0 0 0 0-75 63 63 0 0 1-62-63 38 38 0 0 0-75 0 63 63 0 0 1-63 63 38 38 0 0 0 0 75 63 63 0 0 1 63 62 38 38 0 0 0 37 38z m0-132a136 136 0 0 0-6-6 136 136 0 0 0 6-6 136 136 0 0 0 6 6 136 136 0 0 0-6 6z" fill="#F59E0B"/>' +
				'</svg>' +
				'<?php echo esc_js( $button_text ); ?>' +
				'</a>';

			// Find the "Add New" button and insert after it
			$('.wrap .page-title-action').first().after(buttonHtml);
		});
		</script>
		<?php
	}

	/**
	 * Add "Create attachment with AI" button on media library (upload.php) page
	 */
	public function add_ai_button_to_media_library() {
		if ( ! current_user_can( 'upload_files' ) ) {
			return;
		}

		$target_url = admin_url( 'admin.php?page=smartypress-ai#/image-generation' );
		$button_text = __( 'Create attachment with AI', 'smartypress-ai-engine' );

		?>
		<style>
			.smartypress-ai-add-button {
				position: relative;
				display: inline-flex;
				align-items: center;
				gap: 6px;
				background: transparent;
				border: none;
				padding: 6px 14px;
				font-size: 13px;
				font-weight: 600;
				color: #1e1e1e;
				cursor: pointer;
				white-space: nowrap;
				text-decoration: none;
				line-height: 1.4;
				border-radius: 4px;
				transition: background 0.2s ease;
				margin-left: 8px;
			}

			.smartypress-ai-add-button::before {
				content: '';
				position: absolute;
				inset: 0;
				border-radius: 4px;
				padding: 2px;
				background: linear-gradient(90deg, #2271B1, #E84393, #2271B1, #E84393);
				background-size: 200% 100%;
				animation: smartypress-border-flow 4s ease-in-out infinite;
				-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
				-webkit-mask-composite: xor;
				mask-composite: exclude;
				z-index: -1;
			}

			.smartypress-ai-add-button:hover {
				background: rgba(34, 113, 177, 0.08);
			}

			.smartypress-ai-add-button-icon {
				width: 16px;
				height: 16px;
				flex-shrink: 0;
			}

			@keyframes smartypress-border-flow {
				0%, 100% { background-position: 0% 50%; }
				50% { background-position: 100% 50%; }
			}
		</style>
		<script>
		jQuery(document).ready(function($) {
			var buttonHtml = '<a href="<?php echo esc_url( $target_url ); ?>" class="smartypress-ai-add-button">' +
				'<svg class="smartypress-ai-add-button-icon" width="16" height="16" viewBox="0 0 1000 1000" fill="none" xmlns="http://www.w3.org/2000/svg">' +
				'<path d="M825 788a38 38 0 0 0 38-38 63 63 0 0 1 62-62 38 38 0 0 0 0-75 63 63 0 0 1-62-63 38 38 0 0 0-75 0 63 63 0 0 1-63 63 38 38 0 0 0 0 75 63 63 0 0 1 63 62 38 38 0 0 0 37 38z m0-132a137 137 0 0 0-6-6 135 135 0 0 0 6-6 137 137 0 0 0 6 6 134 134 0 0 0-6 6z m-450 32a38 38 0 0 0 38-38 263 263 0 0 1 262-262 38 38 0 0 0 0-75 263 263 0 0 1-262-263 38 38 0 0 0-75 0 263 263 0 0 1-263 263 38 38 0 0 0 0 75 263 263 0 0 1 263 262 38 38 0 0 0 37 38z m0-193a337 337 0 0 0-145-145 338 338 0 0 0 145-145 337 337 0 0 0 145 145 337 337 0 0 0-145 145z m450-307a38 38 0 0 0 38-38 63 63 0 0 1 62-62 38 38 0 0 0 0-75 63 63 0 0 1-62-63 38 38 0 0 0-75 0 63 63 0 0 1-63 63 38 38 0 0 0 0 75 63 63 0 0 1 63 62 38 38 0 0 0 37 38z m0-132a136 136 0 0 0-6-6 136 136 0 0 0 6-6 136 136 0 0 0 6 6 136 136 0 0 0-6 6z" fill="#F59E0B"/>' +
				'</svg>' +
				'<?php echo esc_js( $button_text ); ?>' +
				'</a>';

			$('.wrap .page-title-action').first().after(buttonHtml);
		});
		</script>
		<?php
	}

	/**
	 * Show admin notice if API keys are not configured
	 */
	public function show_api_key_notice() {
		// Show on all admin pages for users who can manage options
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Get settings
		$settings = get_option( 'smartypress_ai_settings', array() );
		
		// Check if at least one API key is configured
		$has_openai_key   = ! empty( $settings['openai_api_key'] );
		$has_deepseek_key = ! empty( $settings['deepseek_api_key'] );
		$has_anthropic_key = ! empty( $settings['anthropic_api_key'] );
		$has_yandex_key   = ! empty( $settings['yandex_api_key'] ) && ! empty( $settings['yandex_folder_id'] );
		$has_gigachat_key = ! empty( $settings['gigachat_auth_key'] );

		// If at least one key is configured, don't show the notice
		if ( $has_openai_key || $has_deepseek_key || $has_anthropic_key || $has_yandex_key || $has_gigachat_key ) {
			return;
		}

		// Show notice
		$settings_url      = admin_url( 'admin.php?page=smartypress-ai#/settings' );
		$documentation_url = 'https://wp-aifactory.com/step-by-step-guide-to-smartypress-free-ai-engine/';

		// Provider list depends on locale
		if ( get_locale() === 'ru_RU' ) {
			$providers_text = __( 'To start using the plugin, add an API key from one of the providers (OpenAI, Deepseek, Claude, Yandex GPT or GigaChat) in the settings.', 'smartypress-ai-engine' );
		} else {
			$providers_text = __( 'To start using the plugin, add an API key from one of the providers (OpenAI, Deepseek or Claude) in the settings.', 'smartypress-ai-engine' );
		}
		?>
		<div class="notice notice-warning is-dismissible smartypress-ai-api-key-notice">
			<p>
				<strong><?php echo esc_html__( 'SmartyPress AI Engine:', 'smartypress-ai-engine' ); ?></strong>
				<?php echo esc_html( $providers_text ); ?>
			</p>
			<p>
				<a href="<?php echo esc_url( $settings_url ); ?>" class="button button-primary">
					<?php echo esc_html__( 'Go to Settings', 'smartypress-ai-engine' ); ?>
				</a>
				<a href="<?php echo esc_url( $documentation_url ); ?>" class="button" target="_blank" rel="noopener noreferrer">
					<?php echo esc_html__( 'View Documentation', 'smartypress-ai-engine' ); ?>
				</a>
			</p>
		</div>
		<style>
			.smartypress-ai-api-key-notice {
				border-left-color: #f59e0b;
			}
			.smartypress-ai-api-key-notice p:first-child {
				margin-bottom: 0.5em;
			}
			.smartypress-ai-api-key-notice p:last-child {
				margin-top: 0.5em;
				margin-bottom: 0;
			}
			.smartypress-ai-api-key-notice .button {
				margin-right: 10px;
			}
		</style>
		<?php
	}

	/**
	 * Show admin notice if permalinks are not configured
	 */
	public function show_permalink_notice() {
		// Only show on plugin pages
		$screen = get_current_screen();
		if ( ! $screen || strpos( $screen->id, 'smartypress-ai' ) === false ) {
			return;
		}

		// Check if permalinks are enabled
		if ( ! empty( get_option( 'permalink_structure' ) ) ) {
			return;
		}

		$permalink_settings_url = admin_url( 'options-permalink.php' );
		?>
		<div class="notice notice-error smartypress-ai-permalink-notice">
			<p>
				<strong><?php echo esc_html__( 'SmartyPress AI Engine:', 'smartypress-ai-engine' ); ?></strong>
				<?php
				echo esc_html__(
					'This plugin requires Pretty Permalinks to be enabled. REST API will not work with Plain permalinks.',
					'smartypress-ai-engine'
				);
				?>
			</p>
			<p>
				<a href="<?php echo esc_url( $permalink_settings_url ); ?>" class="button button-primary">
					<?php echo esc_html__( 'Configure Permalinks', 'smartypress-ai-engine' ); ?>
				</a>
			</p>
		</div>
		<style>
			.smartypress-ai-permalink-notice {
				border-left-color: #dc3232;
			}
			.smartypress-ai-permalink-notice p:first-child {
				margin-bottom: 0.5em;
			}
			.smartypress-ai-permalink-notice p:last-child {
				margin-top: 0.5em;
				margin-bottom: 0;
			}
		</style>
		<?php
	}

	/**
	 * Show review notice on all admin pages (except plugin pages where notices are hidden).
	 */
	public function show_review_notice() {
		if ( ! current_user_can( 'edit_posts' ) ) {
			return;
		}

		$screen = get_current_screen();
		if ( $screen && strpos( $screen->id, 'smartypress-ai' ) !== false ) {
			return;
		}

		$activated_at = get_option( 'smartypress_ai_activated_at' );
		if ( ! $activated_at ) {
			$activated_at = time();
			add_option( 'smartypress_ai_activated_at', $activated_at );
		}

		$user_id     = get_current_user_id();
		$dismissed_at = get_user_meta( $user_id, 'smartypress_ai_review_dismissed_at', true );
		$dismiss_count = (int) get_user_meta( $user_id, 'smartypress_ai_review_dismiss_count', true );

		if ( ! defined( 'SMARTYPRESS_AI_REVIEW_NOTICE_DEBUG' ) || ! SMARTYPRESS_AI_REVIEW_NOTICE_DEBUG ) {
			if ( $dismiss_count >= 4 ) {
				return;
			}

			$now = time();
			if ( $dismiss_count === 0 ) {
				if ( $now < $activated_at + 7 * DAY_IN_SECONDS ) {
					return;
				}
			} else {
				$intervals = array( 30 * DAY_IN_SECONDS, 90 * DAY_IN_SECONDS, 180 * DAY_IN_SECONDS );
				$idx = min( $dismiss_count - 1, count( $intervals ) - 1 );
				if ( $now < (int) $dismissed_at + $intervals[ $idx ] ) {
					return;
				}
			}
		}

		$review_url = ( get_locale() === 'ru_RU' )
			? 'https://ru.wordpress.org/plugins/smartypress-ai-engine/#description'
			: 'https://wordpress.org/plugins/smartypress-ai-engine/#description';

		$heading     = __( 'SmartyPress AI — Love it? Rate us!', 'smartypress-ai-engine' );
		$message     = __( 'If you enjoy SmartyPress AI, please leave a review and share your ideas for improvement on WordPress.org. It helps us grow!', 'smartypress-ai-engine' );
		$rate_text   = __( 'Rate us', 'smartypress-ai-engine' );
		$later_text  = __( 'Maybe later', 'smartypress-ai-engine' );
		$nonce       = wp_create_nonce( 'smartypress_ai_dismiss_review' );
		wp_enqueue_style( 'dashicons' );
		?>
		<div class="notice smartypress-ai-review-notice" data-nonce="<?php echo esc_attr( $nonce ); ?>">
			<button type="button" class="spai-review-close smartypress-ai-review-dismiss" aria-label="<?php esc_attr_e( 'Dismiss', 'smartypress-ai-engine' ); ?>">
				<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
			</button>
			<div class="spai-review-inner">
				<div class="spai-review-icon" aria-hidden="true">
					<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48" fill="none">
						<!-- 5 stars row -->
						<g transform="translate(2, 6)">
							<polygon points="5,0 6.5,3.5 10,3.8 7.3,6.2 8.1,9.7 5,7.9 1.9,9.7 2.7,6.2 0,3.8 3.5,3.5" fill="#f0b849"/>
							<polygon points="14,0 15.5,3.5 19,3.8 16.3,6.2 17.1,9.7 14,7.9 10.9,9.7 11.7,6.2 9,3.8 12.5,3.5" fill="#f0b849"/>
							<polygon points="23,0 24.5,3.5 28,3.8 25.3,6.2 26.1,9.7 23,7.9 19.9,9.7 20.7,6.2 18,3.8 21.5,3.5" fill="#f0b849"/>
							<polygon points="32,0 33.5,3.5 37,3.8 34.3,6.2 35.1,9.7 32,7.9 28.9,9.7 29.7,6.2 27,3.8 30.5,3.5" fill="#f0b849"/>
							<polygon points="41,0 42.5,3.5 46,3.8 43.3,6.2 44.1,9.7 41,7.9 37.9,9.7 38.7,6.2 36,3.8 39.5,3.5" fill="#f0b849"/>
						</g>
						<!-- Cursor pointer -->
						<g transform="translate(28, 22)">
							<path d="M0,0 L0,14 L3.5,11 L6.5,17 L9,16 L6,10 L10.5,10 Z" fill="#555d66" stroke="#fff" stroke-width="0.8"/>
						</g>
					</svg>
				</div>
				<div class="spai-review-body">
					<strong class="spai-review-heading"><?php echo esc_html( $heading ); ?></strong>
					<span class="spai-review-text"><?php echo esc_html( $message ); ?></span>
					<span class="spai-review-actions">
						<a href="<?php echo esc_url( $review_url ); ?>" class="spai-btn spai-btn-rate" target="_blank" rel="noopener noreferrer">
							<span class="dashicons dashicons-star-filled"></span><?php echo esc_html( $rate_text ); ?>
						</a>
						<button type="button" class="spai-btn spai-btn-later smartypress-ai-review-dismiss">
							<span class="dashicons dashicons-clock"></span><?php echo esc_html( $later_text ); ?>
						</button>
					</span>
				</div>
			</div>
		</div>
		<style>
			.smartypress-ai-review-notice {
				position: relative;
				border-left-color: #f0b849;
				padding: 12px 40px 12px 16px;
				background: #fffdf5;
			}
			.spai-review-close {
				position: absolute;
				top: 8px;
				right: 8px;
				padding: 4px;
				background: transparent;
				border: none;
				cursor: pointer;
				color: #8c8f94;
				line-height: 1;
			}
			.spai-review-close:hover {
				color: #1d2327;
			}
			.spai-review-close .dashicons {
				font-size: 18px;
				width: 18px;
				height: 18px;
			}
			.spai-review-inner {
				display: flex;
				align-items: center;
				gap: 16px;
			}
			.spai-review-icon {
				flex-shrink: 0;
				line-height: 0;
			}
			.spai-review-body {
				display: flex;
				flex-direction: column;
				gap: 4px;
			}
			.spai-review-heading {
				font-size: 14px;
				color: #1d2327;
			}
			.spai-review-text {
				font-size: 13px;
				color: #50575e;
				line-height: 1.5;
			}
			.spai-review-actions {
				display: flex;
				gap: 8px;
				margin-top: 6px;
			}
			.spai-btn {
				display: inline-flex;
				align-items: center;
				gap: 4px;
				padding: 4px 12px;
				border-radius: 4px;
				font-size: 13px;
				font-weight: 500;
				line-height: 1.6;
				text-decoration: none;
				cursor: pointer;
				border: 1px solid;
				box-sizing: border-box;
			}
			.spai-btn .dashicons {
				font-size: 15px;
				width: 15px;
				height: 15px;
				line-height: 15px;
			}
			.spai-btn-rate {
				background: #f0b849;
				border-color: #d4a02a;
				color: #1d2327;
			}
			.spai-btn-rate:hover,
			.spai-btn-rate:focus {
				background: #f5c95a;
				border-color: #c9961e;
				color: #1d2327;
			}
			.spai-btn-rate .dashicons { color: #8a6d19; }
			.spai-btn-later {
				background: #f0f0f1;
				border-color: #c3c4c7;
				color: #50575e;
			}
			.spai-btn-later:hover,
			.spai-btn-later:focus {
				background: #e5e5e6;
				border-color: #b4b4b4;
				color: #1d2327;
			}
			.spai-btn-later .dashicons { color: #8c8f94; }
		</style>
		<script>
		(function() {
			var btns = document.querySelectorAll('.smartypress-ai-review-dismiss');
			btns.forEach(function(btn) {
				btn.addEventListener('click', function() {
					var notice = btn.closest('.smartypress-ai-review-notice');
					if (!notice) return;
					var nonce = notice.getAttribute('data-nonce');
					fetch('<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>', {
						method: 'POST',
						headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
						body: 'action=smartypress_ai_dismiss_review_notice&nonce=' + encodeURIComponent(nonce)
					}).then(function() {
						notice.style.display = 'none';
					});
				});
			});
		})();
		</script>
		<?php
	}

	/**
	 * AJAX handler for dismissing the review notice.
	 */
	public function ajax_dismiss_review_notice() {
		check_ajax_referer( 'smartypress_ai_dismiss_review', 'nonce' );
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error();
		}
		$user_id = get_current_user_id();
		$count = (int) get_user_meta( $user_id, 'smartypress_ai_review_dismiss_count', true );
		update_user_meta( $user_id, 'smartypress_ai_review_dismissed_at', time() );
		update_user_meta( $user_id, 'smartypress_ai_review_dismiss_count', $count + 1 );
		wp_send_json_success();
	}

	/**
	 * Show a one-time notice asking users upgrading from older versions to re-enter
	 * their Yandex service account API key (the OAuth token flow was removed).
	 */
	public function show_yandex_reauth_notice() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		if ( ! get_option( 'smartypress_ai_yandex_reauth_required' ) ) {
			return;
		}

		// If a Yandex API key has since been configured, the migration is complete.
		$settings = get_option( 'smartypress_ai_settings', array() );
		if ( is_array( $settings ) && ! empty( $settings['yandex_api_key'] ) ) {
			delete_option( 'smartypress_ai_yandex_reauth_required' );
			return;
		}

		$settings_url = admin_url( 'admin.php?page=smartypress-ai#/settings' );
		$nonce        = wp_create_nonce( 'smartypress_ai_dismiss_yandex_reauth' );
		?>
		<div class="notice notice-warning is-dismissible smartypress-ai-yandex-reauth-notice" data-nonce="<?php echo esc_attr( $nonce ); ?>">
			<p>
				<strong><?php echo esc_html__( 'SmartyPress AI Engine:', 'smartypress-ai-engine' ); ?></strong>
				<?php
				echo esc_html__(
					'Yandex integration now uses a service account API key instead of an OAuth token. Please re-enter your Yandex API key in the settings to keep YandexGPT and YandexART working.',
					'smartypress-ai-engine'
				);
				?>
			</p>
			<p>
				<a href="<?php echo esc_url( $settings_url ); ?>" class="button button-primary">
					<?php echo esc_html__( 'Go to Settings', 'smartypress-ai-engine' ); ?>
				</a>
			</p>
		</div>
		<style>
			.smartypress-ai-yandex-reauth-notice {
				border-left-color: #f59e0b;
			}
			.smartypress-ai-yandex-reauth-notice p:first-child {
				margin-bottom: 0.5em;
			}
			.smartypress-ai-yandex-reauth-notice p:last-child {
				margin-top: 0.5em;
				margin-bottom: 0;
			}
		</style>
		<script>
		(function() {
			var notice = document.querySelector('.smartypress-ai-yandex-reauth-notice');
			if (!notice) return;
			notice.addEventListener('click', function(e) {
				if (!e.target.classList.contains('notice-dismiss')) return;
				var nonce = notice.getAttribute('data-nonce');
				fetch('<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>', {
					method: 'POST',
					headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
					body: 'action=smartypress_ai_dismiss_yandex_reauth_notice&nonce=' + encodeURIComponent(nonce)
				});
			});
		})();
		</script>
		<?php
	}

	/**
	 * AJAX handler for dismissing the Yandex re-authentication notice.
	 */
	public function ajax_dismiss_yandex_reauth_notice() {
		check_ajax_referer( 'smartypress_ai_dismiss_yandex_reauth', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error();
		}
		delete_option( 'smartypress_ai_yandex_reauth_required' );
		wp_send_json_success();
	}
}

