<?php
/**
 * Settings save logic for REST + React (mirrors classic admin-ui save).
 *
 * @package Newsroom_AI_Assistant
 */

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

if ( ! function_exists( 'newsai_apply_site_profile_defaults' ) ) {
	function newsai_apply_site_profile_defaults( $profile ) {
		if ( $profile === 'blog' ) {
			update_option( 'newsai_timeline_mode', 'manual' );
			update_option( 'newsai_timeline_strategy', 'evergreen' );
			update_option( 'newsai_timeline_limit', 3 );
			update_option( 'newsai_timeline_relevance_threshold', 8 );
			update_option( 'newsai_ui_circular_gauge', 'yes' );
			update_option( 'newsai_ui_onboarding_modal', 'yes' );
			update_option( 'newsai_advanced_nlp', 'yes' );
			update_option( 'nros_schema_type', 'article' );
			update_option( 'nros_schema_output_mode', 'hybrid' );
			update_option( 'newsai_liveblog_schema_enabled', 'no' );
		} else {
			update_option( 'newsai_timeline_mode', 'auto' );
			update_option( 'newsai_timeline_strategy', 'ongoing' );
			update_option( 'newsai_timeline_limit', 5 );
			update_option( 'newsai_timeline_relevance_threshold', 5 );
			update_option( 'newsai_ui_circular_gauge', 'yes' );
			update_option( 'newsai_ui_onboarding_modal', 'yes' );
			update_option( 'newsai_advanced_nlp', 'yes' );
			update_option( 'nros_schema_type', 'newsarticle' );
			update_option( 'nros_schema_output_mode', 'hybrid' );
			update_option( 'newsai_liveblog_schema_enabled', 'yes' );
		}
		update_option( 'newsai_site_profile', $profile );
	}
}

if ( ! function_exists( 'newsai_settings_registry_is_pro' ) ) {
	function newsai_settings_registry_is_pro() {
		return function_exists( 'newsai_is_pro' ) && newsai_is_pro();
	}
}

if ( ! function_exists( 'newsai_settings_registry_field_def' ) ) {
	function newsai_settings_registry_field_def( $key ) {
		foreach ( newsai_settings_registry_sections() as $section ) {
			if ( isset( $section['fields'][ $key ] ) ) {
				return $section['fields'][ $key ];
			}
		}
		return null;
	}
}

if ( ! function_exists( 'newsai_settings_registry_read_option' ) ) {
	function newsai_settings_registry_read_option( $key, array $field ) {
		$type = (string) ( $field['type'] ?? 'text' );

		if ( 'newsai_usage_registry_optin' === $key ) {
			return function_exists( 'newsai_usage_registry_opted_in' ) && newsai_usage_registry_opted_in();
		}
		if ( 'newsai_settings_ui' === $key ) {
			return newsai_settings_ui_mode() === 'react';
		}
		if ( 'newsai_site_desc' === $key && function_exists( 'newsai_get_best_site_description' ) ) {
			return (string) newsai_get_best_site_description();
		}
		if ( in_array( $key, [ 'newsai_prompt_title', 'newsai_prompt_rewrite', 'newsai_prompt_seo' ], true ) ) {
			$raw = (string) get_option( $key, '' );
			if ( trim( $raw ) === '' && function_exists( 'newsai_get_default_prompt' ) ) {
				$kind = str_replace( 'newsai_prompt_', '', $key );
				$lang = function_exists( 'newsai_get_ui_lang' ) ? newsai_get_ui_lang() : 'en';
				return (string) newsai_get_default_prompt( $kind, $lang );
			}
			return $raw;
		}
		if ( 'password' === $type ) {
			return '';
		}

		$raw = get_option( $key, '' );
		if ( 'toggle' === $type ) {
			return ( $raw === 'yes' );
		}
		if ( 'number' === $type || 'range' === $type ) {
			return is_numeric( $raw ) ? (string) (int) $raw : (string) ( $field['default'] ?? '0' );
		}
		if ( 'radio' === $type && is_numeric( $raw ) ) {
			return (string) (int) $raw;
		}
		return is_scalar( $raw ) ? (string) $raw : '';
	}
}

if ( ! function_exists( 'newsai_settings_registry_sanitize_field' ) ) {
	function newsai_settings_registry_sanitize_field( $key, $value, array $field = null ) {
		if ( ! is_array( $field ) ) {
			$field = newsai_settings_registry_field_def( $key );
		}
		if ( ! is_array( $field ) ) {
			return '';
		}
		$type = (string) ( $field['type'] ?? 'text' );

		if ( 'toggle' === $type ) {
			return ( $value === true || $value === 'yes' || $value === '1' || $value === 1 ) ? 'yes' : 'no';
		}
		if ( 'select' === $type || 'radio' === $type ) {
			$choices = (array) ( $field['choices'] ?? [] );
			$val     = is_numeric( array_key_first( $choices ) ) ? (string) (int) $value : sanitize_key( (string) $value );
			if ( is_numeric( array_key_first( $choices ) ) ) {
				$val = (string) (int) $value;
			}
			return array_key_exists( $val, $choices ) ? $val : (string) array_key_first( $choices );
		}
		if ( 'number' === $type || 'range' === $type ) {
			$min = isset( $field['min'] ) ? (int) $field['min'] : PHP_INT_MIN;
			$max = isset( $field['max'] ) ? (int) $field['max'] : PHP_INT_MAX;
			return (string) max( $min, min( $max, (int) $value ) );
		}
		if ( 'textarea' === $type ) {
			return sanitize_textarea_field( (string) $value );
		}
		if ( 'url' === $type ) {
			return esc_url_raw( (string) $value );
		}
		if ( 'email' === $type ) {
			return sanitize_email( (string) $value );
		}
		if ( 'password' === $type ) {
			return sanitize_text_field( (string) $value );
		}
		return sanitize_text_field( (string) $value );
	}
}

if ( ! function_exists( 'newsai_settings_registry_save_field' ) ) {
	function newsai_settings_registry_save_field( $key, $value, array $field ) {
		$type = (string) ( $field['type'] ?? 'text' );

		if ( ! empty( $field['proOnly'] ) && ! newsai_settings_registry_is_pro() ) {
			return;
		}
		if ( ! empty( $field['freeOnly'] ) && newsai_settings_registry_is_pro() ) {
			return;
		}

		if ( 'password' === $type ) {
			$trimmed = trim( (string) $value );
			if ( $trimmed === '' ) {
				return;
			}
			$secret = (string) ( $field['secret'] ?? '' );
			if ( 'psi_api_key' === $secret ) {
				update_option( 'newsai_psi_api_key', sanitize_text_field( $trimmed ), false );
				return;
			}
			if ( $secret !== '' && function_exists( 'newsai_secret_is_locked' ) && newsai_secret_is_locked( $secret ) ) {
				return;
			}
			if ( $secret !== '' && function_exists( 'newsai_secret_update_option' ) ) {
				newsai_secret_update_option( $secret, sanitize_text_field( $trimmed ) );
				return;
			}
			update_option( $key, sanitize_text_field( $trimmed ), false );
			return;
		}

		if ( 'newsai_usage_registry_optin' === $key ) {
			if ( newsai_settings_registry_is_pro() ) {
				return;
			}
			$now = ( $value === true || $value === 'yes' || $value === '1' );
			if ( function_exists( 'newsai_usage_registry_on_optin_changed' ) ) {
				$was = function_exists( 'newsai_usage_registry_opted_in' ) && newsai_usage_registry_opted_in();
				if ( $was !== $now ) {
					newsai_usage_registry_on_optin_changed( $now );
				} elseif ( $now ) {
					newsai_usage_registry_schedule();
				}
			} else {
				update_option( 'newsai_usage_registry_optin', $now ? 'yes' : 'no', false );
			}
			return;
		}

		if ( 'newsai_settings_ui' === $key ) {
			if ( function_exists( 'newsai_settings_set_ui_mode' ) ) {
				$enable = ( $value === true || $value === 'yes' || $value === '1' || $value === 'react' );
				newsai_settings_set_ui_mode( $enable ? 'react' : 'classic' );
			}
			return;
		}

		$sanitized = newsai_settings_registry_sanitize_field( $key, $value, $field );

		$empty_deletes = [
			'newsai_timeline_label_today',
			'newsai_timeline_label_yesterday',
			'newsai_timeline_label_days_ago',
			'newsai_timeline_label_start',
			'newsai_timeline_label_full',
			'newsai_timeline_heading',
		];
		if ( in_array( $key, $empty_deletes, true ) && trim( (string) $sanitized ) === '' ) {
			delete_option( $key );
			return;
		}

		$autoload = in_array( $key, [ 'newsai_ai_provider', 'newsai_ai_openai_model', 'newsai_ai_gemini_model', 'newsai_ai_groq_model', 'newsai_ai_daily_limit_per_user' ], true ) ? false : null;
		if ( null === $autoload ) {
			update_option( $key, $sanitized );
		} else {
			update_option( $key, $sanitized, false );
		}
	}
}

if ( ! function_exists( 'newsai_settings_registry_after_save_section' ) ) {
	function newsai_settings_registry_after_save_section( $section_id, array $data, array $schema_before = [] ) {
		if ( in_array( $section_id, [ 'schema', 'schema_org', 'speakable' ], true ) && function_exists( 'nros_schema_maybe_bump_global_version' ) && ! empty( $schema_before ) ) {
			nros_schema_maybe_bump_global_version( $schema_before );
		}

		if ( 'schema' === $section_id ) {
			$type_before = isset( $schema_before['nros_schema_type'] ) ? (string) $schema_before['nros_schema_type'] : 'newsarticle';
			$type_after  = (string) get_option( 'nros_schema_type', 'newsarticle' );
			if ( $type_before === 'none' && $type_after !== 'none' && function_exists( 'nros_schema_on_schema_enabled' ) ) {
				nros_schema_on_schema_enabled();
			}
			if ( $type_after === 'none' && function_exists( 'nros_schema_schedule_legacy_warm_cron' ) ) {
				nros_schema_schedule_legacy_warm_cron();
			}
		}

		if ( 'performance' === $section_id && isset( $data['nros_schema_megasite_mode'] ) && function_exists( 'nros_schema_schedule_legacy_warm_cron' ) ) {
			nros_schema_schedule_legacy_warm_cron();
		}

		if ( 'site' === $section_id && isset( $data['newsai_lang'] ) ) {
			$old = (string) get_option( 'newsai_lang', '' );
			$new = (string) $data['newsai_lang'];
			if ( $old !== $new && function_exists( 'newsai_get_default_prompt' ) ) {
				update_option( 'newsai_prompt_title', newsai_get_default_prompt( 'title', $new ) );
				update_option( 'newsai_prompt_rewrite', newsai_get_default_prompt( 'rewrite', $new ) );
				update_option( 'newsai_prompt_seo', newsai_get_default_prompt( 'seo', $new ) );
			}
		}

		if ( 'ux' === $section_id ) {
			if ( isset( $data['newsai_tag_pool_size'] ) && function_exists( 'newsai_tag_pool_size_get' ) ) {
				$prev = newsai_tag_pool_size_get();
				$new  = (int) $data['newsai_tag_pool_size'];
				if ( $new !== $prev && function_exists( 'newsai_tag_pool_size_clear_caches' ) ) {
					newsai_tag_pool_size_clear_caches();
				}
			}
			if ( isset( $data['newsai_tag_pool_editor_size'] ) && function_exists( 'newsai_tag_pool_editor_size_get' ) ) {
				$prev = newsai_tag_pool_editor_size_get();
				$new  = (int) $data['newsai_tag_pool_editor_size'];
				if ( $new !== $prev && function_exists( 'newsai_tag_pool_size_clear_caches' ) ) {
					newsai_tag_pool_size_clear_caches();
				}
			}
		}

		if ( 'indexing' === $section_id && newsai_settings_registry_is_pro() ) {
			if ( isset( $data['newsai_indexnow_enabled'] ) && ( $data['newsai_indexnow_enabled'] === true || $data['newsai_indexnow_enabled'] === 'yes' ) && function_exists( 'newsai_indexnow_flush_rewrite_rules' ) ) {
				newsai_indexnow_flush_rewrite_rules();
			}
			if ( function_exists( 'newsai_gsc_schedule_cron' ) ) {
				newsai_gsc_schedule_cron();
			}
		}

		if ( 'insights' === $section_id && function_exists( 'newsai_schedule_seasonal_radar' ) ) {
			newsai_schedule_seasonal_radar();
			if ( get_option( 'newsai_seasonal_radar_enabled', 'yes' ) === 'yes' && function_exists( 'newsai_seasonal_radar_compute' ) ) {
				newsai_seasonal_radar_compute();
			}
		}

		if ( 'timeline' === $section_id && isset( $data['newsai_timeline_mode'] ) ) {
			$mode = (string) $data['newsai_timeline_mode'];
			if ( $mode === 'auto' && ! newsai_settings_registry_is_pro() ) {
				update_option( 'newsai_timeline_mode', 'manual' );
			}
		}

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

if ( ! function_exists( 'newsai_settings_registry_run_action' ) ) {
	/**
	 * @param string $action Action id.
	 * @param array  $params Params.
	 * @return array|WP_Error
	 */
	function newsai_settings_registry_run_action( $action, array $params = [] ) {
		switch ( $action ) {
			case 'apply_site_profile':
				$profile = isset( $params['profile'] ) ? sanitize_key( (string) $params['profile'] ) : 'newsroom';
				if ( ! in_array( $profile, [ 'newsroom', 'blog' ], true ) ) {
					return new WP_Error( 'invalid_profile', __( 'Invalid site profile.', 'newsroom-ai-assistant' ), [ 'status' => 400 ] );
				}
				if ( function_exists( 'newsai_apply_site_profile_defaults' ) ) {
					newsai_apply_site_profile_defaults( $profile );
				}
				return [ 'ok' => true, 'message' => __( 'Site profile applied.', 'newsroom-ai-assistant' ) ];

			case 'apply_publisher_profile':
				$profile = isset( $params['profile'] ) ? sanitize_key( (string) $params['profile'] ) : 'standard';
				if ( ! function_exists( 'newsai_apply_publisher_profile' ) ) {
					return new WP_Error( 'missing_fn', __( 'Publisher profiles unavailable.', 'newsroom-ai-assistant' ), [ 'status' => 500 ] );
				}
				newsai_apply_publisher_profile( $profile );
				return [ 'ok' => true, 'message' => __( 'Performance profile applied.', 'newsroom-ai-assistant' ) ];

			case 'schema_warm_batch':
				$warmed = function_exists( 'nros_schema_warm_posts_batch' ) ? nros_schema_warm_posts_batch( 25 ) : 0;
				return [
					'ok'      => true,
					'warmed'  => (int) $warmed,
					'message' => sprintf(
						/* translators: %d: post count */
						__( 'Warmed %d post(s).', 'newsroom-ai-assistant' ),
						(int) $warmed
					),
				];

			default:
				return new WP_Error( 'invalid_action', __( 'Unknown action.', 'newsroom-ai-assistant' ), [ 'status' => 400 ] );
		}
	}
}
