<?php
/**
 * AI Settings
 *
 * This file contains all AI settings functionality.
 *
 * @package Simple_Ai_Auto_Post
 * @since 1.0.0
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

// Make sure this file is being included by a parent file.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Enqueue the script for the AI settings
 */
function saiap_enqueue_ai_settings_script() {
	wp_enqueue_script( 'saiap-admin-js', plugin_dir_url( dirname( __FILE__ ) ) . 'assets/js/admin.js', array( 'jquery' ), '1.0.0', true );
}

/**
 * AJAX callback for saving API keys
 */
function saiap_save_api_keys_callback() {
	// Check if the AJAX request is properly formed
	if ( empty( $_POST ) ) {
		wp_send_json_error( 'No data received. Please try again.' );
		return;
	}

	// Check nonce for security
	if ( ! isset( $_POST['saiap_api_keys_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['saiap_api_keys_nonce'] ) ), 'saiap_save_api_keys_action' ) ) {
		wp_send_json_error( 'Security check failed' );
		return;
	}

	// Get the values from the form
	$openai_api_key    = isset( $_POST['saiap_openai_api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['saiap_openai_api_key'] ) ) : '';
	$anthropic_api_key = isset( $_POST['saiap_anthropic_api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['saiap_anthropic_api_key'] ) ) : '';
	$gemini_api_key    = isset( $_POST['saiap_gemini_api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['saiap_gemini_api_key'] ) ) : '';
	$default_provider  = isset( $_POST['saiap_default_provider'] ) ? sanitize_text_field( wp_unslash( $_POST['saiap_default_provider'] ) ) : 'openai';

	// Check if this is the first time saving any API key (for tracking consent prompt).
	$had_keys_before = ! empty( get_option( 'saiap_openai_api_key', '' ) ) ||
	                   ! empty( get_option( 'saiap_anthropic_api_key', '' ) ) ||
	                   ! empty( get_option( 'saiap_gemini_api_key', '' ) );

	// Save the API keys
	$result_openai = update_option( 'saiap_openai_api_key', $openai_api_key );

	$result_anthropic = update_option( 'saiap_anthropic_api_key', $anthropic_api_key );

	$result_gemini = update_option( 'saiap_gemini_api_key', $gemini_api_key );

	$result_provider = update_option( 'saiap_default_provider', $default_provider );

	// Check if this is the first time saving keys and user hasn't made a tracking consent choice.
	$has_keys_now           = ! empty( $openai_api_key ) || ! empty( $anthropic_api_key ) || ! empty( $gemini_api_key );
	$first_key_saved        = ! $had_keys_before && $has_keys_now;
	$needs_tracking_consent = $first_key_saved && get_option( 'saiap_tracking_consent', null ) === null;

	// Save model based on provider
	if ( $default_provider === 'anthropic' ) {
		$model = isset( $_POST['saiap_anthropic_model'] ) ? sanitize_text_field( wp_unslash( $_POST['saiap_anthropic_model'] ) ) : 'claude-opus-4-5';
		update_option( 'saiap_anthropic_model', $model );
	} elseif ( $default_provider === 'gemini' ) {
		$model = isset( $_POST['saiap_gemini_model'] ) ? sanitize_text_field( wp_unslash( $_POST['saiap_gemini_model'] ) ) : 'gemini-3.1-pro-preview';
		update_option( 'saiap_gemini_model', $model );
	} else {
		$model = isset( $_POST['saiap_openai_model'] ) ? sanitize_text_field( wp_unslash( $_POST['saiap_openai_model'] ) ) : 'gpt-5.4';
		update_option( 'saiap_openai_model', $model );
	}

	// Verify values were saved correctly
	$saved_openai_key    = get_option( 'saiap_openai_api_key', '' );
	$saved_anthropic_key = get_option( 'saiap_anthropic_api_key', '' );
	$saved_gemini_key    = get_option( 'saiap_gemini_api_key', '' );
	$saved_provider      = get_option( 'saiap_default_provider', '' );

	// Return success
	$response_data = array(
		'message'               => __( 'API settings saved successfully!', 'clearpost-simple-ai-auto-post' ),
		'provider'              => $default_provider,
		'saved_keys'            => array(
			'openai'    => ! empty( $openai_api_key ),
			'anthropic' => ! empty( $anthropic_api_key ),
			'gemini'    => ! empty( $gemini_api_key ),
		),
		'show_tracking_consent' => $needs_tracking_consent,
	);
	wp_send_json_success( $response_data );
}

add_action( 'wp_ajax_saiap_save_api_keys', 'saiap_save_api_keys_callback' );

/**
 * AJAX callback for saving notification settings
 */
function saiap_save_notifications_callback() {
    // Check nonce for security
    if ( ! isset( $_POST['saiap_notifications_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['saiap_notifications_nonce'] ) ), 'saiap_save_notifications_action' ) ) {
        wp_send_json_error( __( 'Security check failed', 'clearpost-simple-ai-auto-post' ) );
    }

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( __( 'Unauthorized', 'clearpost-simple-ai-auto-post' ) );
    }

    $enabled    = isset( $_POST['saiap_notify_on_schedule'] ) ? sanitize_text_field( wp_unslash( $_POST['saiap_notify_on_schedule'] ) ) : 'no';
    $recipients = isset( $_POST['saiap_notify_recipients'] ) ? sanitize_text_field( wp_unslash( $_POST['saiap_notify_recipients'] ) ) : '';

    update_option( 'saiap_notify_on_schedule', $enabled === 'yes' ? 'yes' : 'no' );
    update_option( 'saiap_notify_recipients', $recipients );

    wp_send_json_success( array( 'message' => __( 'Notification settings saved!', 'clearpost-simple-ai-auto-post' ) ) );
}

add_action( 'wp_ajax_saiap_save_notifications', 'saiap_save_notifications_callback' );

/**
 * AJAX callback for saving the AI-can-create-terms taxonomy setting.
 */
function saiap_save_taxonomy_settings_callback() {
	if ( ! isset( $_POST['saiap_taxonomy_settings_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['saiap_taxonomy_settings_nonce'] ) ), 'saiap_save_taxonomy_settings_action' ) ) {
		wp_send_json_error( __( 'Security check failed', 'clearpost-simple-ai-auto-post' ) );
	}

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( __( 'Unauthorized', 'clearpost-simple-ai-auto-post' ) );
	}

	$allow_create = isset( $_POST['saiap_allow_ai_create_terms'] ) && '1' === sanitize_text_field( wp_unslash( $_POST['saiap_allow_ai_create_terms'] ) );
	update_option( 'saiap_allow_ai_create_terms', $allow_create );

	wp_send_json_success( array( 'message' => __( 'Taxonomy settings saved!', 'clearpost-simple-ai-auto-post' ) ) );
}

add_action( 'wp_ajax_saiap_save_taxonomy_settings', 'saiap_save_taxonomy_settings_callback' );

/**
 * Render the Settings tab
 */
function saiap_render_ai_settings_tab( $models = array() ) {
	$license_key = get_option( 'saiap_license_key', '' );
	$scenario    = saiap_get_user_scenario();

	// Note: Tracking consent prompt is now shown immediately via JavaScript after
	// first API key save, rather than on the next page load.

	// Render trial CTA banner for non-trial users.
	if ( in_array( $scenario, array( 'no_trial_no_keys', 'no_trial_has_keys' ), true ) ) {
		?>
		<div class="saiap-settings-trial-banner">
			<div class="saiap-settings-trial-banner__content">
				<span class="dashicons dashicons-superhero-alt saiap-settings-trial-banner__icon"></span>
				<div class="saiap-settings-trial-banner__text">
					<strong><?php esc_html_e( 'Skip the API key setup', 'clearpost-simple-ai-auto-post' ); ?></strong>
					<span><?php esc_html_e( 'Start your free trial to get SEO-driven content with zero configuration.', 'clearpost-simple-ai-auto-post' ); ?></span>
				</div>
				<button type="button" class="button button-primary saiap-start-trial-btn">
					<?php esc_html_e( 'Start Free Trial', 'clearpost-simple-ai-auto-post' ); ?>
				</button>
			</div>
		</div>
		<?php
	}
	?>
	<div class="tab-content ai-settings-tab-content">
		<div class="container">
			<?php if ( empty( $license_key ) ) : ?>
			<div class="col col-12">
				<div class="card">
					<h2 class="spacing-16-row"><?php esc_html_e( 'API Settings', 'clearpost-simple-ai-auto-post' ); ?></h2>
					<p class="spacing-16-row"><?php esc_html_e( 'Enter your API keys for any LLM providers you wish to use.', 'clearpost-simple-ai-auto-post' ); ?></p>
					<p class="spacing-16-row"><?php esc_html_e( 'Note: You don\'t have to do this if you\'re using ClearPost Premium (no API keys needed).', 'clearpost-simple-ai-auto-post' ); ?></p>
					<div class="spacing-8-row">
						<a href="https://clearpostplugin.com/" target="_blank" class="secondary-button"><?php esc_html_e( 'Grow organic traffic on autopilot (no API keys needed)', 'clearpost-simple-ai-auto-post' ); ?></a>
					</div>
					
					<form id="saiap-api-settings-form" method="post">
						<?php wp_nonce_field( 'saiap_save_api_keys_action', 'saiap_api_keys_nonce' ); ?>
						
						<div class="row">
							<div class="col col-6 openai-api-settings">
								<div class="spacing-16-row">
									<label for="saiap_openai_api_key" class="body-text"><?php esc_html_e( 'OpenAI API Key:', 'clearpost-simple-ai-auto-post' ); ?></label>
									<input type="password" id="saiap_openai_api_key" name="saiap_openai_api_key" class="large-text" value="<?php echo esc_attr( get_option( 'saiap_openai_api_key' ) ); ?>" />
									<p class="small-text"><?php esc_html_e( 'Your OpenAI API key is required to use this plugin. Get one from openai.com', 'clearpost-simple-ai-auto-post' ); ?></p>
								</div>
							</div>
							
							<div class="col col-6 anthropic-api-settings">
								<div class="spacing-16-row">
									<label for="saiap_anthropic_api_key" class="body-text"><?php esc_html_e( 'Anthropic API Key:', 'clearpost-simple-ai-auto-post' ); ?></label>
									<input type="password" id="saiap_anthropic_api_key" name="saiap_anthropic_api_key" class="large-text" value="<?php echo esc_attr( get_option( 'saiap_anthropic_api_key' ) ); ?>" />
									<p class="small-text"><?php esc_html_e( 'Your Anthropic API key is required to use Claude. Get one from console.anthropic.com', 'clearpost-simple-ai-auto-post' ); ?></p>
								</div>
							</div>
							
							<div class="col col-6 gemini-api-settings">
								<div class="spacing-16-row">
									<label for="saiap_gemini_api_key" class="body-text"><?php esc_html_e( 'Gemini API Key:', 'clearpost-simple-ai-auto-post' ); ?></label>
									<input type="password" id="saiap_gemini_api_key" name="saiap_gemini_api_key" class="large-text" value="<?php echo esc_attr( get_option( 'saiap_gemini_api_key' ) ); ?>" />
									<p class="small-text"><?php esc_html_e( 'Your Google API key is required to use Gemini. Get one from ai.google.dev', 'clearpost-simple-ai-auto-post' ); ?></p>
								</div>
							</div>
						</div>
						
						<div class="spacing-24 text-align-center">
							<button type="button" id="saiap-save-api-keys" class="primary-button" onclick="saveApiKeys()">
								<?php esc_html_e( 'Save API Settings', 'clearpost-simple-ai-auto-post' ); ?>
							</button>
						</div>
						
						<div id="api-settings-message" class="spacing-16" style="display: none;"></div>
					</form>
				</div>
			</div>
			<?php endif; ?>

			<div class="col col-12">
				<div class="card">
					<h2 class="spacing-16-row"><?php esc_html_e( 'Notifications', 'clearpost-simple-ai-auto-post' ); ?></h2>
					<p class="spacing-16-row"><?php esc_html_e( 'Get an email when the scheduler creates a new draft.', 'clearpost-simple-ai-auto-post' ); ?></p>

					<form id="saiap-notifications-form" method="post">
						<?php wp_nonce_field( 'saiap_save_notifications_action', 'saiap_notifications_nonce' ); ?>

						<div class="spacing-16-row">
							<label for="saiap_notify_on_schedule" class="body-text"><?php esc_html_e( 'Enable email notifications', 'clearpost-simple-ai-auto-post' ); ?></label>
							<select id="saiap_notify_on_schedule" name="saiap_notify_on_schedule" class="regular-text">
								<option value="no" <?php selected( get_option( 'saiap_notify_on_schedule', 'yes' ), 'no' ); ?>><?php esc_html_e( 'No', 'clearpost-simple-ai-auto-post' ); ?></option>
								<option value="yes" <?php selected( get_option( 'saiap_notify_on_schedule', 'yes' ), 'yes' ); ?>><?php esc_html_e( 'Yes', 'clearpost-simple-ai-auto-post' ); ?></option>
							</select>
						</div>

						<div class="spacing-16-row">
							<label for="saiap_notify_recipients" class="body-text"><?php esc_html_e( 'Recipients (comma-separated emails)', 'clearpost-simple-ai-auto-post' ); ?></label>
							<input type="text" id="saiap_notify_recipients" name="saiap_notify_recipients" class="large-text" value="<?php echo esc_attr( get_option( 'saiap_notify_recipients', get_option( 'admin_email', '' ) ) ); ?>" />
							<p class="small-text"><?php esc_html_e( 'Defaults to the site admin email.', 'clearpost-simple-ai-auto-post' ); ?></p>
						</div>

						<div class="spacing-24 text-align-center">
							<button type="button" id="saiap-save-notifications" class="primary-button" onclick="saveNotificationSettings()">
								<?php esc_html_e( 'Save Notification Settings', 'clearpost-simple-ai-auto-post' ); ?>
							</button>
						</div>

						<div id="notifications-settings-message" class="spacing-16" style="display: none;"></div>
					</form>
				</div>
			</div>

			<div class="col col-12">
				<div class="card">
					<h2 class="spacing-16-row"><?php esc_html_e( 'Categories &amp; Tags', 'clearpost-simple-ai-auto-post' ); ?></h2>
					<p class="spacing-16-row"><?php esc_html_e( 'Control whether the AI can create new categories and tags, or only choose from the ones you\'ve already set up.', 'clearpost-simple-ai-auto-post' ); ?></p>

					<form id="saiap-taxonomy-settings-form" method="post">
						<?php wp_nonce_field( 'saiap_save_taxonomy_settings_action', 'saiap_taxonomy_settings_nonce' ); ?>

						<div class="spacing-16-row">
							<label for="saiap_allow_ai_create_terms" class="body-text">
								<input type="checkbox" id="saiap_allow_ai_create_terms" name="saiap_allow_ai_create_terms" value="1" <?php checked( (bool) get_option( 'saiap_allow_ai_create_terms', false ), true ); ?> />
								<?php esc_html_e( 'Allow AI to create new categories and tags', 'clearpost-simple-ai-auto-post' ); ?>
							</label>
							<p class="small-text">
								<?php esc_html_e( 'When off (recommended), posts are tagged only with the categories and tags that already exist on your site. This prevents thin archive pages that hurt SEO. To use this mode, add the categories and tags you want under Posts → Categories and Posts → Tags first, then the AI will choose from your taxonomy.', 'clearpost-simple-ai-auto-post' ); ?>
							</p>
						</div>

						<div class="spacing-24 text-align-center">
							<button type="button" id="saiap-save-taxonomy-settings" class="primary-button" onclick="saveTaxonomySettings()">
								<?php esc_html_e( 'Save Settings', 'clearpost-simple-ai-auto-post' ); ?>
							</button>
						</div>

						<div id="taxonomy-settings-message" class="spacing-16" style="display: none;"></div>
					</form>
				</div>
			</div>

			<?php saiap_render_gsc_settings(); ?>
		</div>
	</div>
	<?php
	saiap_enqueue_ai_settings_script();
	saiap_render_privacy_settings();
}

/**
 * Render the Google Search Console integration settings card.
 * Only shown for premium/trial users.
 */
function saiap_render_gsc_settings() {
	$license_key = get_option( 'saiap_license_key', '' );
	if ( empty( $license_key ) ) {
		return;
	}

	$domain          = saiap_get_server_host();
	$premium_api_url = str_replace( 'host.docker.internal', 'localhost', SAIAP_PREMIUM_API_URL );
	// Redirect to dashboard after OAuth so the auto-review can trigger.
	$return_url      = admin_url( 'admin.php?page=saiap&tab=dashboard' );
	$gsc_nonce       = wp_create_nonce( 'saiap_gsc_nonce' );
	// OAuth start is a top-level navigation, so it stays pointed at the backend directly.
	$connect_url     = $premium_api_url . '/api/gsc/oauth/start?' . http_build_query(
		array(
			'domain'     => $domain,
			'return_url' => $return_url,
		)
	);
	// Status and disconnect are XHR calls — proxied through admin-ajax to avoid CORS.
	$status_url      = admin_url( 'admin-ajax.php?action=saiap_gsc_status&_wpnonce=' . $gsc_nonce );
	$disconnect_url  = admin_url( 'admin-ajax.php?action=saiap_gsc_disconnect&_wpnonce=' . $gsc_nonce );

	// Check for return from OAuth flow.
	$gsc_connected = isset( $_GET['gsc_connected'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$gsc_error     = isset( $_GET['gsc_error'] ) ? sanitize_text_field( wp_unslash( $_GET['gsc_error'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	?>
	<div class="col col-12">
		<div class="card" id="saiap-gsc-card">
			<h2 class="spacing-16-row"><?php esc_html_e( 'Google Search Console', 'clearpost-simple-ai-auto-post' ); ?></h2>
			<p class="spacing-16-row"><?php esc_html_e( 'Connect Google Search Console to let the AI see your real search performance — rankings, clicks, and top queries. This helps it write content that targets what\'s actually working.', 'clearpost-simple-ai-auto-post' ); ?></p>

			<?php if ( $gsc_connected ) : ?>
				<div class="notice notice-success inline spacing-16-row">
					<p><?php esc_html_e( 'Google Search Console connected successfully!', 'clearpost-simple-ai-auto-post' ); ?></p>
				</div>
			<?php elseif ( $gsc_error ) : ?>
				<div class="notice notice-error inline spacing-16-row">
					<p>
					<?php
					switch ( $gsc_error ) {
						case 'denied':
							esc_html_e( 'Google Search Console access was denied. Please try again.', 'clearpost-simple-ai-auto-post' );
							break;
						case 'no_properties':
							esc_html_e( 'No Search Console properties found. Make sure your site is added to Google Search Console first.', 'clearpost-simple-ai-auto-post' );
							break;
						case 'no_match':
							esc_html_e( 'Could not match a Search Console property to this site\'s domain. Check your GSC properties.', 'clearpost-simple-ai-auto-post' );
							break;
						default:
							esc_html_e( 'Failed to connect Google Search Console. Please try again.', 'clearpost-simple-ai-auto-post' );
					}
					?>
					</p>
				</div>
			<?php endif; ?>

			<div id="saiap-gsc-status" class="spacing-16-row">
				<span class="spinner is-active" style="float: none; margin: 0;"></span>
				<span><?php esc_html_e( 'Checking connection...', 'clearpost-simple-ai-auto-post' ); ?></span>
			</div>

			<div id="saiap-gsc-connected" class="spacing-16-row" style="display: none;">
				<p>
					<span class="dashicons dashicons-yes-alt" style="color: #00a32a;"></span>
					<?php esc_html_e( 'Connected to:', 'clearpost-simple-ai-auto-post' ); ?>
					<strong id="saiap-gsc-property"></strong>
				</p>
				<button type="button" class="button" id="saiap-gsc-disconnect">
					<?php esc_html_e( 'Disconnect', 'clearpost-simple-ai-auto-post' ); ?>
				</button>
			</div>

			<div id="saiap-gsc-disconnected" class="spacing-24 text-align-center" style="display: none;">
				<a href="<?php echo esc_url( $connect_url ); ?>" class="primary-button" style="text-decoration: none;">
					<?php esc_html_e( 'Connect Google Search Console', 'clearpost-simple-ai-auto-post' ); ?>
				</a>
				<p class="description" style="margin-top: 12px;">
					<?php esc_html_e( 'After connecting, you\'ll be taken to your dashboard where ClearPost will analyze your search data.', 'clearpost-simple-ai-auto-post' ); ?>
				</p>
			</div>
		</div>
	</div>

	<script>
	(function() {
		var statusUrl = <?php echo wp_json_encode( $status_url ); ?>;
		var disconnectUrl = <?php echo wp_json_encode( $disconnect_url ); ?>;
		var statusEl = document.getElementById('saiap-gsc-status');
		var connectedEl = document.getElementById('saiap-gsc-connected');
		var disconnectedEl = document.getElementById('saiap-gsc-disconnected');
		var propertyEl = document.getElementById('saiap-gsc-property');

		fetch(statusUrl)
			.then(function(r) { return r.json(); })
			.then(function(data) {
				statusEl.style.display = 'none';
				if (data.connected) {
					propertyEl.textContent = data.property_url;
					connectedEl.style.display = '';
				} else {
					disconnectedEl.style.display = '';
				}
			})
			.catch(function() {
				statusEl.style.display = 'none';
				disconnectedEl.style.display = '';
			});

		document.getElementById('saiap-gsc-disconnect').addEventListener('click', function() {
			if (!confirm(<?php echo wp_json_encode( __( 'Disconnect Google Search Console?', 'clearpost-simple-ai-auto-post' ) ); ?>)) {
				return;
			}
			fetch(disconnectUrl)
				.then(function(r) { return r.json(); })
				.then(function() {
					connectedEl.style.display = 'none';
					disconnectedEl.style.display = '';
				});
		});
	})();
	</script>
	<?php
}