<?php
/**
 * SEO plugin detection and meta writers.
 *
 * @package CatalogPilot\AiStudio
 */

namespace CatalogPilot\AiStudio;

defined( 'ABSPATH' ) || exit;

final class SEO {

	const INT_YOAST    = 'yoast';
	const INT_RANKMATH = 'rankmath';
	const INT_AIOSEO   = 'aioseo';
	const INT_CORE     = 'core';

	public static function detect() {
		$active = self::active_plugin_slugs();

		// Yoast — slug: wordpress-seo or wordpress-seo-premium.
		if ( self::plugin_in( $active, array( 'wordpress-seo', 'wordpress-seo-premium' ) )
			|| defined( 'WPSEO_VERSION' )
			|| class_exists( 'WPSEO_Options' ) ) {
			return self::INT_YOAST;
		}
		// Rank Math — slug: seo-by-rank-math (free) or seo-by-rank-math-pro.
		if ( self::plugin_in( $active, array( 'seo-by-rank-math', 'seo-by-rank-math-pro' ) )
			|| defined( 'RANK_MATH_VERSION' )
			|| class_exists( '\\RankMath\\RankMath' ) ) {
			return self::INT_RANKMATH;
		}
		// AIOSEO — slug: all-in-one-seo-pack or aioseo-pro.
		if ( self::plugin_in( $active, array( 'all-in-one-seo-pack', 'aioseo-pro' ) )
			|| defined( 'AIOSEO_VERSION' )
			|| function_exists( 'aioseo' ) ) {
			return self::INT_AIOSEO;
		}
		return self::INT_CORE;
	}

	/**
	 * Plugin slugs that are active site-wide OR network-active.
	 * Works on CLI, REST and front-end without requiring plugin constants to be
	 * defined (which breaks when plugins lazy-load their bootstrap).
	 *
	 * @return string[] Folder slugs, e.g. ["woocommerce", "seo-by-rank-math"].
	 */
	private static function active_plugin_slugs() {
		$plugins = (array) get_option( 'active_plugins', array() );
		if ( is_multisite() ) {
			$network = (array) get_site_option( 'active_sitewide_plugins', array() );
			$plugins = array_merge( $plugins, array_keys( $network ) );
		}
		$slugs = array();
		foreach ( $plugins as $file ) {
			$slugs[] = strtok( (string) $file, '/' );
		}
		return array_filter( array_unique( $slugs ) );
	}

	private static function plugin_in( array $active, array $needles ) {
		foreach ( $needles as $slug ) {
			if ( in_array( $slug, $active, true ) ) {
				return true;
			}
		}
		return false;
	}

	public static function integration_label() {
		$map = array(
			self::INT_YOAST    => 'Yoast SEO',
			self::INT_RANKMATH => 'Rank Math',
			self::INT_AIOSEO   => 'All in One SEO',
			self::INT_CORE     => __( 'No SEO plugin detected (slug only)', 'catalogpilot-ai-studio-for-woocommerce' ),
		);
		$id = self::detect();
		return array( 'id' => $id, 'label' => $map[ $id ] );
	}

	public static function apply( $product_id, array $data ) {
		$product_id = absint( $product_id );
		if ( ! $product_id || ! get_post( $product_id ) ) {
			return new \WP_Error( 'cpais_invalid_product', __( 'Product not found.', 'catalogpilot-ai-studio-for-woocommerce' ) );
		}

		$applied = array();

		$slug = isset( $data['slug'] ) ? sanitize_title( $data['slug'] ) : '';
		if ( '' !== $slug ) {
			wp_update_post( array( 'ID' => $product_id, 'post_name' => $slug ) );
			$applied[] = 'slug';
		}

		switch ( self::detect() ) {
			case self::INT_YOAST:
				$applied = array_merge( $applied, self::apply_yoast( $product_id, $data ) );
				break;
			case self::INT_RANKMATH:
				$applied = array_merge( $applied, self::apply_rankmath( $product_id, $data ) );
				break;
			case self::INT_AIOSEO:
				$applied = array_merge( $applied, self::apply_aioseo( $product_id, $data ) );
				break;
			default:
				$applied = array_merge( $applied, self::apply_core( $product_id, $data ) );
				break;
		}

		return $applied;
	}

	private static function apply_yoast( $product_id, array $d ) {
		$map = array(
			'meta_title'       => '_yoast_wpseo_title',
			'meta_description' => '_yoast_wpseo_metadesc',
			'focus_keyword'    => '_yoast_wpseo_focuskw',
			'og_title'         => '_yoast_wpseo_opengraph-title',
			'og_description'   => '_yoast_wpseo_opengraph-description',
			'twitter_title'    => '_yoast_wpseo_twitter-title',
			'twitter_description' => '_yoast_wpseo_twitter-description',
		);
		return self::write_meta( $product_id, $d, $map );
	}

	private static function apply_rankmath( $product_id, array $d ) {
		$map = array(
			'meta_title'          => 'rank_math_title',
			'meta_description'    => 'rank_math_description',
			'focus_keyword'       => 'rank_math_focus_keyword',
			'og_title'            => 'rank_math_facebook_title',
			'og_description'      => 'rank_math_facebook_description',
			'twitter_title'       => 'rank_math_twitter_title',
			'twitter_description' => 'rank_math_twitter_description',
		);
		return self::write_meta( $product_id, $d, $map );
	}

	private static function apply_aioseo( $product_id, array $d ) {
		$applied = array();
		if ( ! class_exists( '\\AIOSEO\\Plugin\\Common\\Models\\Post' ) ) {
			return self::apply_core( $product_id, $d );
		}
		$post = \AIOSEO\Plugin\Common\Models\Post::getPost( $product_id );
		if ( isset( $d['meta_title'] ) ) {
			$post->title = sanitize_text_field( $d['meta_title'] );
			$applied[]   = 'meta_title';
		}
		if ( isset( $d['meta_description'] ) ) {
			$post->description = sanitize_text_field( $d['meta_description'] );
			$applied[]         = 'meta_description';
		}
		if ( isset( $d['focus_keyword'] ) ) {
			$post->keyphrases = wp_json_encode(
				array( 'focus' => array( 'keyphrase' => sanitize_text_field( $d['focus_keyword'] ) ) )
			);
			$applied[] = 'focus_keyword';
		}
		if ( isset( $d['og_title'] ) ) {
			$post->og_title = sanitize_text_field( $d['og_title'] );
			$applied[]      = 'og_title';
		}
		if ( isset( $d['og_description'] ) ) {
			$post->og_description = sanitize_text_field( $d['og_description'] );
			$applied[]            = 'og_description';
		}
		if ( isset( $d['twitter_title'] ) ) {
			$post->twitter_title = sanitize_text_field( $d['twitter_title'] );
			$applied[]           = 'twitter_title';
		}
		if ( isset( $d['twitter_description'] ) ) {
			$post->twitter_description = sanitize_text_field( $d['twitter_description'] );
			$applied[]                 = 'twitter_description';
		}
		$post->save();
		return $applied;
	}

	private static function apply_core( $product_id, array $d ) {
		$map = array(
			'meta_title'          => '_cpais_seo_title',
			'meta_description'    => '_cpais_seo_description',
			'focus_keyword'       => '_cpais_seo_focus_keyword',
			'og_title'            => '_cpais_seo_og_title',
			'og_description'      => '_cpais_seo_og_description',
			'twitter_title'       => '_cpais_seo_twitter_title',
			'twitter_description' => '_cpais_seo_twitter_description',
		);
		return self::write_meta( $product_id, $d, $map );
	}

	private static function write_meta( $product_id, array $d, array $map ) {
		$applied = array();
		foreach ( $map as $field => $meta_key ) {
			if ( ! isset( $d[ $field ] ) ) {
				continue;
			}
			$value = sanitize_text_field( $d[ $field ] );
			update_post_meta( $product_id, $meta_key, $value );
			$applied[] = $field;
		}
		return $applied;
	}
}
