<?php
/**
 * Settings class for AgenticWP plugin.
 *
 * @package AgenticWP
 */

namespace Agentic_WP;

defined( 'ABSPATH' ) || exit;

require_once plugin_dir_path( __FILE__ ) . 'class-settings-base.php';
require_once plugin_dir_path( __FILE__ ) . 'class-settings-api.php';
require_once plugin_dir_path( __FILE__ ) . 'class-settings-content.php';
require_once plugin_dir_path( __FILE__ ) . 'class-settings-jobs.php';
require_once plugin_dir_path( __FILE__ ) . 'class-settings-actions.php';
require_once plugin_dir_path( __FILE__ ) . 'class-settings-schema.php';
require_once plugin_dir_path( __FILE__ ) . 'class-meta-box-meta-description.php';
require_once plugin_dir_path( __FILE__ ) . 'class-meta-box-schema.php';

/**
 * Main settings class that orchestrates all settings functionality.
 */
class Settings {

	/**
	 * PayPal hosted button ID for donations.
	 *
	 * @var string
	 */
	private const PAYPAL_HOSTED_BUTTON_ID = 'DJ9GULXH8TZWC';

	/**
	 * API settings instance.
	 *
	 * @var Settings_API
	 */
	private $api_settings;

	/**
	 * Content settings instance.
	 *
	 * @var Settings_Content
	 */
	private $content_settings;

	/**
	 * Jobs settings instance.
	 *
	 * @var Settings_Jobs
	 */
	private $jobs_settings;

	/**
	 * Actions settings instance.
	 *
	 * @var Settings_Actions
	 */
	private $actions_settings;

	/**
	 * Schema settings instance.
	 *
	 * @var Settings_Schema
	 */
	private $schema_settings;

	/**
	 * Meta box meta description instance.
	 *
	 * @var Meta_Box_Meta_Description
	 */
	private $meta_box_meta_description;

	/**
	 * Meta box schema instance.
	 *
	 * @var Meta_Box_Schema
	 */
	private $meta_box_schema;

	/**
	 * Initialize settings and register hooks.
	 */
	public function __construct() {
		$this->api_settings     = new Settings_API();
		$this->content_settings = new Settings_Content();
		$this->jobs_settings    = new Settings_Jobs();
		$this->actions_settings = new Settings_Actions();
		$this->schema_settings  = new Settings_Schema();

		$this->meta_box_meta_description = new Meta_Box_Meta_Description();
		$this->meta_box_schema           = new Meta_Box_Schema();

		add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
		add_action( 'admin_init', array( $this, 'settings_init' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_scripts' ) );
	}

	/**
	 * Add settings page as submenu under Agentic WP.
	 *
	 * @return void
	 */
	public function add_admin_menu() {
		// Add Settings as submenu under Agentic WP (dashboard creates parent menu).
		add_submenu_page(
			'agenticwp-dashboard',
			__( 'Settings', 'agenticwp' ),
			__( 'Settings', 'agenticwp' ),
			'manage_options',
			'agenticwp-settings',
			array( $this, 'options_page' )
		);
	}

	/**
	 * Initialize and register all plugin settings.
	 *
	 * @return void
	 */
	public function settings_init() {
		$this->api_settings->register_settings();
		$this->content_settings->register_settings();
		$this->actions_settings->register_settings();
		$this->schema_settings->register_settings();

		add_settings_section(
			'agentic_wp_section',
			'AI Setup',
			null,
			'agentic_wp'
		);

		add_settings_section(
			'agentic_wp_chat_section',
			'Chat Settings',
			null,
			'agentic_wp'
		);

		add_settings_section(
			'agentic_wp_content_section',
			'Content Generation',
			null,
			'agentic_wp'
		);

		add_settings_section(
			'agentic_wp_actions_section',
			'Action Manager',
			null,
			'agentic_wp'
		);

		add_settings_section(
			'agentic_wp_schema_section',
			'SEO Schema',
			null,
			'agentic_wp'
		);

		$this->api_settings->add_settings_fields( 'agentic_wp_section' );
		$this->content_settings->add_settings_fields( 'agentic_wp_chat_section', 'agentic_wp_content_section' );
		$this->actions_settings->add_settings_fields( 'agentic_wp_actions_section' );
	}

	/**
	 * Render the settings page content.
	 *
	 * @return void
	 */
	public function options_page() {
		?>
		<div class="wrap">
			<h1>Agentic WP Settings</h1>
			<?php $this->render_tip_jar_banner(); ?>
			<form method="post" action="options.php" class="agenticwp-settings-wrapper">
				<?php settings_fields( 'agentic_wp' ); ?>

				<div class="agenticwp-settings-section agenticwp-section-light" data-section="openai-config">
					<div class="agenticwp-section-header">
						<h2><?php echo esc_html__( 'AI Setup', 'agenticwp' ); ?></h2>
						<button type="button" class="agenticwp-section-toggle" aria-expanded="true" aria-label="<?php esc_attr_e( 'Toggle AI Setup section', 'agenticwp' ); ?>">
							<span class="agenticwp-toggle-icon"></span>
						</button>
					</div>
					<div class="agenticwp-section-content">

					<div class="agenticwp-openai-config">
						<?php $this->api_settings->api_key_field(); ?>
						<?php $this->api_settings->model_field(); ?>

						<h3><?php echo esc_html__( 'Advanced Options', 'agenticwp' ); ?></h3>
						<div class="agenticwp-config-grid">
							<div class="agenticwp-config-field">
								<div class="agenticwp-field-header">
									<label for="agentic_wp_reasoning_effort"><?php echo esc_html__( 'Reasoning Effort', 'agenticwp' ); ?></label>
									<button type="button" class="agenticwp-tooltip-trigger" aria-label="<?php echo esc_attr__( 'Help', 'agenticwp' ); ?>" aria-expanded="false" aria-describedby="reasoning-effort-tooltip">
										<span class="dashicons dashicons-info-outline"></span>
									</button>
									<?php $this->api_settings->reasoning_effort_tooltip(); ?>
								</div>
								<?php $this->api_settings->reasoning_effort_field(); ?>
							</div>

							<div class="agenticwp-config-field">
								<div class="agenticwp-field-header">
									<label for="agentic_wp_max_output_tokens"><?php echo esc_html__( 'Response Length Limit', 'agenticwp' ); ?></label>
									<button type="button" class="agenticwp-tooltip-trigger" aria-label="<?php echo esc_attr__( 'Help', 'agenticwp' ); ?>" aria-expanded="false" aria-describedby="max-output-tokens-tooltip">
										<span class="dashicons dashicons-info-outline"></span>
									</button>
									<?php $this->api_settings->max_output_tokens_tooltip(); ?>
								</div>
								<?php $this->api_settings->max_output_tokens_field(); ?>
							</div>
						</div>

						<div class="agenticwp-config-grid">
							<div class="agenticwp-config-field">
								<div class="agenticwp-field-header">
									<label for="agentic_wp_message_history_limit"><?php echo esc_html__( 'Message History Limit', 'agenticwp' ); ?></label>
									<button type="button" class="agenticwp-tooltip-trigger" aria-label="<?php echo esc_attr__( 'Help', 'agenticwp' ); ?>" aria-expanded="false" aria-describedby="message-history-limit-tooltip">
										<span class="dashicons dashicons-info-outline"></span>
									</button>
									<?php $this->content_settings->message_history_limit_tooltip(); ?>
								</div>
								<?php $this->content_settings->message_history_limit_field(); ?>
							</div>

							<div class="agenticwp-config-field">
							</div>
						</div>

						<div class="agenticwp-options-grid">
							<?php $this->api_settings->toast_notifications_field(); ?>
							<?php $this->api_settings->web_search_field(); ?>
						</div>
					</div>
					</div>
				</div>

				<div class="agenticwp-settings-section agenticwp-section-dark" data-section="content-generation">
					<div class="agenticwp-section-header">
						<h2><?php echo esc_html__( 'Content Generation', 'agenticwp' ); ?></h2>
						<button type="button" class="agenticwp-section-toggle" aria-expanded="true" aria-label="<?php esc_attr_e( 'Toggle Content Generation section', 'agenticwp' ); ?>">
							<span class="agenticwp-toggle-icon"></span>
						</button>
					</div>
					<div class="agenticwp-section-content">

					<div class="agenticwp-settings-columns">
						<div class="agenticwp-field-group">
							<label for="agentic_wp_create_post_directions"><?php echo esc_html__( 'Writing Style Instructions', 'agenticwp' ); ?></label>
							<p class="description"><?php echo esc_html__( 'Tell the AI how you want your content to sound. For example, should it be professional and formal, or casual and friendly? This helps create content that matches your brand\'s voice.', 'agenticwp' ); ?></p>
							<?php $this->content_settings->writing_directions_field(); ?>
						</div>

						<div class="agenticwp-field-group">
							<?php $this->content_settings->default_image_field(); ?>
						</div>
					</div>
					</div>
				</div>

				<div class="agenticwp-settings-section agenticwp-section-light" data-section="action-manager">
					<div class="agenticwp-section-header">
						<h2><?php echo esc_html__( 'Action Manager', 'agenticwp' ); ?></h2>
						<button type="button" class="agenticwp-section-toggle" aria-expanded="true" aria-label="<?php esc_attr_e( 'Toggle Action Manager section', 'agenticwp' ); ?>">
							<span class="agenticwp-toggle-icon"></span>
						</button>
					</div>
					<div class="agenticwp-section-content">
						<div class="agenticwp-intro-text">
							<p><?php echo esc_html__( 'Create custom shortcuts that help the AI complete specific tasks quickly and consistently. These shortcuts work for any type of task - from content creation and SEO work to site management and troubleshooting.', 'agenticwp' ); ?></p>
						</div>

					<div class="agenticwp-field-group">
						<?php $this->actions_settings->actions_management_field(); ?>
					</div>
					</div>

				</div>

				<div class="agenticwp-settings-section agenticwp-section-dark" data-section="seo-schema">
					<div class="agenticwp-section-header">
						<h2><?php echo esc_html__( 'SEO Schema', 'agenticwp' ); ?></h2>
						<button type="button" class="agenticwp-section-toggle" aria-expanded="true" aria-label="<?php esc_attr_e( 'Toggle SEO Schema section', 'agenticwp' ); ?>">
							<span class="agenticwp-toggle-icon"></span>
						</button>
					</div>
					<div class="agenticwp-section-content">
						<div class="agenticwp-intro-text">
							<p><?php echo esc_html__( 'Configure organization information for structured data markup. This helps search engines understand your content and may improve search results appearance.', 'agenticwp' ); ?></p>
						</div>

						<div class="agenticwp-settings-columns">
							<div class="agenticwp-field-group">
								<label for="agentic_wp_organization_name"><?php echo esc_html__( 'Organization Name', 'agenticwp' ); ?></label>
								<?php $this->schema_settings->organization_name_field(); ?>
							</div>

							<div class="agenticwp-field-group">
								<label for="agentic_wp_organization_logo"><?php echo esc_html__( 'Organization Logo URL', 'agenticwp' ); ?></label>
								<?php $this->schema_settings->organization_logo_field(); ?>
							</div>
						</div>

						<div class="agenticwp-settings-columns">
							<div class="agenticwp-field-group">
								<label for="agentic_wp_organization_email"><?php echo esc_html__( 'Contact Email', 'agenticwp' ); ?></label>
								<?php $this->schema_settings->organization_email_field(); ?>
							</div>

							<div class="agenticwp-field-group">
								<label for="agentic_wp_organization_phone"><?php echo esc_html__( 'Contact Phone', 'agenticwp' ); ?></label>
								<?php $this->schema_settings->organization_phone_field(); ?>
							</div>
						</div>
					</div>
				</div>

				<div class="agenticwp-settings-section agenticwp-section-light" data-section="background-jobs">
					<div class="agenticwp-section-header">
						<h2><?php echo esc_html__( 'Background Jobs Monitor', 'agenticwp' ); ?></h2>
						<button type="button" class="agenticwp-section-toggle" aria-expanded="true" aria-label="<?php esc_attr_e( 'Toggle Background Jobs Monitor section', 'agenticwp' ); ?>">
							<span class="agenticwp-toggle-icon"></span>
						</button>
					</div>
					<div class="agenticwp-section-content">
						<?php $this->jobs_settings->background_jobs_section_callback(); ?>
					</div>
				</div>

				<?php submit_button(); ?>
			</form>
		</div>
		<?php
	}

	/**
	 * Render the tip jar banner.
	 *
	 * @return void
	 */
	private function render_tip_jar_banner(): void {
		?>
		<div class="agenticwp-tip-jar" data-tip-jar>
			<div class="agenticwp-tip-jar-icon"><span class="dashicons dashicons-heart"></span></div>
			<div class="agenticwp-tip-jar-content">
				<span class="agenticwp-tip-jar-title"><?php esc_html_e( 'Enjoying Agentic WP?', 'agenticwp' ); ?></span>
				<span class="agenticwp-tip-jar-message"><?php esc_html_e( 'Your support helps fund new features and improvements.', 'agenticwp' ); ?></span>
			</div>
			<div class="agenticwp-tip-jar-action">
				<form action="https://www.paypal.com/donate/?hosted_button_id=<?php echo esc_attr( self::PAYPAL_HOSTED_BUTTON_ID ); ?>" method="post" target="_blank">
					<input type="image" src="https://www.paypalobjects.com/en_AU/i/btn/btn_donate_SM.gif" name="submit" title="<?php esc_attr_e( 'Donate with PayPal', 'agenticwp' ); ?>" alt="<?php esc_attr_e( 'Donate with PayPal button', 'agenticwp' ); ?>">
				</form>
			</div>
			<button type="button" class="agenticwp-tip-jar-dismiss" aria-label="<?php esc_attr_e( 'Dismiss tip jar', 'agenticwp' ); ?>">
				<span class="dashicons dashicons-no-alt"></span>
			</button>
		</div>
		<?php
	}

	/**
	 * Get the OpenAI API key.
	 *
	 * @return string
	 */
	public static function get_api_key() {
		return Settings_API::get_api_key();
	}

	/**
	 * Get the selected OpenAI model.
	 *
	 * @return string
	 */
	public static function get_model() {
		return Settings_API::get_model();
	}

	/**
	 * Get the reasoning effort setting.
	 *
	 * @return string
	 */
	public static function get_reasoning_effort() {
		return Settings_API::get_reasoning_effort();
	}

	/**
	 * Get the maximum output tokens setting.
	 *
	 * @return int
	 */
	public static function get_max_output_tokens() {
		return Settings_API::get_max_output_tokens();
	}

	/**
	 * Get the message history limit setting.
	 *
	 * @return int
	 */
	public static function get_message_history_limit() {
		return Settings_Content::get_message_history_limit();
	}

	/**
	 * Get the writing style instructions.
	 *
	 * @return string
	 */
	public static function get_create_post_directions(): string {
		return Settings_Content::get_create_post_directions();
	}

	/**
	 * Get the session timeout in minutes.
	 *
	 * @return int
	 */
	public static function get_session_timeout_min(): int {
		return Settings_Content::get_session_timeout_min();
	}

	/**
	 * Get the post schema definition.
	 *
	 * @return array
	 */
	public static function get_post_schema(): array {
		return Settings_Content::get_post_schema();
	}

	/**
	 * Enqueue admin scripts and styles.
	 *
	 * @param string $hook Current admin page hook.
	 * @return void
	 */
	public function admin_scripts( $hook ) {
		if ( 'agentic-wp_page_agenticwp-settings' !== $hook ) {
			return;
		}

		$plugin_data = get_file_data(
			plugin_dir_path( __DIR__ ) . 'agenticwp.php',
			array( 'Version' => 'Version' )
		);
		$version     = $plugin_data['Version'] ?: '1.0.0';

		wp_enqueue_style(
			'agenticwp-admin',
			plugin_dir_url( __DIR__ ) . 'assets/css/admin.css',
			array(),
			$version
		);

		wp_enqueue_style(
			'agenticwp-tip-jar',
			plugin_dir_url( __DIR__ ) . 'assets/css/admin/tip-jar.css',
			array(),
			$version
		);

		if ( function_exists( 'wp_enqueue_media' ) ) {
			wp_enqueue_media();
		}

		$script_base = plugin_dir_url( __DIR__ ) . 'assets/js/admin/';

		wp_register_script(
			'agenticwp-admin-utils',
			$script_base . 'utils.js',
			array( 'jquery' ),
			$version,
			true
		);

		wp_register_script(
			'agenticwp-admin-api-keys',
			$script_base . 'api-keys.js',
			array( 'jquery', 'agenticwp-admin-utils' ),
			$version,
			true
		);

		wp_register_script(
			'agenticwp-admin-default-image',
			$script_base . 'default-image.js',
			array( 'jquery', 'agenticwp-admin-utils' ),
			$version,
			true
		);

		wp_register_script(
			'agenticwp-admin-character-counter',
			$script_base . 'character-counter.js',
			array( 'jquery' ),
			$version,
			true
		);

		wp_register_script(
			'agenticwp-admin-sample-prompts',
			$script_base . 'sample-prompts.js',
			array( 'jquery' ),
			$version,
			true
		);

		wp_register_script(
			'agenticwp-admin-job-monitor',
			$script_base . 'job-monitor.js',
			array( 'jquery', 'agenticwp-admin-utils' ),
			$version,
			true
		);

		wp_register_script(
			'agenticwp-admin-button-enhancements',
			$script_base . 'button-enhancements.js',
			array( 'jquery' ),
			$version,
			true
		);

		wp_register_script(
			'agenticwp-admin-actions-manager',
			$script_base . 'actions-manager.js',
			array( 'jquery' ),
			$version,
			true
		);

		wp_register_script(
			'agenticwp-admin-collapsible-sections',
			$script_base . 'collapsible-sections.js',
			array( 'jquery' ),
			$version,
			true
		);

		wp_register_script(
			'agenticwp-admin-model-selection',
			$script_base . 'model-selection.js',
			array( 'jquery', 'agenticwp-admin-utils' ),
			$version,
			true
		);

		wp_register_script(
			'agenticwp-admin-dropdown-auto-save',
			$script_base . 'dropdown-auto-save.js',
			array( 'jquery', 'agenticwp-admin-utils' ),
			$version,
			true
		);

		wp_register_script(
			'agenticwp-admin-tooltips',
			$script_base . 'tooltips.js',
			array( 'jquery' ),
			$version,
			true
		);

		wp_register_script(
			'agenticwp-admin-heartbeat-health',
			$script_base . 'heartbeat-health.js',
			array( 'jquery', 'heartbeat' ),
			$version,
			true
		);

		wp_enqueue_script(
			'agenticwp-admin-settings',
			plugin_dir_url( __DIR__ ) . 'assets/js/admin-settings.js',
			array(
				'jquery',
				'agenticwp-admin-utils',
				'agenticwp-admin-api-keys',
				'agenticwp-admin-default-image',
				'agenticwp-admin-character-counter',
				'agenticwp-admin-sample-prompts',
				'agenticwp-admin-job-monitor',
				'agenticwp-admin-button-enhancements',
				'agenticwp-admin-actions-manager',
				'agenticwp-admin-collapsible-sections',
				'agenticwp-admin-model-selection',
				'agenticwp-admin-dropdown-auto-save',
				'agenticwp-admin-tooltips',
				'agenticwp-admin-heartbeat-health',
			),
			$version,
			true
		);

		wp_enqueue_script(
			'agenticwp-tip-jar',
			$script_base . 'tip-jar.js',
			array(),
			$version,
			true
		);
		wp_localize_script( 'agenticwp-tip-jar', 'agenticwp_tip_jar', array( 'version' => $version ) );

		$localization_data = array_merge(
			array(
				'ajaxUrl'               => admin_url( 'admin-ajax.php' ),
				'deleteConfirmText'     => __( 'Are you sure you want to delete your API key? You will need to enter a new one.', 'agenticwp' ),
				'mediaTitle'            => __( 'Select Default Placeholder Image', 'agenticwp' ),
				'mediaButton'           => __( 'Use this image', 'agenticwp' ),
				'promptsConfirmReplace' => __( 'Replace your current writing style instructions with this template?', 'agenticwp' ),
				'promptsDefaultLabel'   => __( 'Sample example', 'agenticwp' ),
				'promptsMaxReached'     => __( 'You have reached the maximum number of writing style templates.', 'agenticwp' ),
				'promptsMaxCount'       => Settings_Content::get_max_sample_prompts(),
				'nonces'                => array(
					'save_model'                 => wp_create_nonce( 'agenticwp_save_model' ),
					'save_reasoning_effort'      => wp_create_nonce( 'agenticwp_save_reasoning_effort' ),
					'save_max_output_tokens'     => wp_create_nonce( 'agenticwp_save_max_output_tokens' ),
					'save_message_history_limit' => wp_create_nonce( 'agenticwp_save_message_history_limit' ),
					'save_toast_notifications'   => wp_create_nonce( 'agenticwp_save_toast_notifications' ),
					'save_web_search'            => wp_create_nonce( 'agenticwp_save_web_search' ),
					'save_writing_directions'    => wp_create_nonce( 'agenticwp_save_writing_directions' ),
					'save_sample_prompts'        => wp_create_nonce( 'agenticwp_save_sample_prompts' ),
					'save_action'                => wp_create_nonce( 'agenticwp_save_action' ),
					'delete_action'              => wp_create_nonce( 'agenticwp_delete_action' ),
					'save_category'              => wp_create_nonce( 'agenticwp_save_category' ),
					'delete_category'            => wp_create_nonce( 'agenticwp_delete_category' ),
					'clear_unused_categories'    => wp_create_nonce( 'agenticwp_clear_unused_categories' ),
				),
			),
			$this->jobs_settings->get_localization_data()
		);

		wp_localize_script(
			'agenticwp-admin-settings',
			'agenticwpAdmin',
			$localization_data
		);
	}

	/**
	 * Get the default image ID.
	 *
	 * @return int
	 */
	public static function get_default_image_id(): int {
		return Settings_Content::get_default_image_id();
	}

	/**
	 * Get the default image URL.
	 *
	 * @return string
	 */
	public static function get_default_image_url(): string {
		return Settings_Content::get_default_image_url();
	}

	/**
	 * Check if toast notifications should be enabled.
	 *
	 * @return bool
	 */
	public static function should_enable_toast_notifications(): bool {
		return Settings_API::should_enable_toast_notifications();
	}

	/**
	 * Check if web search is enabled.
	 *
	 * @return bool
	 */
	public static function is_web_search_enabled(): bool {
		return Settings_API::is_web_search_enabled();
	}

	/**
	 * Get a setting value with optional default.
	 *
	 * @param string $key The setting key (with or without the agentic_wp_ prefix).
	 * @param mixed  $default_value Default value if setting is not found.
	 * @return mixed The setting value.
	 */
	public static function get_option( string $key, $default_value = null ) {
		// Handle both prefixed and non-prefixed keys for backward compatibility.
		if ( strpos( $key, 'agentic_wp_' ) !== 0 ) {
			$key = "agentic_wp_{$key}";
		}
		return get_option( $key, $default_value );
	}
}
