<?php

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

class Niwa_AI_Admin_Settings {

    public function register() {
        register_setting( 'niwa_ai_auth_group', Niwa_AI_Constants::OPT_AUTH, array( $this, 'sanitize_auth' ) );
        register_setting( 'niwa_ai_general_group', Niwa_AI_Constants::OPT_SETTINGS, array( $this, 'sanitize_general' ) );
    }

    public function sanitize_auth( $input ) {
        $existing = $this->load_auth_options_from_db();
        $out = is_array( $existing ) ? $existing : array();

        $mode = isset( $input['mode'] ) ? sanitize_text_field( $input['mode'] ) : 'api_key';
        $out['mode'] = in_array( $mode, array( 'api_key', 'oauth' ), true ) ? $mode : 'api_key';
        $out['api_key'] = isset( $input['api_key'] ) ? sanitize_text_field( $input['api_key'] ) : ( isset( $out['api_key'] ) ? sanitize_text_field( (string) $out['api_key'] ) : '' );

        // Backward compatibility: preserve manual token fields if provided.
        if ( isset( $input['oauth_access_token'] ) ) {
            $out['oauth_access_token'] = sanitize_text_field( $input['oauth_access_token'] );
        }
        if ( isset( $input['oauth_refresh_token'] ) ) {
            $out['oauth_refresh_token'] = sanitize_text_field( $input['oauth_refresh_token'] );
        }
        if ( isset( $input['oauth_expires_at'] ) ) {
            $out['oauth_expires_at'] = max( 0, intval( $input['oauth_expires_at'] ) );
        }
        if ( isset( $input['oauth_account_id'] ) ) {
            $out['oauth_account_id'] = sanitize_text_field( $input['oauth_account_id'] );
        }
        if ( isset( $input['oauth_email'] ) ) {
            $out['oauth_email'] = sanitize_email( $input['oauth_email'] );
        }
        if ( isset( $input['oauth_last_error'] ) ) {
            $out['oauth_last_error'] = sanitize_text_field( $input['oauth_last_error'] );
        }

        $auth_changed =
            ( isset( $existing['mode'] ) ? (string) $existing['mode'] : '' ) !== ( isset( $out['mode'] ) ? (string) $out['mode'] : '' )
            || ( isset( $existing['api_key'] ) ? (string) $existing['api_key'] : '' ) !== ( isset( $out['api_key'] ) ? (string) $out['api_key'] : '' );

        if ( $auth_changed && function_exists( 'niwa_ai_queue_admin_autonomy_poll_restart' ) ) {
            niwa_ai_queue_admin_autonomy_poll_restart( 'auth-settings-updated' );
        }

        return $out;
    }

    private function load_auth_options_from_db() {
        global $wpdb;

        if ( isset( $wpdb ) && $wpdb instanceof wpdb ) {
            $raw = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
                    Niwa_AI_Constants::OPT_AUTH
                )
            );

            if ( null !== $raw ) {
                $decoded = maybe_unserialize( $raw );
                return is_array( $decoded ) ? $decoded : array();
            }
        }

        $opts = get_option( Niwa_AI_Constants::OPT_AUTH, array() );
        return is_array( $opts ) ? $opts : array();
    }

    public function sanitize_general( $input ) {
        $existing = get_option( Niwa_AI_Constants::OPT_SETTINGS, array() );
        $out = is_array( $existing ) ? $existing : array();
		unset( $out['frontend_rlm_model'], $out['rlm_confidence_threshold'], $out['rlm_min_chunks'], $out['memory_vector_scan_cap'] );

        if ( ! is_array( $input ) ) {
            return $out;
        }

        $form = isset( $input['_niwa_general_form'] ) ? sanitize_key( (string) $input['_niwa_general_form'] ) : '';
		if ( array_key_exists( 'model', $input ) ) {
			unset( $out['model'] );
			$model = $this->validate_model_for_mode( $input['model'], $this->get_effective_auth_mode() );
			if ( '' !== $model ) {
				$out['model'] = $model;
			}
		}
		if ( array_key_exists( 'enable_frontend_stage_timing', $input ) ) {
			$out['enable_frontend_stage_timing'] = 1;
		} elseif ( 'main' === $form ) {
			$out['enable_frontend_stage_timing'] = 0;
		}

        if ( isset( $input['chat_theme_mode'] ) ) {
            $theme = sanitize_text_field( $input['chat_theme_mode'] );
            $out['chat_theme_mode'] = in_array( $theme, array( 'neutral', 'auto', 'light', 'dark' ), true ) ? $theme : 'neutral';
        }
        if ( array_key_exists( 'enable_flyout', $input ) ) {
            $out['enable_flyout'] = 1;
        } elseif ( 'main' === $form ) {
            $out['enable_flyout'] = 0;
        }
        if ( array_key_exists( 'frontend_avatar_url', $input ) ) {
            $out['frontend_avatar_url'] = esc_url_raw( $input['frontend_avatar_url'] );
        }
        if ( array_key_exists( 'backend_avatar_url', $input ) ) {
            $out['backend_avatar_url'] = esc_url_raw( $input['backend_avatar_url'] );
        }

        return $out;
    }

	private function get_effective_auth_mode() {
		if ( ! class_exists( 'Niwa_AI_Auth_Manager' ) ) {
			return 'api_key';
		}

		return ( new Niwa_AI_Auth_Manager( 'frontend' ) )->get_mode();
	}

	private function validate_model_for_mode( $model, $mode ) {
		if ( ! class_exists( 'Niwa_AI_Model_Catalog' ) ) {
			return '';
		}

		$model   = strtolower( trim( sanitize_text_field( (string) $model ) ) );
		$model   = Niwa_AI_Model_Catalog::migrate_retired_selector( $model );
		$catalog = new Niwa_AI_Model_Catalog();

		return $catalog->is_valid_model_for_mode( $mode, $model ) ? $model : '';
	}
}
