<?php
/**
 * SiteSEO Importer
 *
 * Imports SEO meta from SiteSEO into SEOvault.
 * SiteSEO uses the same meta key layout as SEOPress with a _siteseo_ prefix.
 *
 * @package SEOvaultSEO\Migration\Providers
 */

namespace SEOvaultSEO\Migration\Providers;

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

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

class SiteSEO extends BaseImporter {

	const PLUGIN_NAME = 'SiteSEO';
	const PLUGIN_FILE = 'siteseo/siteseo.php';
	const META_PREFIX = '_siteseo_';

	const EXCLUDED_KEYS = array(
		'_siteseo_analysis_data',
	);

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

	const GENERAL_MAPPING = array(
		'_siteseo_titles_title'     => 'seo_title',
		'_siteseo_titles_desc'      => 'seo_description',
		'_siteseo_robots_canonical' => 'canonical_url',
	);

	const SOCIAL_MAPPING = array(
		'_siteseo_social_fb_title' => 'og_title',
		'_siteseo_social_fb_desc'  => 'og_description',
	);

	const PLACEHOLDERS = array(
		'%%sitetitle%%'             => '%site_name%',
		'%%tagline%%'               => '%site_description%',
		'%%post_title%%'            => '%post_title%',
		'%%post_excerpt%%'          => '%post_excerpt%',
		'%%post_date%%'             => '%published_date%',
		'%%post_modified_date%%'    => '%modified_date%',
		'%%post_author%%'           => '%author_name%',
		'%%_category_title%%'       => '%term_name%',
		'%%_category_description%%' => '%term_description%',
		'%%tag_title%%'             => '%term_name%',
		'%%tag_description%%'       => '%term_description%',
		'%%term_title%%'            => '%term_name%',
		'%%term_description%%'      => '%term_description%',
		'%%archive_title%%'         => '%post_title%',
		'%%archive_date%%'          => '%current_date%',
		'%%currentdate%%'           => '%current_date%',
		'%%sep%%'                   => '-',
	);

	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( 'SITESEO_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 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'] );
		}

		$focus_keyword = ImporterUtils::get_primary_keyword( $this->get_source( '_siteseo_analysis_target_kw', '' ) );
		if ( '' !== $focus_keyword ) {
			$this->target_meta['focus_keyword'] = $focus_keyword;
			$imported                           = true;
		}

		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 ) {
		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 );
		$imported = $this->import_og_image() || $imported;

		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 );
		$imported = $this->import_og_image() || $imported;

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

	public function import_global_settings() {
		$titles = get_option( 'siteseo_titles_option_name', array() );
		$social = get_option( 'siteseo_social_option_name', array() );

		if ( ! is_array( $titles ) ) {
			$titles = array();
		}
		if ( ! is_array( $social ) ) {
			$social = array();
		}

		$imported = false;

		if ( ! empty( $titles['titles_home_site_title'] ) ) {
			\SEOvaultSEO\Core\Options::set_home_title(
				$this->replace_placeholders( (string) $titles['titles_home_site_title'] )
			);
			$imported = true;
		}
		if ( ! empty( $titles['titles_home_site_desc'] ) ) {
			\SEOvaultSEO\Core\Options::set_home_description(
				$this->replace_placeholders( (string) $titles['titles_home_site_desc'] )
			);
			$imported = true;
		}

		if ( ! empty( $titles['titles_single_titles'] ) && is_array( $titles['titles_single_titles'] ) ) {
			foreach ( $titles['titles_single_titles'] as $config ) {
				if ( ! is_array( $config ) || empty( $config['title'] ) ) {
					continue;
				}
				\SEOvaultSEO\Core\Options::set_title_template(
					$this->replace_placeholders( (string) $config['title'] )
				);
				$imported = true;
				break;
			}
		}

		if ( ! empty( $social['social_accounts_facebook'] ) ) {
			\SEOvaultSEO\Core\Options::set( 'facebook_page_url', $social['social_accounts_facebook'] );
			$imported = true;
		}
		if ( ! empty( $social['social_accounts_twitter'] ) ) {
			\SEOvaultSEO\Core\Options::set(
				'twitter_username',
				ltrim( (string) $social['social_accounts_twitter'], '@' )
			);
			$imported = true;
		}

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

	private function import_robots_settings( $object_id, $object_kind ) {
		$imported = false;

		if ( $this->is_yes_value( $this->get_source( '_siteseo_robots_index', '' ) ) ) {
			$this->target_meta['robots_noindex'] = true;
			$imported                            = true;
		}
		if ( $this->is_yes_value( $this->get_source( '_siteseo_robots_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
		);
	}

	private function import_og_image() {
		$url = $this->get_source( '_siteseo_social_fb_img', '' );

		if ( '' === $url ) {
			$attachment_id = (int) $this->get_source( '_siteseo_social_fb_img_attachment_id', 0 );
			if ( $attachment_id > 0 ) {
				$resolved = wp_get_attachment_url( $attachment_id );
				$url      = $resolved ? $resolved : '';
			}
		}

		if ( '' === $url ) {
			return false;
		}

		$this->target_meta['og_image'] = $url;

		return true;
	}

	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 );
	}

	private function replace_placeholders( $value ) {
		if ( ! is_string( $value ) ) {
			return $value;
		}

		$placeholders            = self::PLACEHOLDERS;
		$placeholders['%%sep%%'] = $this->get_separator();

		return str_replace( array_keys( $placeholders ), array_values( $placeholders ), $value );
	}

	private function get_separator() {
		$titles = get_option( 'siteseo_titles_option_name', array() );

		if ( is_array( $titles ) && ! empty( $titles['separator'] ) ) {
			return (string) $titles['separator'];
		}

		return '-';
	}
}
