<?php
/**
 * Rank Math Importer
 *
 * Imports SEO meta from Rank Math 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 RankMath extends BaseImporter {

	const PLUGIN_NAME = 'Rank Math';
	const PLUGIN_FILE = 'seo-by-rank-math/rank-math.php';
	const META_PREFIX = 'rank_math_';

	const EXCLUDED_KEYS = array(
		'rank_math_seo_score',
		'rank_math_seo_score_history',
		'rank_math_internal_links',
		'rank_math_internal_links_processed',
		'rank_math_external_links',
		'rank_math_pillar_content',
		'rank_math_analytic_object_id',
	);

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

	const GENERAL_MAPPING = array(
		'rank_math_title'         => 'seo_title',
		'rank_math_description'   => 'seo_description',
		'rank_math_canonical_url' => 'canonical_url',
		'rank_math_focus_keyword' => 'focus_keyword',
	);

	const SOCIAL_MAPPING = array(
		'rank_math_facebook_title'       => 'og_title',
		'rank_math_facebook_description' => 'og_description',
		'rank_math_facebook_image'       => 'og_image',
		'rank_math_og_content_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%',
		'%%modified%%'         => '%modified_date%',
		'%%date%%'             => '%published_date%',
		'%%title%%'            => '%post_title%',
		'%%excerpt%%'          => '%post_excerpt%',
		'%%name%%'             => '%author_name%',
		'%%term%%'             => '%term_name%',
		'%%term_description%%' => '%term_description%',
		'%%post_url%%'         => '%post_url%',
	);

	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( 'seo-by-rank-math', defined( 'RANK_MATH_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 ) {
			return get_term_meta( $id );
		}
		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'] );
		}
		if ( $imported && isset( $this->target_meta['focus_keyword'] ) ) {
			$this->target_meta['focus_keyword'] = ImporterUtils::get_primary_keyword( $this->target_meta['focus_keyword'] );
		}

		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::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 ) {
		$robots   = $this->get_source( 'rank_math_robots', '' );
		$imported = false;

		if ( is_array( $robots ) ) {
			$robots = implode( ',', $robots );
		}

		if ( false !== strpos( (string) $robots, 'noindex' ) ) {
			$this->target_meta['robots_noindex'] = true;
			$imported                            = true;
		}
		if ( false !== strpos( (string) $robots, '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 ) {
		return $this->import_post_meta_robots( $term_id );
	}

	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::SOCIAL_MAPPING );

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

	public function import_global_settings() {
		$settings = get_option( 'rank-math-options-titles', array() );
		$imported = false;

		if ( is_array( $settings ) ) {
			if ( isset( $settings['homepage_title'] ) ) {
				\SEOvaultSEO\Core\Options::set_home_title( $this->replace_placeholders( $settings['homepage_title'] ) );
				$imported = true;
			}
			if ( isset( $settings['homepage_description'] ) ) {
				\SEOvaultSEO\Core\Options::set_home_description( $this->replace_placeholders( $settings['homepage_description'] ) );
				$imported = true;
			}
		}

		$social = get_option( 'rank-math-options-general', array() );
		if ( is_array( $social ) ) {
			if ( isset( $social['social_facebook_author'] ) ) {
				\SEOvaultSEO\Core\Options::set( 'facebook_page_url', $social['social_facebook_author'] );
				$imported = true;
			}
			if ( isset( $social['social_twitter_author'] ) ) {
				\SEOvaultSEO\Core\Options::set( 'twitter_username', ltrim( $social['social_twitter_author'], '@' ) );
				$imported = true;
			}
		}

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

	private function replace_placeholders( $value ) {
		if ( ! is_string( $value ) ) {
			return $value;
		}
		return strtr( $value, self::PLACEHOLDERS );
	}
}
