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

if ( ! class_exists( 'SftcyWordaiSeoStandards' ) ) {
	/**
	 * Central SEO standards used by WordAI generation and scan workflows.
	 */
	class SftcyWordaiSeoStandards {

		public static function content_setting_defaults() {
			return array(
				'sc-wordai-use-seo-content-structure' => 1,
				'sc-wordai-use-heading-structure'     => 1,
				'sc-wordai-use-seo-content-depth'     => 1,
				'sc-wordai-search-intent-mode'        => 'auto',
				'sc-wordai-use-people-first-content'  => 1,
				'sc-wordai-use-trust-signals'         => 1,
				'sc-wordai-faq-section-mode'          => 'off',
				'sc-wordai-faq-count'                 => '2',
				'sc-wordai-internal-link-policy'      => 'natural',
				'sc-wordai-schema-type'               => 'auto',
				'sc-wordai-readability-target'        => 'standard',
				'sc-wordai-use-content-freshness'     => 1,
			);
		}

		public static function search_intent_modes() {
			return array(
				'auto'          => __( 'Auto detect from prompt', 'wordai-pro' ),
				'informational' => __( 'Informational', 'wordai-pro' ),
				'commercial'    => __( 'Commercial research', 'wordai-pro' ),
				'transactional' => __( 'Transactional / conversion', 'wordai-pro' ),
				'navigational'  => __( 'Navigational / brand page', 'wordai-pro' ),
				'how_to'        => __( 'How-to / tutorial', 'wordai-pro' ),
				'comparison'    => __( 'Comparison', 'wordai-pro' ),
				'review'        => __( 'Review', 'wordai-pro' ),
			);
		}

		public static function faq_section_modes() {
			return array(
				'off'    => __( 'Do not add FAQ section', 'wordai-pro' ),
				'auto'   => __( 'Auto add when helpful', 'wordai-pro' ),
				'always' => __( 'Always add FAQ section', 'wordai-pro' ),
			);
		}

		public static function faq_counts() {
			return array(
				'2' => __( '2 questions', 'wordai-pro' ),
				'3' => __( '3 questions', 'wordai-pro' ),
				'4' => __( '4 questions', 'wordai-pro' ),
				'5' => __( '5 questions', 'wordai-pro' ),
				'6' => __( '6 questions', 'wordai-pro' ),
			);
		}

		public static function internal_link_policies() {
			return array(
				'none'    => __( 'Do not request internal links', 'wordai-pro' ),
				'natural' => __( 'Add one natural internal link when relevant', 'wordai-pro' ),
				'suggest' => __( 'Add internal link suggestions when relevant', 'wordai-pro' ),
			);
		}

		public static function schema_types() {
			return array(
				'auto'          => __( 'Auto match content type', 'wordai-pro' ),
				'article'       => __( 'Article', 'wordai-pro' ),
				'blogposting'   => __( 'BlogPosting', 'wordai-pro' ),
				'product'       => __( 'Product', 'wordai-pro' ),
				'faqpage'       => __( 'FAQPage', 'wordai-pro' ),
				'howto'         => __( 'HowTo', 'wordai-pro' ),
				'review'        => __( 'Review', 'wordai-pro' ),
				'localbusiness' => __( 'LocalBusiness', 'wordai-pro' ),
			);
		}

		public static function readability_targets() {
			return array(
				'simple'   => __( 'Simple', 'wordai-pro' ),
				'standard' => __( 'Standard', 'wordai-pro' ),
				'expert'   => __( 'Expert', 'wordai-pro' ),
			);
		}

		public static function sanitize_content_settings( $settings ) {
			$settings = is_array( $settings ) ? $settings : array();
			$defaults = self::content_setting_defaults();

			$select_maps = array(
				'sc-wordai-search-intent-mode'   => self::search_intent_modes(),
				'sc-wordai-faq-section-mode'     => self::faq_section_modes(),
				'sc-wordai-faq-count'            => self::faq_counts(),
				'sc-wordai-internal-link-policy' => self::internal_link_policies(),
				'sc-wordai-schema-type'          => self::schema_types(),
				'sc-wordai-readability-target'   => self::readability_targets(),
			);

			foreach ( $select_maps as $key => $map ) {
				$value = isset( $settings[ $key ] ) ? sanitize_key( (string) $settings[ $key ] ) : (string) $defaults[ $key ];
				if ( ! isset( $map[ $value ] ) ) {
					$value = (string) $defaults[ $key ];
				}
				$settings[ $key ] = $value;
			}

			foreach ( array( 'sc-wordai-use-people-first-content', 'sc-wordai-use-trust-signals', 'sc-wordai-use-content-freshness' ) as $key ) {
				if ( ! array_key_exists( $key, $settings ) ) {
					$settings[ $key ] = (int) $defaults[ $key ];
					continue;
				}
				$settings[ $key ] = ! empty( $settings[ $key ] ) ? 1 : 0;
			}

			return $settings;
		}

		public static function get_rules( $post_type = 'post' ) {
			$is_product = 'product' === $post_type;

			return array(
				'meta_title_min'       => 35,
				'meta_title_max'       => 60,
				'meta_description_min' => 120,
				'meta_description_max' => 160,
				'minimum_words'        => $is_product ? 120 : 500,
				'heading_tags'         => array( 'h2', 'h3' ),
				'focus_keyword_target' => 'Use the focus keyword naturally in the title, intro, body, SEO title, and meta description.',
				'link_target'          => 'Use one useful internal link and one authoritative external reference when they genuinely fit the content.',
				'image_target'         => 'Use a relevant featured image and descriptive image alt text when images are generated or inserted.',
			);
		}

		public static function is_enabled( $settings, $key, $default = 1 ) {
			if ( ! is_array( $settings ) || ! array_key_exists( $key, $settings ) ) {
				return (bool) $default;
			}

			return (int) $settings[ $key ] === 1;
		}

		public static function build_content_prompt_guidelines( $settings = array(), $paragraph_count = 3, $post_type = 'post' ) {
			$rules            = self::get_rules( $post_type );
			$paragraph_count  = max( 1, (int) $paragraph_count );
			$minimum_words    = max( (int) $rules['minimum_words'], $paragraph_count * 140 );
			$site_url         = home_url( '/' );
			$search_intent    = sanitize_key( (string) ( $settings['sc-wordai-search-intent-mode'] ?? 'auto' ) );
			$faq_mode         = sanitize_key( (string) ( $settings['sc-wordai-faq-section-mode'] ?? 'auto' ) );
			$faq_count        = max( 2, min( 6, (int) ( $settings['sc-wordai-faq-count'] ?? 2 ) ) );
			$link_policy      = sanitize_key( (string) ( $settings['sc-wordai-internal-link-policy'] ?? 'natural' ) );
			$schema_type      = sanitize_key( (string) ( $settings['sc-wordai-schema-type'] ?? 'auto' ) );
			$readability      = sanitize_key( (string) ( $settings['sc-wordai-readability-target'] ?? 'standard' ) );
			$lines            = array();

			if ( self::is_enabled( $settings, 'sc-wordai-use-seo-content-structure', 1 ) ) {
				if ( self::is_basic_tier() ) {
					$lines[] = 'Follow practical SEO writing standards for the article body only: clear search intent, natural topic wording, helpful intro, scannable sections, and a useful conclusion.';
					$lines[] = 'Do not generate separate SEO title, meta description, or focus keyword fields in this response.';
				} else {
					$lines[] = 'Follow practical SEO writing standards: clear search intent, natural focus keyword usage, helpful intro, scannable sections, and a useful conclusion.';
					$lines[] = sprintf( 'Keep SEO title/meta compatibility in mind: title target %d-%d characters, meta description target %d-%d characters.', $rules['meta_title_min'], $rules['meta_title_max'], $rules['meta_description_min'], $rules['meta_description_max'] );
				}
				$lines[] = sprintf( 'Respect the selected content length: use exactly %d body paragraphs. If more SEO depth is needed, make those paragraphs richer instead of adding extra paragraphs.', $paragraph_count );
				$lines[] = self::get_search_intent_instruction( $search_intent );
				$lines[] = self::get_internal_link_instruction( $link_policy, $site_url );
				$lines[] = 'Do not invent fake external URLs. Mention external sources only when you are confident they are real and relevant; otherwise omit external links.';
			}

			if ( self::is_enabled( $settings, 'sc-wordai-use-people-first-content', 1 ) ) {
				$lines[] = 'Make the content people-first: provide practical value, original phrasing, concrete examples, and useful details beyond generic summaries.';
			}

			if ( self::is_enabled( $settings, 'sc-wordai-use-trust-signals', 1 ) ) {
				$lines[] = 'Use trust-building language: be accurate, avoid unsupported claims, avoid fake statistics, and add cautious wording for health, legal, finance, or safety topics.';
			}

			if ( self::is_enabled( $settings, 'sc-wordai-use-content-freshness', 1 ) ) {
				$lines[] = 'Keep time-sensitive content fresh: avoid outdated claims, avoid unsupported current-year statistics, and state when readers should verify changing details.';
			}

			if ( self::is_enabled( $settings, 'sc-wordai-use-heading-structure', 1 ) ) {
				$lines[] = 'Return clean WordPress-ready HTML body content using <h2> for main sections and <h3> for subsections when helpful.';
				$lines[] = 'Do not use Markdown headings, asterisks, bullet lists, numbered lists, <ul>, <ol>, <li>, code fences, or surrounding explanations.';
			} else {
				$lines[] = 'Return clean paragraph text without Markdown formatting, bullet lists, numbered lists, code fences, or surrounding explanations.';
			}

			if ( self::is_enabled( $settings, 'sc-wordai-use-seo-content-depth', 1 ) ) {
				$lines[] = sprintf( 'Write at least %d words unless the topic is only suitable for a shorter product-style description.', $minimum_words );
				$lines[] = 'Add concrete details, benefits, examples, and clear transitions so the content is useful instead of thin or repetitive.';
			}

			$lines[] = self::get_readability_instruction( $readability );
			$lines[] = self::get_schema_instruction( $schema_type );
			$faq_instruction = self::get_faq_instruction( $faq_mode, $faq_count );
			if ( $faq_instruction ) {
				$lines[] = $faq_instruction;
			}

			return implode( "\n", $lines );
		}

		private static function get_search_intent_instruction( $mode ) {
			$instructions = array(
				'auto'          => 'Infer the search intent from the user prompt and structure the content for that intent.',
				'informational' => 'Target informational intent: explain the topic clearly, answer likely questions, and teach the reader.',
				'commercial'    => 'Target commercial research intent: compare considerations, benefits, tradeoffs, and buying factors without sounding pushy.',
				'transactional' => 'Target transactional intent: make benefits, next steps, objections, and conversion-oriented details clear while staying helpful.',
				'navigational'  => 'Target navigational or brand-page intent: clarify what the page, brand, product, or service is and help visitors find the next step.',
				'how_to'        => 'Target how-to intent: organize the answer as practical steps, prerequisites, tips, and common mistakes when suitable.',
				'comparison'    => 'Target comparison intent: explain alternatives, selection criteria, pros, cons, and best-fit use cases fairly.',
				'review'        => 'Target review intent: cover strengths, limitations, use cases, credibility factors, and who should or should not choose it.',
			);

			return $instructions[ $mode ] ?? $instructions['auto'];
		}

		private static function get_internal_link_instruction( $policy, $site_url ) {
			if ( 'none' === $policy ) {
				return 'Do not add internal links unless the user explicitly asks for them.';
			}

			if ( 'suggest' === $policy ) {
				return sprintf( 'When relevant, add a short "Internal link ideas" note with natural anchor text suggestions for this site: %s', $site_url );
			}

			return sprintf( 'If an internal link fits naturally, include one useful internal link to this site URL: %s', $site_url );
		}

		private static function get_readability_instruction( $target ) {
			if ( 'simple' === $target ) {
				return 'Use simple readability: short sentences, plain words, minimal jargon, and clear paragraph breaks.';
			}

			if ( 'expert' === $target ) {
				return 'Use expert readability: precise terminology, deeper context, and professional detail while keeping the writing clear.';
			}

			return 'Use standard readability: clear, natural, well-organized writing that most readers can follow easily.';
		}

		private static function get_schema_instruction( $schema_type ) {
			if ( 'auto' === $schema_type ) {
				return 'Structure the content so it could support the most appropriate schema type, but do not output JSON-LD or schema markup.';
			}

			$schema_labels = array(
				'article'       => 'Article',
				'blogposting'   => 'BlogPosting',
				'product'       => 'Product',
				'faqpage'       => 'FAQPage',
				'howto'         => 'HowTo',
				'review'        => 'Review',
				'localbusiness' => 'LocalBusiness',
			);

			$label = $schema_labels[ $schema_type ] ?? 'Article';
			return sprintf( 'Structure the content so it could support %s schema if the site owner later adds structured data, but do not output JSON-LD or schema markup.', $label );
		}

		private static function get_faq_instruction( $mode, $count ) {
			if ( 'off' === $mode ) {
				return 'Do not add an FAQ section, Frequently Asked Questions heading, Q&A block, standalone question-and-answer list, or FAQ-style ending unless the user prompt explicitly asks for FAQs.';
			}

			if ( 'always' === $mode ) {
				return sprintf( 'Add a concise FAQ section with %d genuinely useful questions and answers at the end.', $count );
			}

			return sprintf( 'Add a concise FAQ section with up to %d questions only when it clearly helps the topic or search intent; skip it for content types where an FAQ would feel forced.', $count );
		}

		public static function get_seo_title_generation_guideline( $post_type = 'post' ) {
			$rules = self::get_rules( $post_type );
			$min   = max( 50, (int) $rules['meta_title_min'] );
			$max   = min( 60, (int) $rules['meta_title_max'] );

			return sprintf(
				'Target %1$d-%2$d characters. Never return a very short SEO title; include the main topic/focus keyword near the beginning, keep it natural, compelling, and search-friendly.',
				$min,
				$max
			);
		}

		public static function get_basic_upgrade_suggestion() {
			return 'SEO title, meta description, and focus keyword need improvement for better search visibility. Upgrade to WordAI Pro to activate SEO generation in the content modal: https://softcoy.com/products/wordai-pro/checkout';
		}

		private static function is_basic_tier() {
			return class_exists( 'SftcyWordaiFeatures' ) && SftcyWordaiFeatures::wordai_is_basic_tier();
		}
	}
}
