<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'SftcyWordaiFeatures' ) ) {
	/**
	 * Central feature-availability helper for WordAI.
	 */
	class SftcyWordaiFeatures {
		private static $wordai_feature_flags_registry = null;

		public static function wordai_get_product_tier() {
			$tier = defined( 'WORDAI_PRODUCT_TIER' ) ? WORDAI_PRODUCT_TIER : 'pro';
			$tier = apply_filters( 'wordai_product_tier', $tier );
			return sanitize_key( $tier );
		}

		public static function wordai_get_textdomain() {
			$textdomain = defined( 'SFTCY_WORDAI_TEXT_DOMAIN' ) ? SFTCY_WORDAI_TEXT_DOMAIN : 'wordai-pro';
			return (string) apply_filters( 'wordai_textdomain', $textdomain );
		}

		public static function wordai_get_feature_flags_registry() {
			if ( null !== self::$wordai_feature_flags_registry ) {
				return self::$wordai_feature_flags_registry;
			}

			$registry_file = trailingslashit( SFTCY_WORDAI_PLUGIN_DIR ) . 'features/feature-flags.json';
			$registry      = array(
				'schemaVersion' => 1,
				'features'      => array(),
			);

			if ( file_exists( $registry_file ) ) {
				$raw = file_get_contents( $registry_file );
				$map = json_decode( $raw, true );

				if ( is_array( $map ) && isset( $map['features'] ) && is_array( $map['features'] ) ) {
					$registry = $map;
				}
			}

			self::$wordai_feature_flags_registry = (array) apply_filters( 'wordai_feature_flags_registry', $registry );
			return self::$wordai_feature_flags_registry;
		}

		public static function wordai_get_feature_rule( $feature_key = '' ) {
			$feature_key = sanitize_key( $feature_key );
			$registry    = self::wordai_get_feature_flags_registry();
			$tier        = self::wordai_get_product_tier();

			if ( empty( $feature_key ) || empty( $registry['features'][ $feature_key ] ) || ! is_array( $registry['features'][ $feature_key ] ) ) {
				return array(
					'feature' => $feature_key,
					'tier'    => $tier,
					'status'  => 'pro' === $tier ? 'full' : 'pro_only',
					'limits'  => array(),
				);
			}

			$feature_map = $registry['features'][ $feature_key ];
			$status      = isset( $feature_map[ $tier ] ) ? sanitize_key( $feature_map[ $tier ] ) : ( 'pro' === $tier ? 'full' : 'pro_only' );
			$limits      = array();

			if ( ! empty( $feature_map['limits'][ $tier ] ) && is_array( $feature_map['limits'][ $tier ] ) ) {
				$limits = $feature_map['limits'][ $tier ];
			}

			return array(
				'feature' => $feature_key,
				'tier'    => $tier,
				'status'  => $status,
				'limits'  => $limits,
			);
		}

		public static function wordai_get_default_feature_flags() {
			$tier         = self::wordai_get_product_tier();
			$registry     = self::wordai_get_feature_flags_registry();
			$feature_flags = array();

			if ( ! empty( $registry['features'] ) && is_array( $registry['features'] ) ) {
				foreach ( $registry['features'] as $feature_key => $feature_map ) {
					if ( ! is_array( $feature_map ) ) {
						continue;
					}

					$status = isset( $feature_map[ $tier ] ) ? sanitize_key( $feature_map[ $tier ] ) : ( 'pro' === $tier ? 'full' : 'pro_only' );
					$feature_flags[ sanitize_key( $feature_key ) ] = in_array( $status, array( 'full', 'limited' ), true );
				}
			}

			return (array) apply_filters( 'wordai_feature_flags', $feature_flags, $tier );
		}

		public static function wordai_is_feature_available( $feature_key = '' ) {
			$feature_key   = sanitize_key( $feature_key );
			$feature_flags = self::wordai_get_default_feature_flags();
			$is_available  = ! empty( $feature_flags[ $feature_key ] );

			return (bool) apply_filters(
				'wordai_is_feature_available',
				$is_available,
				$feature_key,
				self::wordai_get_product_tier()
			);
		}

		public static function wordai_is_feature_limited( $feature_key = '' ) {
			$rule = self::wordai_get_feature_rule( $feature_key );
			return isset( $rule['status'] ) && 'limited' === $rule['status'];
		}

		public static function wordai_get_feature_limits( $feature_key = '' ) {
			$rule = self::wordai_get_feature_rule( $feature_key );
			return ! empty( $rule['limits'] ) && is_array( $rule['limits'] ) ? $rule['limits'] : array();
		}

		public static function wordai_get_feature_availability( $feature_key = '' ) {
			$rule      = self::wordai_get_feature_rule( $feature_key );
			$status    = isset( $rule['status'] ) ? $rule['status'] : 'pro_only';
			$available = in_array( $status, array( 'full', 'limited' ), true );
			$limits    = self::wordai_get_feature_limits( $feature_key );
			$message   = '';

			if ( 'pro_only' === $status ) {
				$message = __( 'Available in WordAI Pro.', self::wordai_get_textdomain() );
			} elseif ( 'limited' === $status ) {
				$message = __( 'Available with limits in this version.', self::wordai_get_textdomain() );
			}

			return array(
				'feature'   => sanitize_key( $feature_key ),
				'tier'      => self::wordai_get_product_tier(),
				'available' => (bool) $available,
				'limited'   => 'limited' === $status,
				'limits'    => $limits,
				'message'   => $message,
			);
		}

		public static function wordai_get_upgrade_url() {
			$url = defined( 'SFTCY_WORDAI_PRODUCT_URL' ) ? SFTCY_WORDAI_PRODUCT_URL : 'https://softcoy.com/products/wordai-pro/checkout';
			return esc_url_raw( (string) apply_filters( 'wordai_upgrade_url', $url ) );
		}

		public static function wordai_get_upgrade_cta_label() {
			return (string) apply_filters( 'wordai_upgrade_cta_label', __( 'Get Pro', self::wordai_get_textdomain() ) );
		}

		public static function wordai_is_basic_tier() {
			return 'basic' === self::wordai_get_product_tier();
		}

		public static function wordai_get_limited_values( $feature_key = '', $limit_key = '', $fallback = array() ) {
			$limits    = self::wordai_get_feature_limits( $feature_key );
			$limit_key = sanitize_key( (string) $limit_key );

			if ( ! empty( $limit_key ) && ! empty( $limits[ $limit_key ] ) && is_array( $limits[ $limit_key ] ) ) {
				return array_values(
					array_map(
						'strval',
						$limits[ $limit_key ]
					)
				);
			}

			return array_values(
				array_map(
					'strval',
					(array) $fallback
				)
			);
		}

		public static function wordai_apply_content_setting_limits( $settings = array() ) {
			$settings = is_array( $settings ) ? $settings : array();

			if ( ! self::wordai_is_basic_tier() ) {
				return $settings;
			}

			$field_map = array(
				'sc-wordai-writing-style'      => array(
					'limit_key' => 'writing_styles',
					'fallback'  => array( 'descriptive', 'persuasive', 'narrative' ),
					'default'   => 'descriptive',
				),
				'sc-wordai-writing-tone'       => array(
					'limit_key' => 'writing_tones',
					'fallback'  => array( 'informative', 'friendly', 'professional' ),
					'default'   => 'informative',
				),
				'sc-wordai-title-length'       => array(
					'limit_key' => 'title_lengths',
					'fallback'  => array( '35n45', '45n55', '50n60' ),
					'default'   => '50n60',
				),
				'sc-wordai-content-paragraphs' => array(
					'limit_key' => 'content_paragraphs',
					'fallback'  => array( '1', '2', '3' ),
					'default'   => '3',
				),
				'sc-wordai-excerpt-words'      => array(
					'limit_key' => 'excerpt_words',
					'fallback'  => array( '20', '30' ),
					'default'   => '30',
				),
				'sc-wordai-tags-number'        => array(
					'limit_key' => 'tags_numbers',
					'fallback'  => array( '2', '3' ),
					'default'   => '2',
					'feature'   => 'language_and_tone_controls',
				),
				'sc-wordai-search-intent-mode' => array(
					'limit_key' => 'search_intents',
					'fallback'  => array( 'auto', 'informational', 'how_to' ),
					'default'   => 'auto',
					'feature'   => 'advanced_seo_content_controls',
				),
				'sc-wordai-faq-section-mode'   => array(
					'limit_key' => 'faq_modes',
					'fallback'  => array( 'off', 'auto' ),
					'default'   => 'off',
					'feature'   => 'advanced_seo_content_controls',
				),
				'sc-wordai-faq-count'          => array(
					'limit_key' => 'faq_counts',
					'fallback'  => array( '2' ),
					'default'   => '2',
					'feature'   => 'advanced_seo_content_controls',
				),
				'sc-wordai-internal-link-policy' => array(
					'limit_key' => 'internal_link_policies',
					'fallback'  => array( 'natural' ),
					'default'   => 'natural',
					'feature'   => 'advanced_seo_content_controls',
				),
				'sc-wordai-schema-type'        => array(
					'limit_key' => 'schema_types',
					'fallback'  => array( 'auto', 'article', 'blogposting' ),
					'default'   => 'auto',
					'feature'   => 'advanced_seo_content_controls',
				),
				'sc-wordai-readability-target' => array(
					'limit_key' => 'readability_targets',
					'fallback'  => array( 'standard' ),
					'default'   => 'standard',
					'feature'   => 'advanced_seo_content_controls',
				),
			);

			foreach ( $field_map as $field_key => $config ) {
				$feature_key    = ! empty( $config['feature'] ) ? $config['feature'] : 'language_and_tone_controls';
				$allowed_values = self::wordai_get_limited_values( $feature_key, $config['limit_key'], $config['fallback'] );
				$current_value  = isset( $settings[ $field_key ] ) ? (string) $settings[ $field_key ] : '';
				$default_value  = isset( $config['default'] ) ? (string) $config['default'] : '';

				if ( empty( $allowed_values ) ) {
					continue;
				}

				if ( ! in_array( $current_value, $allowed_values, true ) ) {
					$settings[ $field_key ] = in_array( $default_value, $allowed_values, true ) ? $default_value : $allowed_values[0];
				}
			}

			$settings['sc-wordai-use-people-first-content'] = 1;
			$settings['sc-wordai-use-trust-signals']        = 1;
			$settings['sc-wordai-use-content-freshness']    = 1;

			return $settings;
		}

		public static function wordai_apply_image_setting_limits( $settings = array() ) {
			$settings = is_array( $settings ) ? $settings : array();

			if ( ! self::wordai_is_basic_tier() ) {
				return $settings;
			}

			$image_limits = self::wordai_get_feature_limits( 'image_generation' );
			$max_images   = ! empty( $image_limits['maxImages'] ) ? max( 1, (int) $image_limits['maxImages'] ) : 1;

			$settings['sc-wordai-image-number'] = isset( $settings['sc-wordai-image-number'] )
				? min( $max_images, max( 1, (int) $settings['sc-wordai-image-number'] ) )
				: $max_images;

			$allowed_gemini_styles = array(
				'photorealistic',
				'cinematic',
				'illustration',
				'watercolor',
				'3d',
				'isometric',
				'anime',
				'pixelart',
			);

			if (
				isset( $settings['sc-wordai-gemini-image-style'] )
				&& ! in_array( (string) $settings['sc-wordai-gemini-image-style'], $allowed_gemini_styles, true )
			) {
				$settings['sc-wordai-gemini-image-style'] = 'photorealistic';
			}

			return $settings;
		}

		public static function wordai_get_embedding_item_limit() {
			$limits = self::wordai_get_feature_limits( 'contents_embedding' );
			return ! empty( $limits['maxItems'] ) ? max( 1, (int) $limits['maxItems'] ) : 0;
		}

		public static function wordai_get_seo_scan_monthly_limit() {
			$limits = self::wordai_get_feature_limits( 'seo_scan' );
			return ! empty( $limits['monthlyItems'] ) ? max( 1, (int) $limits['monthlyItems'] ) : 0;
		}

		public static function wordai_get_provider_feature_key( $provider = '' ) {
			$provider_map = array(
				'openai'    => 'provider_openai',
				'google'    => 'provider_google_gemini',
				'gemini'    => 'provider_google_gemini',
				'anthropic' => 'provider_anthropic_claude',
				'claude'    => 'provider_anthropic_claude',
				'xai'       => 'provider_xai_grok',
				'grok'      => 'provider_xai_grok',
			);

			$provider = sanitize_key( (string) $provider );
			return isset( $provider_map[ $provider ] ) ? $provider_map[ $provider ] : '';
		}

		public static function wordai_is_provider_available( $provider = '' ) {
			$feature_key = self::wordai_get_provider_feature_key( $provider );

			if ( empty( $feature_key ) ) {
				return false;
			}

			return self::wordai_is_feature_available( $feature_key );
		}
	}
}
