<?php
/**
 * WPFAQBlock Settings Page
 *
 * Provides a settings page under WPFAQBlock for storing:
 *   - OpenAI API Key (for AI FAQ Generator)
 *   - Google Gemini API Key
 *
 * @package WPFAQBlock
 * @since   2.0.0
 */

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

/**
 * Class WPFAQBlock_Settings
 */
class WPFAQBlock_Settings
{

	/** Option key for API key. */
	const OPTION_AI_KEY = 'wpfaqblock_openai_api_key';
	/** Option key for Gemini API key. */
	const OPTION_GEMINI_KEY = 'wpfaqblock_gemini_api_key';
	/** Option key for FAQ Schema output. */
	const OPTION_SCHEMA_ENABLED = 'wpfaqblock_schema_enabled';

	/** Settings group/page slug. */
	const PAGE_SLUG = 'wpfaqblock-settings';

	// ──────────────────────────────────────────────
	// Registration
	// ──────────────────────────────────────────────

	/**
	 * Register settings submenu and WP Settings API.
	 *
	 * @since 2.0.0
	 * @return void
	 */
	public function register(): void
	{
		add_action('admin_menu', array($this, 'add_settings_submenu'), 20);
		add_action('admin_init', array($this, 'register_settings'));
		add_action('admin_enqueue_scripts', array($this, 'enqueue_settings_assets'));
	}

	/**
	 * Add Settings submenu under WPFAQBlock menu.
	 *
	 * @since 2.0.0
	 * @return void
	 */
	public function add_settings_submenu(): void
	{
		add_submenu_page(
			'wpfaqblock',
			__('Settings', 'wpfaqblock'),
			__('Settings', 'wpfaqblock'),
			'manage_options',
			self::PAGE_SLUG,
			array($this, 'render_settings_page')
		);
	}

	/**
	 * Enqueue settings page specific CSS.
	 *
	 * @since 2.0.0
	 * @param string $hook_suffix Current admin page hook.
	 * @return void
	 */
	public function enqueue_settings_assets(string $hook_suffix): void
	{
		if ('wpfaqblock_page_wpfaqblock-settings' !== $hook_suffix) {
			return;
		}

		wp_enqueue_style(
			'wpfaqblock-admin-setting',
			WPFAQBLOCK_URL . 'assets/css/wpfaqblock-admin-setting.css',
			array(),
			filemtime(WPFAQBLOCK_DIR . 'assets/css/wpfaqblock-admin-setting.css')
		);

		// Also enqueue the builder CSS for shared tokens & topbar.
		wp_enqueue_style(
			'wpfaqblock-admin-builder',
			WPFAQBLOCK_URL . 'assets/css/admin-builder.css',
			array(),
			filemtime(WPFAQBLOCK_DIR . 'assets/css/admin-builder.css')
		);
	}

	/**
	 * Register settings with WP Settings API.
	 *
	 * @since 2.0.0
	 * @return void
	 */
	public function register_settings(): void
	{
		register_setting(
			'wpfaqblock_settings_group',
			self::OPTION_AI_KEY,
			array(
				'type' => 'string',
				'sanitize_callback' => 'sanitize_text_field',
				'default' => '',
			)
		);

		register_setting(
			'wpfaqblock_settings_group',
			self::OPTION_GEMINI_KEY,
			array(
				'type' => 'string',
				'sanitize_callback' => 'sanitize_text_field',
				'default' => '',
			)
		);

		register_setting(
			'wpfaqblock_settings_group',
			self::OPTION_SCHEMA_ENABLED,
			array(
				'type' => 'string',
				'sanitize_callback' => array($this, 'sanitize_checkbox'),
				'default' => '',
			)
		);

		add_settings_section(
			'wpfaqblock_schema_section',
			'',
			array($this, 'render_schema_section_description'),
			self::PAGE_SLUG
		);

		add_settings_field(
			'wpfaqblock_schema_enabled_field',
			__('FAQ Schema', 'wpfaqblock'),
			array($this, 'render_schema_enabled_field'),
			self::PAGE_SLUG,
			'wpfaqblock_schema_section'
		);

		add_settings_section(
			'wpfaqblock_ai_section',
			'', // Title intentionally empty — rendered inside our custom icon header
			array($this, 'render_ai_section_description'),
			self::PAGE_SLUG
		);

		add_settings_field(
			'wpfaqblock_openai_key_field',
			__('OpenAI API Key (ChatGPT)', 'wpfaqblock'),
			array($this, 'render_api_key_field'),
			self::PAGE_SLUG,
			'wpfaqblock_ai_section'
		);

		add_settings_field(
			'wpfaqblock_gemini_key_field',
			__('Google Gemini API Key', 'wpfaqblock'),
			array($this, 'render_gemini_key_field'),
			self::PAGE_SLUG,
			'wpfaqblock_ai_section'
		);
	}

	// ──────────────────────────────────────────────
	// Renderers
	// ──────────────────────────────────────────────

	/**
	 * Render the settings page wrapper.
	 *
	 * @since 2.0.0
	 * @return void
	 */
	public function render_settings_page(): void
	{
		if (!current_user_can('manage_options')) {
			wp_die(esc_html__('You do not have permission to access this page.', 'wpfaqblock'));
		}
		?>
		<div id="wpfaqblock-builder" class="faqb-settings-page">

			<!-- TOP BAR -->
			<div class="faqb-topbar">
				<div class="faqb-topbar__brand">
					<img src="<?php echo esc_url(WPFAQBLOCK_URL . 'assets/images/logo.svg'); ?>" alt="WPFAQBlock Logo"
						style="height: 45px; width: auto;">
				</div>
				<div class="faqb-topbar__actions">
					<a href="<?php echo esc_url(admin_url('admin.php?page=wpfaqblock')); ?>"
						class="faqb-btn faqb-btn--outline faqb-btn--sm">
						<span class="dashicons dashicons-arrow-left-alt" style="font-size:14px;width:14px;height:14px;margin-top:3px;"></span>
						<?php esc_html_e('Back to Dashboard', 'wpfaqblock'); ?>
					</a>
				</div>
			</div>

			<!-- MAIN LAYOUT -->
			<div class="faqb-settings-layout">

				<!-- Page header -->
				<div class="faqb-settings-header">
					<h1 class="faqb-settings-header__title">
						<?php esc_html_e('Plugin Settings', 'wpfaqblock'); ?>
					</h1>
					<p class="faqb-settings-header__subtitle">
						<?php esc_html_e('Configure global schema output, display preferences, and API keys.', 'wpfaqblock'); ?>
					</p>
				</div>

				<!-- Settings card -->
				<div class="faqb-settings-card">
					<form method="post" action="options.php">
						<?php settings_fields('wpfaqblock_settings_group'); ?>
						<?php do_settings_sections(self::PAGE_SLUG); ?>
						<div class="faqb-settings-footer">
							<?php
							submit_button(
								__('Save Changes', 'wpfaqblock'),
								'faqb-btn faqb-btn--primary',
								'submit',
								false
							);
							?>
						</div>
					</form>
				</div>

			</div>
		</div>
		<?php
	}

	/**
	 * Render the AI section description / header.
	 *
	 * @since 2.0.0
	 * @return void
	 */
	public function render_ai_section_description(): void
	{
		?>
		<div class="faqb-section-head">
			<div class="faqb-section-head__icon">
				<span class="dashicons dashicons-admin-network"></span>
			</div>
			<div class="faqb-section-head__text">
				<h3>
					<?php esc_html_e('AI FAQ Generator', 'wpfaqblock'); ?>
				</h3>
				<p><?php esc_html_e('Enter your API keys to enable AI-powered FAQ generation. Keys are stored securely and never exposed on the front-end.', 'wpfaqblock'); ?></p>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the OpenAI API key input field.
	 *
	 * @since 2.0.0
	 * @return void
	 */
	public function render_api_key_field(): void
	{
		$value = get_option(self::OPTION_AI_KEY, '');
		?>
		<div class="faqb-input-wrap">
			<span class="faqb-input-wrap__icon dashicons dashicons-lock"></span>
			<input
				type="password"
				name="<?php echo esc_attr(self::OPTION_AI_KEY); ?>"
				id="wpfaqblock_openai_api_key"
				value="<?php echo esc_attr($value); ?>"
				class="regular-text"
				autocomplete="new-password"
				placeholder="sk-..."
			>
		</div>
		<p class="description">
			<?php esc_html_e('Used for the primary AI generation engine.', 'wpfaqblock'); ?>
			&nbsp;<a href="https://platform.openai.com/api-keys" target="_blank" rel="noopener noreferrer">
				<?php esc_html_e('→ Get OpenAI API key', 'wpfaqblock'); ?>
			</a>
		</p>
		<?php
	}

	/**
	 * Render the Gemini API key input field.
	 *
	 * @since 2.0.0
	 * @return void
	 */
	public function render_gemini_key_field(): void
	{
		$value = get_option(self::OPTION_GEMINI_KEY, '');
		?>
		<div class="faqb-input-wrap">
			<span class="faqb-input-wrap__icon dashicons dashicons-google"></span>
			<input
				type="password"
				name="<?php echo esc_attr(self::OPTION_GEMINI_KEY); ?>"
				id="wpfaqblock_gemini_api_key"
				value="<?php echo esc_attr($value); ?>"
				class="regular-text"
				autocomplete="new-password"
				placeholder="AIza..."
			>
		</div>
		<p class="description">
			<?php esc_html_e('Gemini offers a free tier — great for getting started.', 'wpfaqblock'); ?>
			&nbsp;<a href="https://aistudio.google.com/app/apikey" target="_blank" rel="noopener noreferrer">
				<?php esc_html_e('→ Get Gemini API key', 'wpfaqblock'); ?>
			</a>
		</p>
		<?php
	}

	/**
	 * Render the FAQ Schema section description / header.
	 *
	 * @since 2.0.0
	 * @return void
	 */
	public function render_schema_section_description(): void
	{
		?>
		<div class="faqb-section-head">
			<div class="faqb-section-head__icon">
				<span class="dashicons dashicons-media-code"></span>
			</div>
			<div class="faqb-section-head__text">
				<h3>
					<?php esc_html_e('FAQ Schema', 'wpfaqblock'); ?>
				</h3>
				<p><?php esc_html_e('Optionally output FAQPage JSON-LD for FAQs that are visible on the current page.', 'wpfaqblock'); ?></p>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the FAQ Schema enabled checkbox.
	 *
	 * @since 2.0.0
	 * @return void
	 */
	public function render_schema_enabled_field(): void
	{
		$value = get_option(self::OPTION_SCHEMA_ENABLED, '');
		?>
		<label class="faqb-checkbox-field" for="wpfaqblock_schema_enabled">
			<input
				type="checkbox"
				name="<?php echo esc_attr(self::OPTION_SCHEMA_ENABLED); ?>"
				id="wpfaqblock_schema_enabled"
				value="1"
				<?php checked('1', $value); ?>
			>
			<span><?php esc_html_e('Enable FAQPage structured data output', 'wpfaqblock'); ?></span>
		</label>
		<p class="description">
			<?php esc_html_e('When enabled, schema is generated only from FAQs rendered by WPFAQBlock on that page. Repeated FAQs are de-duplicated automatically.', 'wpfaqblock'); ?>
		</p>
		<?php
	}

	/**
	 * Sanitize checkbox settings.
	 *
	 * @since 2.0.0
	 *
	 * @param mixed $value Raw value.
	 * @return string
	 */
	public function sanitize_checkbox($value): string
	{
		return '1' === (string) $value ? '1' : '';
	}

	// ──────────────────────────────────────────────
	// Static helper — used by AJAX handler
	// ──────────────────────────────────────────────

	/**
	 * Get the stored OpenAI API key.
	 *
	 * @since 2.0.0
	 * @return string Empty string if not set.
	 */
	public static function get_api_key(): string
	{
		return (string) get_option(self::OPTION_AI_KEY, '');
	}

	/**
	 * Get the stored Gemini API key.
	 *
	 * @since 2.0.0
	 * @return string
	 */
	public static function get_gemini_key(): string
	{
		return (string) get_option(self::OPTION_GEMINI_KEY, '');
	}

	/**
	 * Check whether FAQ Schema output is enabled.
	 *
	 * @since 2.0.0
	 * @return bool
	 */
	public static function is_schema_enabled(): bool
	{
		return '1' === (string) get_option(self::OPTION_SCHEMA_ENABLED, '');
	}
}
