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

namespace SEOvaultSEO\Migration\Providers;

use SEOvaultSEO\Migration\BaseImporter;
use SEOvaultSEO\Migration\ImporterUtils;

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

class SureRank extends BaseImporter {

	const PLUGIN_NAME = 'SureRank';
	const PLUGIN_FILE = 'surerank/surerank.php';
	const META_PREFIX = 'surerank_settings';

	const EXCLUDED_KEYS = array(
		'surerank_settings_schemas',
	);

	const SETTINGS_GROUPS = array(
		'general',
		'social',
		'schemas',
	);

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

	const GENERAL_MAPPING = array(
		'page_title'       => 'seo_title',
		'page_description' => 'seo_description',
		'canonical_url'    => 'canonical_url',
		'focus_keyword'    => 'focus_keyword',
	);

	const SOCIAL_MAPPING = array(
		'facebook_title'       => 'og_title',
		'facebook_description' => 'og_description',
		'facebook_image_url'   => 'og_image',
	);

	const PLACEHOLDERS = array(
		'%site_name%'        => '%site_name%',
		'%tagline%'          => '%site_description%',
		'%title%'            => '%post_title%',
		'%content%'          => '%post_excerpt%',
		'%excerpt%'          => '%post_excerpt%',
		'%term_title%'       => '%term_name%',
		'%term_description%' => '%term_description%',
		'%author_name%'      => '%author_name%',
		'%published%'        => '%published_date%',
		'%modified%'         => '%modified_date%',
		'%permalink%'        => '%post_url%',
		'%page%'             => '%page%',
		'%sep%'              => '-',
		'%separator%'        => '-',
		'%site_url%'         => '%site_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 defined( 'SURERANK_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 = '' ) {
		$raw = $is_taxonomy ? get_term_meta( $id ) : get_post_meta( $id );

		return $this->normalize_surerank_meta( is_array( $raw ) ? $raw : array() );
	}

	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'] );
		}
		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, $term_id, 'term', 'general' ),
			$imported
		);
	}

	public function import_post_meta_robots( $post_id ) {
		return $this->import_robots_settings( $post_id, 'post' );
	}

	public function import_term_meta_robots( $term_id ) {
		return $this->import_robots_settings( $term_id, 'term' );
	}

	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( 'surerank_settings', array() );
		if ( ! is_array( $settings ) ) {
			$settings = array();
		}

		$imported = false;

		if ( ! empty( $settings['home_page_title'] ) ) {
			\SEOvaultSEO\Core\Options::set_home_title( $this->replace_placeholders( $settings['home_page_title'] ) );
			$imported = true;
		}
		if ( ! empty( $settings['home_page_description'] ) ) {
			\SEOvaultSEO\Core\Options::set_home_description( $this->replace_placeholders( $settings['home_page_description'] ) );
			$imported = true;
		}
		if ( ! empty( $settings['page_title'] ) ) {
			\SEOvaultSEO\Core\Options::set_title_template( $this->replace_placeholders( $settings['page_title'] ) );
			$imported = true;
		}

		$facebook_url = $settings['facebook_page_url'] ?? '';
		if ( empty( $facebook_url ) && ! empty( $settings['social_profiles']['facebook'] ) ) {
			$facebook_url = $settings['social_profiles']['facebook'];
		}
		if ( ! empty( $facebook_url ) ) {
			\SEOvaultSEO\Core\Options::set( 'facebook_page_url', $facebook_url );
			$imported = true;
		}

		$twitter_username = $settings['twitter_profile_username'] ?? '';
		if ( empty( $twitter_username ) && ! empty( $settings['social_profiles']['twitter'] ) ) {
			$twitter_username = $settings['social_profiles']['twitter'];
		}
		if ( ! empty( $twitter_username ) ) {
			\SEOvaultSEO\Core\Options::set( 'twitter_username', ltrim( $twitter_username, '@' ) );
			$imported = true;
		}

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

	/**
	 * Flatten SureRank post/term meta into logical field keys.
	 *
	 * SureRank stores values as surerank_settings_{field} and/or grouped arrays
	 * under surerank_settings_general and surerank_settings_social. Older sites
	 * may still have a single surerank_settings blob.
	 *
	 * @param array $raw_meta Raw meta from get_post_meta() or get_term_meta().
	 * @return array
	 */
	private function normalize_surerank_meta( array $raw_meta ) {
		$flat = array();

		foreach ( $raw_meta as $key => $values ) {
			if ( ! is_string( $key ) ) {
				continue;
			}

			if ( 'surerank_settings' !== $key && ! str_starts_with( $key, 'surerank_settings_' ) ) {
				continue;
			}

			if ( in_array( $key, self::EXCLUDED_KEYS, true ) ) {
				continue;
			}

			$value = is_array( $values ) ? reset( $values ) : $values;

			if ( 'surerank_settings' === $key ) {
				if ( is_array( $value ) ) {
					$flat = array_merge( $flat, $this->flatten_settings_value( $value ) );
				}
				continue;
			}

			$sub_key = substr( $key, strlen( 'surerank_settings_' ) );
			if ( is_array( $value ) && in_array( $sub_key, self::SETTINGS_GROUPS, true ) ) {
				$flat = array_merge( $flat, $value );
				continue;
			}

			if ( is_array( $value ) ) {
				$flat = array_merge( $flat, $this->flatten_settings_value( $value ) );
				continue;
			}

			$flat[ $sub_key ] = $value;
		}

		return $flat;
	}

	/**
	 * Recursively flatten grouped SureRank settings arrays.
	 *
	 * @param array $value Settings array.
	 * @return array
	 */
	private function flatten_settings_value( array $value ) {
		$flat = array();

		foreach ( $value as $key => $item ) {
			if ( is_array( $item ) && in_array( $key, self::SETTINGS_GROUPS, true ) ) {
				$flat = array_merge( $flat, $item );
				continue;
			}

			if ( is_array( $item ) && 'schemas' !== $key ) {
				$flat = array_merge( $flat, $this->flatten_settings_value( $item ) );
				continue;
			}

			$flat[ $key ] = $item;
		}

		return $flat;
	}

	/**
	 * Import noindex / nofollow flags from SureRank yes/no fields.
	 *
	 * @param int    $object_id   Post or term ID.
	 * @param string $object_kind 'post' or 'term'.
	 * @return array
	 */
	private function import_robots_settings( $object_id, $object_kind ) {
		$imported = false;

		if ( $this->is_yes_value( $this->get_source( 'post_no_index', '' ) ) ) {
			$this->target_meta['robots_noindex'] = true;
			$imported                            = true;
		}
		if ( $this->is_yes_value( $this->get_source( 'post_no_follow', '' ) ) ) {
			$this->target_meta['robots_nofollow'] = true;
			$imported                             = true;
		}

		return ImporterUtils::build_response(
			ImporterUtils::import_status_message( $imported, $object_id, $object_kind, 'meta_robots' ),
			$imported
		);
	}

	/**
	 * Check if a SureRank boolean field is enabled.
	 *
	 * @param mixed $value Raw value.
	 * @return bool
	 */
	private function is_yes_value( $value ) {
		if ( is_bool( $value ) ) {
			return $value;
		}

		$value = strtolower( trim( (string) $value ) );

		return in_array( $value, array( 'yes', '1', 'true', 'on' ), true );
	}

	/**
	 * Replace SureRank title/description 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 );
	}
}
