<?php
/**
 * Settings registry for REST + React Settings UI (2.7).
 *
 * @package Newsroom_AI_Assistant
 */

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

require_once __DIR__ . '/settings-registry-sections.php';
require_once __DIR__ . '/settings-registry-save.php';
require_once __DIR__ . '/settings-registry-meta.php';

if ( ! function_exists( 'newsai_settings_react_build_exists' ) ) {
	function newsai_settings_react_build_exists() {
		return is_readable( NEWSAI_PATH . 'assets/admin-app/build/index.js' );
	}
}

if ( ! function_exists( 'newsai_settings_ui_locked_by_constant' ) ) {
	function newsai_settings_ui_locked_by_constant() {
		return defined( 'NEWSAI_REACT_SETTINGS' );
	}
}

if ( ! function_exists( 'newsai_settings_ui_mode' ) ) {
	/**
	 * @return string 'classic'|'react'
	 */
	function newsai_settings_ui_mode() {
		if ( newsai_settings_ui_locked_by_constant() ) {
			return (bool) NEWSAI_REACT_SETTINGS ? 'react' : 'classic';
		}
		$mode = (string) get_option( 'newsai_settings_ui', 'classic' );
		return ( $mode === 'react' ) ? 'react' : 'classic';
	}
}

if ( ! function_exists( 'newsai_settings_set_ui_mode' ) ) {
	/**
	 * @param string $mode 'classic'|'react'
	 * @return bool Whether the mode was saved.
	 */
	function newsai_settings_set_ui_mode( $mode ) {
		if ( newsai_settings_ui_locked_by_constant() ) {
			return false;
		}
		$mode = ( $mode === 'react' ) ? 'react' : 'classic';
		if ( $mode === 'react' ) {
			return false;
		}
		update_option( 'newsai_settings_ui', 'classic', false );
		return true;
	}
}

if ( ! function_exists( 'newsai_settings_react_enabled' ) ) {
	function newsai_settings_react_enabled() {
		if ( newsai_settings_ui_mode() !== 'react' ) {
			return false;
		}
		return (bool) apply_filters( 'newsai_settings_react_enabled', false );
	}
}

if ( ! function_exists( 'newsai_settings_registry_enrich_sections' ) ) {
	function newsai_settings_registry_enrich_sections( array $sections ) {
		$is_pro = newsai_settings_registry_is_pro();
		foreach ( $sections as $sid => &$section ) {
			if ( ! is_array( $section ) ) {
				continue;
			}
			foreach ( (array) ( $section['fields'] ?? [] ) as $key => &$field ) {
				if ( ! is_array( $field ) ) {
					continue;
				}
				if ( 'password' === ( $field['type'] ?? '' ) ) {
					$secret = (string) ( $field['secret'] ?? '' );
					if ( 'psi_api_key' === $secret ) {
						$field['hasValue'] = function_exists( 'newsai_crux_get_api_key' ) && newsai_crux_get_api_key() !== '';
					} elseif ( $secret !== '' && function_exists( 'newsai_secret_has_stored' ) ) {
						$field['hasValue'] = newsai_secret_has_stored( $secret );
						$field['locked']   = function_exists( 'newsai_secret_is_locked' ) && newsai_secret_is_locked( $secret );
					}
				}
				if ( ! empty( $field['proOnly'] ) && ! $is_pro ) {
					$field['disabled'] = true;
					if ( empty( $field['help'] ) ) {
						$field['help'] = __( 'Requires Newsroom Pro. Upgrade to change this setting.', 'newsroom-ai-assistant' );
					}
				}
				if ( ! empty( $field['freeOnly'] ) && $is_pro ) {
					$field['hidden'] = true;
				}
			}
			unset( $field );
			if ( isset( $section['fields']['newsai_settings_ui'] ) ) {
				$ui_field = &$section['fields']['newsai_settings_ui'];
				if ( newsai_settings_ui_locked_by_constant() ) {
					$ui_field['locked']  = true;
					$ui_field['help']    = __( 'Controlled by NEWSAI_REACT_SETTINGS in wp-config.php. Remove that line to manage here.', 'newsroom-ai-assistant' );
					$ui_field['disabled'] = true;
				} else {
					$ui_field['disabled'] = true;
					$ui_field['help']     = __( 'Coming soon — the modern React admin is being redesigned.', 'newsroom-ai-assistant' );
				}
				unset( $ui_field );
			}
		}
		unset( $section );
		return $sections;
	}
}

if ( ! function_exists( 'newsai_settings_registry_read_values' ) ) {
	function newsai_settings_registry_read_values( $section_ids = null ) {
		$sections = newsai_settings_registry_sections();
		if ( is_array( $section_ids ) ) {
			$sections = array_intersect_key( $sections, array_flip( $section_ids ) );
		}
		$values = [];
		foreach ( $sections as $section_id => $section ) {
			if ( ( $section['type'] ?? '' ) === 'profiles' ) {
				continue;
			}
			$values[ $section_id ] = [];
			foreach ( (array) ( $section['fields'] ?? [] ) as $key => $field ) {
				if ( ! empty( $field['hidden'] ) ) {
					continue;
				}
				$values[ $section_id ][ $key ] = newsai_settings_registry_read_option( $key, $field );
			}
		}
		return $values;
	}
}

if ( ! function_exists( 'newsai_settings_registry_save_section' ) ) {
	function newsai_settings_registry_save_section( $section_id, array $data ) {
		$sections = newsai_settings_registry_sections();
		if ( ! isset( $sections[ $section_id ] ) ) {
			return new WP_Error( 'invalid_section', __( 'Unknown settings section.', 'newsroom-ai-assistant' ), [ 'status' => 400 ] );
		}
		if ( ( $sections[ $section_id ]['type'] ?? '' ) === 'profiles' ) {
			return new WP_Error( 'invalid_section', __( 'Use profile actions for presets.', 'newsroom-ai-assistant' ), [ 'status' => 400 ] );
		}

		$allowed = (array) ( $sections[ $section_id ]['fields'] ?? [] );
		$schema_before = in_array( $section_id, [ 'schema', 'schema_org', 'speakable' ], true ) && function_exists( 'nros_schema_snapshot_versioned_options' )
			? nros_schema_snapshot_versioned_options()
			: [];

		foreach ( $data as $key => $value ) {
			$key = (string) $key;
			if ( ! isset( $allowed[ $key ] ) || ! empty( $allowed[ $key ]['hidden'] ) ) {
				continue;
			}
			newsai_settings_registry_save_field( $key, $value, $allowed[ $key ] );
		}

		if ( 'indexing' === $section_id ) {
			if ( isset( $data['newsai_crux_origin_url'] ) ) {
				$url = esc_url_raw( (string) $data['newsai_crux_origin_url'] );
				update_option( 'newsai_crux_origin_url', $url, false );
			}
			if ( isset( $data['newsai_psi_api_key'] ) && trim( (string) $data['newsai_psi_api_key'] ) !== '' ) {
				update_option( 'newsai_psi_api_key', sanitize_text_field( (string) $data['newsai_psi_api_key'] ), false );
			}
		}

		newsai_settings_registry_after_save_section( $section_id, $data, $schema_before );

		return true;
	}
}

if ( ! function_exists( 'newsai_settings_registry_health' ) ) {
	function newsai_settings_registry_health() {
		$schema_type = (string) get_option( 'nros_schema_type', 'newsarticle' );
		$megasite    = ( get_option( 'nros_schema_megasite_mode', 'yes' ) === 'yes' );
		$lite        = ( get_option( 'newsai_lite_mode', 'no' ) === 'yes' );
		$ai_on       = function_exists( 'newsai_ai_is_active' ) && newsai_ai_is_active();

		return [
			'schema' => [
				'state'   => ( $schema_type !== 'none' ) ? 'ok' : 'warn',
				'message' => ( $schema_type !== 'none' )
					? __( 'Schema is active.', 'newsroom-ai-assistant' )
					: __( 'Schema is off.', 'newsroom-ai-assistant' ),
			],
			'performance' => [
				'state'   => ( $megasite || $lite ) ? 'ok' : 'info',
				'message' => $megasite
					? __( 'Megasite protections on.', 'newsroom-ai-assistant' )
					: __( 'Enable Megasite mode on large sites.', 'newsroom-ai-assistant' ),
			],
			'setup' => [
				'state'   => ( trim( (string) get_option( 'nros_site_name', '' ) ) !== '' ) ? 'ok' : 'warn',
				'message' => __( 'Site identity configured.', 'newsroom-ai-assistant' ),
			],
			'ai' => [
				'state'   => $ai_on ? 'ok' : 'info',
				'message' => $ai_on ? __( 'AI Assist active.', 'newsroom-ai-assistant' ) : __( 'AI Assist not configured.', 'newsroom-ai-assistant' ),
			],
		];
	}
}

if ( ! function_exists( 'newsai_settings_registry_payload' ) ) {
	function newsai_settings_registry_payload() {
		$site_profile = (string) get_option( 'newsai_site_profile', 'newsroom' );
		$publisher    = function_exists( 'newsai_get_publisher_profile' ) ? newsai_get_publisher_profile() : 'standard';

		return [
			'version'  => defined( 'NEWSAI_VERSION' ) ? NEWSAI_VERSION : '1',
			'groups'   => newsai_settings_registry_groups(),
			'sections' => newsai_settings_registry_enrich_sections( newsai_settings_registry_sections() ),
			'values'   => newsai_settings_registry_read_values(),
			'health'   => newsai_settings_registry_health(),
			'pro'      => [ 'active' => newsai_settings_registry_is_pro() ],
			'profiles' => [
				'site'             => $site_profile,
				'siteChoices'      => [
					'newsroom' => __( 'Newsroom Profile', 'newsroom-ai-assistant' ),
					'blog'     => __( 'Blog Profile', 'newsroom-ai-assistant' ),
				],
				'publisher'        => $publisher,
				'publisherChoices' => function_exists( 'newsai_publisher_profile_choices' ) ? newsai_publisher_profile_choices() : [],
			],
			'meta'     => newsai_settings_registry_meta(),
			'wizard'   => [
				'completed' => (bool) get_option( 'nros_wizard_completed', false ),
				'url'       => admin_url( 'admin.php?page=newsai-wizard' ),
			],
			'classicUrl' => admin_url( 'admin.php?page=newsai-settings&tab=settings&ui=classic' ),
			'switchClassicUrl' => admin_url( 'admin.php?page=newsai-settings&tab=settings&newsai_ui_mode=classic' ),
			'settingsPageUrl' => admin_url( 'admin.php?page=newsai-settings&tab=settings' ),
			'dashboardPageUrl' => admin_url( 'admin.php?page=newsai-settings&tab=alerts' ),
			'reactUi'    => [
				'mode'       => newsai_settings_ui_mode(),
				'active'     => newsai_settings_react_enabled(),
				'locked'     => newsai_settings_ui_locked_by_constant(),
				'buildReady' => newsai_settings_react_build_exists(),
			],
			'i18n'       => [
				'save'            => __( 'Save changes', 'newsroom-ai-assistant' ),
				'saving'          => __( 'Saving…', 'newsroom-ai-assistant' ),
				'saved'           => __( 'Settings saved.', 'newsroom-ai-assistant' ),
				'error'           => __( 'Could not save. Try again.', 'newsroom-ai-assistant' ),
				'helpTitle'       => __( 'Tip', 'newsroom-ai-assistant' ),
				'classicLink'     => __( 'Open classic settings', 'newsroom-ai-assistant' ),
				'classicTitle'    => __( 'Need every option?', 'newsroom-ai-assistant' ),
				'classicDesc'     => __( 'Classic settings include schema JSON preview, full indexing controls, and the original tabbed form.', 'newsroom-ai-assistant' ),
				'openClassic'     => __( 'Open classic settings', 'newsroom-ai-assistant' ),
				'openDashboard'   => __( 'Dashboard', 'newsroom-ai-assistant' ),
				'switchClassicUi' => __( 'Switch to classic UI', 'newsroom-ai-assistant' ),
				'classicDashTitle' => __( 'Need kanban & radar?', 'newsroom-ai-assistant' ),
				'classicDashDesc'  => __( 'Classic dashboard includes the full kanban board, competitor radar, and legacy task tools.', 'newsroom-ai-assistant' ),
				'gettingStarted'  => __( 'New here?', 'newsroom-ai-assistant' ),
				'runWizard'       => __( 'Run the setup wizard to configure schema, GEO, and publisher profile.', 'newsroom-ai-assistant' ),
				'wizardCta'       => __( 'Start wizard', 'newsroom-ai-assistant' ),
				'wizardRerun'     => __( 'Re-run setup wizard', 'newsroom-ai-assistant' ),
				'loading'         => __( 'Loading settings…', 'newsroom-ai-assistant' ),
				'unsaved'         => __( '%d unsaved section(s)', 'newsroom-ai-assistant' ),
				'on'              => __( 'On', 'newsroom-ai-assistant' ),
				'off'             => __( 'Off', 'newsroom-ai-assistant' ),
				'guide'           => __( 'Guided setup — change one section at a time and save when ready.', 'newsroom-ai-assistant' ),
				'applyProfile'    => __( 'Apply preset', 'newsroom-ai-assistant' ),
				'profileConfirm'  => __( 'Apply this preset? Related settings will be overwritten.', 'newsroom-ai-assistant' ),
				'siteProfile'     => __( 'Site type', 'newsroom-ai-assistant' ),
				'publisherProfile'=> __( 'Performance tier', 'newsroom-ai-assistant' ),
				'warmSchema'      => __( 'Warm next 25 posts', 'newsroom-ai-assistant' ),
				'proLocked'       => __( 'Pro feature', 'newsroom-ai-assistant' ),
				'passwordKeep'    => __( 'Leave blank to keep saved key.', 'newsroom-ai-assistant' ),
				'testConnection'  => __( 'Test connection', 'newsroom-ai-assistant' ),
				'syncNow'         => __( 'Sync now', 'newsroom-ai-assistant' ),
				'saveJson'        => __( 'Save service account JSON', 'newsroom-ai-assistant' ),
				'removeJson'      => __( 'Remove stored JSON', 'newsroom-ai-assistant' ),
				'replaceJson'     => __( 'Replace service account JSON', 'newsroom-ai-assistant' ),
				'jsonConfigured'  => __( 'Service account configured', 'newsroom-ai-assistant' ),
				'jsonMissing'     => __( 'No service account stored yet.', 'newsroom-ai-assistant' ),
				'jsonLocked'      => __( 'Set via NEWSAI_INDEXING_SERVICE_JSON in wp-config.php', 'newsroom-ai-assistant' ),
				'startBackfill'   => __( 'Start 12-month backfill', 'newsroom-ai-assistant' ),
				'backfillRunning' => __( 'Backfill running…', 'newsroom-ai-assistant' ),
				'testIndexNow'    => __( 'Test IndexNow', 'newsroom-ai-assistant' ),
				'testWeeklyReport'=> __( 'Send test report', 'newsroom-ai-assistant' ),
				'generatePolicy'  => __( 'Generate page with AI', 'newsroom-ai-assistant' ),
				'working'         => __( 'Working…', 'newsroom-ai-assistant' ),
				'reactUiLabel'    => __( 'Modern settings UI', 'newsroom-ai-assistant' ),
				'reactUiHelp'     => __( 'Guided React settings instead of the classic form. Stored in the database — no wp-config change needed.', 'newsroom-ai-assistant' ),
				'reloadSettings'  => __( 'Reloading settings…', 'newsroom-ai-assistant' ),
			],
		];
	}
}
