<?php

namespace Fotogenic_AI;

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

final class Settings {
    private static ?Settings $instance = null;
    private string $option_name = 'fotogenic_ai_settings';

    private function __construct() {}

    public static function instance(): Settings {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function get_option_name(): string {
        return $this->option_name;
    }

    public function get_defaults(): array {
        $api_defaults = Api_Endpoints::get_default_config();

        return [
            'api_environment'          => 'production',
            'api_base_path'            => $api_defaults['base_path'],
            'api_endpoints'            => $api_defaults['endpoints'],
            'custom_instructions'      => '',
            'debug_logging'            => 1,
            'delete_data_on_uninstall' => 0,
        ];
    }

    public function get_options(): array {
        $options = get_option( $this->option_name, [] );
        if ( ! is_array( $options ) ) {
            $options = [];
        }

        return wp_parse_args( $options, $this->get_defaults() );
    }

    public function get_api_base_url(): string {
        $options   = $this->get_options();
        $env       = $options['api_environment'];
        $defaults  = Api_Endpoints::get_default_config();
        $base_url  = $defaults['base_urls'][ $env ] ?? $defaults['base_urls']['production'];

        return (string) apply_filters( 'fotogenic_ai_api_base_url', $base_url, $env );
    }

    public function get_api_base_path(): string {
        $options = $this->get_options();
        $path    = $options['api_base_path'];
        if ( '' === trim( (string) $path ) ) {
            $defaults = Api_Endpoints::get_default_config();
            $path = $defaults['base_path'] ?? '';
        }
        $path = (string) apply_filters( 'fotogenic_ai_api_base_path', $path );
        return Api_Endpoints::normalize_base_path( $path );
    }

    public function get_api_endpoints(): array {
        $options   = $this->get_options();
        $endpoints = $options['api_endpoints'];
        $endpoints = (array) apply_filters( 'fotogenic_ai_api_endpoints', $endpoints );
        return Api_Endpoints::normalize_endpoints( $endpoints );
    }

    public function sanitize_settings( $input ): array {
        return $this->prepare_settings_for_save( $input, [
            'context' => 'settings',
        ] );
    }

    public function prepare_settings_for_save( $input, array $args = [] ): array {
        $existing = isset( $args['existing'] ) && is_array( $args['existing'] )
            ? wp_parse_args( $args['existing'], $this->get_defaults() )
            : $this->get_options();
        $input = is_array( $input ) ? $input : [];

        return $this->sanitize_core_settings( $input, $existing );
    }

    private function sanitize_core_settings( array $input, array $existing ): array {
        $defaults  = $this->get_defaults();
        $sanitized = $defaults;

        $sanitized['api_environment'] = 'production';
        $sanitized['api_base_path']   = isset( $input['api_base_path'] )
            ? Api_Endpoints::normalize_base_path( (string) $input['api_base_path'] )
            : Api_Endpoints::normalize_base_path( (string) ( $existing['api_base_path'] ?? $defaults['api_base_path'] ) );
		$endpoint_defaults = (array) $defaults['api_endpoints'];
		if ( isset( $existing['api_endpoints'] ) && is_array( $existing['api_endpoints'] ) ) {
			$endpoint_defaults = array_replace(
				$endpoint_defaults,
				array_intersect_key( $existing['api_endpoints'], $endpoint_defaults )
			);
		}
        $sanitized['api_endpoints'] = $this->sanitize_api_endpoints(
            isset( $input['api_endpoints'] ) && is_array( $input['api_endpoints'] ) ? $input['api_endpoints'] : [],
			$endpoint_defaults
        );
        $custom_instructions = isset( $input['custom_instructions'] )
            ? sanitize_textarea_field( (string) $input['custom_instructions'] )
            : (string) ( $existing['custom_instructions'] ?? $defaults['custom_instructions'] );
        $sanitized['custom_instructions'] = function_exists( 'mb_substr' )
            ? mb_substr( $custom_instructions, 0, 5000 )
            : substr( $custom_instructions, 0, 5000 );
        $sanitized['debug_logging']            = empty( $input['debug_logging'] ) ? 0 : 1;
        $sanitized['delete_data_on_uninstall'] = empty( $input['delete_data_on_uninstall'] ) ? 0 : 1;

        return $sanitized;
    }

    private function sanitize_api_endpoints( array $input, array $defaults ): array {
        $sanitized = [];
        foreach ( $defaults as $key => $default_value ) {
            $value = $input[ $key ] ?? $default_value;
            $sanitized[ $key ] = sanitize_text_field( (string) $value );
        }
        return Api_Endpoints::normalize_endpoints( $sanitized );
    }
}
