<?php
/**
 * Yoast SEO Importer
 *
 * Imports SEO meta from Yoast SEO into SEOvault.
 *
 * @package SEOvaultSEO\Migration\Providers
 */

namespace SEOvaultSEO\Migration\Providers;

use SEOvaultSEO\Compatibility\Detector;
use SEOvaultSEO\Migration\BaseImporter;
use SEOvaultSEO\Migration\ImporterUtils;

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

class Yoast extends BaseImporter {

	const PLUGIN_NAME = 'Yoast SEO';
	const PLUGIN_FILE = 'wordpress-seo/wp-seo.php';
	const META_PREFIX = '_yoast_wpseo_';

	const EXCLUDED_KEYS = array(
		'_yoast_wpseo_primary_category',
		'_yoast_wpseo_content_score',
		'_yoast_wpseo_estimated-reading-time-minutes',
		'_yoast_wpseo_keywordsynonyms',
		'_yoast_wpseo_focuskeywords',
	);

	const NOT_ALLOWED_TYPES = array(
		'elementor_library',
		'product_shipping_class',
	);

	const GENERAL_MAPPING = array(
		'_yoast_wpseo_title'     => 'seo_title',
		'_yoast_wpseo_metadesc'  => 'seo_description',
		'_yoast_wpseo_canonical' => 'canonical_url',
		'_yoast_wpseo_focuskw'   => 'focus_keyword',
	);

	const SOCIAL_MAPPING = array(
		'_yoast_wpseo_opengraph-title'       => 'og_title',
		'_yoast_wpseo_opengraph-description' => 'og_description',
		'_yoast_wpseo_opengraph-image'       => 'og_image',
	);

	const TERM_GENERAL_MAPPING = array(
		'wpseo_title'     => 'seo_title',
		'wpseo_metadesc'  => 'seo_description',
		'wpseo_canonical' => 'canonical_url',
		'wpseo_focuskw'   => 'focus_keyword',
	);

	const TERM_SOCIAL_MAPPING = array(
		'wpseo_opengraph-title'       => 'og_title',
		'wpseo_opengraph-description' => 'og_description',
		'wpseo_opengraph-image'       => 'og_image',
	);

	const PLACEHOLDERS = array(
		'%%sitename%%'         => '%site_name%',
		'%%sitedesc%%'         => '%site_description%',
		'%%sep%%'              => '-',
		'%%page%%'             => '%page%',
		'%%currenttime%%'      => '%current_time%',
		'%%currentyear%%'      => '%current_year%',
		'%%currentmonth%%'     => '%current_month%',
		'%%currentday%%'       => '%current_day%',
		'%%currentdate%%'      => '%current_date%',
		'%%modified%%'         => '%modified_date%',
		'%%date%%'             => '%published_date%',
		'%%title%%'            => '%post_title%',
		'%%excerpt%%'          => '%post_excerpt%',
		'%%name%%'             => '%author_name%',
		'%%term_title%%'       => '%term_name%',
		'%%term_description%%' => '%term_description%',
		'%%post_url%%'         => '%post_url%',
		'%%org_name%%'         => '%site_name%',
		'%%org_url%%'          => '%site_url%',
		'%%org_logo%%'         => '%site_logo%',
	);

	public function get_plugin_name() {
		return self::PLUGIN_NAME;
	}

	public function get_plugin_file() {
		return self::PLUGIN_FILE;
	}

	public function is_plugin_active() {
		return Detector::is_migration_plugin_active( 'wordpress-seo', defined( 'WPSEO_VERSION' ) );
	}

	protected function get_meta_key_prefix() {
		return self::META_PREFIX;
	}

	protected function get_excluded_meta_keys() {
		return self::EXCLUDED_KEYS;
	}

	protected function get_not_allowed_types() {
		return self::NOT_ALLOWED_TYPES;
	}

	protected function get_source_meta_data( $id, $is_taxonomy, $type = '' ) {
		if ( $is_taxonomy ) {
			$term_meta = get_option( 'wpseo_taxonomy_meta', array() );
			$data      = $term_meta[ $type ][ $id ] ?? array();
			return is_array( $data ) ? $data : array();
		}
		return get_post_meta( $id );
	}

	public function import_post_general_settings( $post_id ) {
		$imported = $this->process_meta_mapping( self::GENERAL_MAPPING );

		if ( $imported && isset( $this->target_meta['seo_title'] ) ) {
			$this->target_meta['seo_title'] = $this->replace_placeholders( $this->target_meta['seo_title'] );
		}
		if ( $imported && isset( $this->target_meta['seo_description'] ) ) {
			$this->target_meta['seo_description'] = $this->replace_placeholders( $this->target_meta['seo_description'] );
		}

		return ImporterUtils::build_response(
			ImporterUtils::import_status_message( $imported, $post_id, 'post', 'general' ),
			$imported
		);
	}

	public function import_term_general_settings( $term_id ) {
		$imported = $this->process_meta_mapping( self::TERM_GENERAL_MAPPING );

		if ( $imported && isset( $this->target_meta['seo_title'] ) ) {
			$this->target_meta['seo_title'] = $this->replace_placeholders( $this->target_meta['seo_title'] );
		}
		if ( $imported && isset( $this->target_meta['seo_description'] ) ) {
			$this->target_meta['seo_description'] = $this->replace_placeholders( $this->target_meta['seo_description'] );
		}

		return ImporterUtils::build_response(
			ImporterUtils::import_status_message( $imported, $term_id, 'term', 'general' ),
			$imported
		);
	}

	public function import_post_meta_robots( $post_id ) {
		// Yoast: ''/'0' = inherit defaults, '1' = noindex, '2' = force index.
		// Only write an explicit override. Never store "index" for blank/default
		// values — that defeats SEOvault post-type noindex.
		$noindex  = $this->get_source( '_yoast_wpseo_meta-robots-noindex', '0' );
		$nofollow = $this->get_source( '_yoast_wpseo_meta-robots-nofollow', '0' );

		$imported = false;

		if ( '1' === $noindex || 'noindex' === $noindex ) {
			$this->target_meta['robots_noindex'] = true;
			$imported                            = true;
		} elseif ( '2' === $noindex || 'index' === $noindex ) {
			$this->target_meta['robots_noindex'] = false;
			$imported                            = true;
		}

		if ( '1' === $nofollow || 'nofollow' === $nofollow ) {
			$this->target_meta['robots_nofollow'] = true;
			$imported                             = true;
		}

		return ImporterUtils::build_response(
			ImporterUtils::import_status_message( $imported, $post_id, 'post', 'meta_robots' ),
			$imported
		);
	}

	public function import_term_meta_robots( $term_id ) {
		$noindex = $this->get_source( 'wpseo_noindex', '' );

		$imported = false;
		if ( 'noindex' === $noindex || '1' === $noindex ) {
			$this->target_meta['robots_noindex'] = true;
			$imported                            = true;
		}

		return ImporterUtils::build_response(
			ImporterUtils::import_status_message( $imported, $term_id, 'term', 'meta_robots' ),
			$imported
		);
	}

	public function import_post_social( $post_id ) {
		$imported = $this->process_meta_mapping( self::SOCIAL_MAPPING );

		return ImporterUtils::build_response(
			ImporterUtils::import_status_message( $imported, $post_id, 'post', 'social' ),
			$imported
		);
	}

	public function import_term_social( $term_id ) {
		$imported = $this->process_meta_mapping( self::TERM_SOCIAL_MAPPING );

		return ImporterUtils::build_response(
			ImporterUtils::import_status_message( $imported, $term_id, 'term', 'social' ),
			$imported
		);
	}

	public function import_global_settings() {
		$titles   = get_option( 'wpseo_titles', array() );
		$social   = get_option( 'wpseo_social', array() );
		$imported = false;

		if ( is_array( $titles ) ) {
			if ( isset( $titles['title-home-wpseo'] ) ) {
				\SEOvaultSEO\Core\Options::set_home_title( $this->replace_placeholders( $titles['title-home-wpseo'] ) );
				$imported = true;
			}
			if ( isset( $titles['metadesc-home-wpseo'] ) ) {
				\SEOvaultSEO\Core\Options::set_home_description( $this->replace_placeholders( $titles['metadesc-home-wpseo'] ) );
				$imported = true;
			}
		}

		if ( is_array( $social ) ) {
			if ( isset( $social['facebook_site'] ) ) {
				\SEOvaultSEO\Core\Options::set( 'facebook_page_url', $social['facebook_site'] );
				$imported = true;
			}
			if ( isset( $social['twitter_site'] ) ) {
				\SEOvaultSEO\Core\Options::set( 'twitter_username', ltrim( $social['twitter_site'], '@' ) );
				$imported = true;
			}
		}

		return ImporterUtils::build_response(
			$imported
				? __( 'Global settings imported from Yoast SEO.', 'seovault-ai' )
				: __( 'No global settings found to import from Yoast SEO.', 'seovault-ai' ),
			$imported
		);
	}

	/**
	 * Replace Yoast placeholders with SEOvault equivalents.
	 *
	 * @param string $value Value containing placeholders.
	 * @return string
	 */
	private function replace_placeholders( $value ) {
		if ( ! is_string( $value ) ) {
			return $value;
		}
		return strtr( $value, self::PLACEHOLDERS );
	}
}
