<?php
/**
 * Importer - Meta Importer
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\Importer;

use SEOvaultSEO\Core\PostMeta;

/**
 * Imports SEO meta from competitor plugins
 */
class Importer {

	/**
	 * Batch size for imports
	 */
	const BATCH_SIZE = 50;

	/**
	 * Import meta from a specific post
	 *
	 * @param int    $post_id Post ID
	 * @param string $provider Provider name
	 * @param bool   $overwrite Whether to overwrite existing SEOvault meta
	 * @return array Import result
	 */
	public static function import_post( $post_id, $provider = null, $overwrite = false ) {
		if ( null === $provider ) {
			$provider = \SEOvaultSEO\Compatibility\Detector::detect_active_provider();
		}

		if ( \SEOvaultSEO\Compatibility\Detector::PROVIDER_NONE === $provider ) {
			return array(
				'success' => false,
				'message' => 'No other SEO plugin detected',
			);
		}

		$meta = Reader::read_from_active_plugin( $post_id );

		if ( empty( $meta ) ) {
			return array(
				'success' => false,
				'message' => 'No meta found for this post',
			);
		}

		$imported = array();
		$skipped  = array();

		// Import SEO title
		if ( ! empty( $meta['seo_title'] ) ) {
			$existing = PostMeta::get_seo_title( $post_id );
			if ( $overwrite || empty( $existing ) ) {
				PostMeta::set_seo_title( $post_id, $meta['seo_title'] );
				$imported[] = 'seo_title';
			} else {
				$skipped[] = 'seo_title';
			}
		}

		// Import SEO description
		if ( ! empty( $meta['seo_description'] ) ) {
			$existing = PostMeta::get_seo_description( $post_id );
			if ( $overwrite || empty( $existing ) ) {
				PostMeta::set_seo_description( $post_id, $meta['seo_description'] );
				$imported[] = 'seo_description';
			} else {
				$skipped[] = 'seo_description';
			}
		}

		// Import focus keyword
		if ( ! empty( $meta['focus_keyword'] ) ) {
			$existing = PostMeta::get_focus_keyword( $post_id );
			if ( $overwrite || empty( $existing ) ) {
				PostMeta::set_focus_keyword( $post_id, $meta['focus_keyword'] );
				$imported[] = 'focus_keyword';
			} else {
				$skipped[] = 'focus_keyword';
			}
		}

		// Import canonical URL
		if ( ! empty( $meta['canonical_url'] ) ) {
			$existing = PostMeta::get_canonical_url( $post_id );
			if ( $overwrite || empty( $existing ) ) {
				PostMeta::set_canonical_url( $post_id, $meta['canonical_url'] );
				$imported[] = 'canonical_url';
			} else {
				$skipped[] = 'canonical_url';
			}
		}

		// Import noindex — only persist an explicit noindex. Writing false for
		// default/blank source robots would create a per-post override and
		// defeat post-type noindex settings.
		if ( ! empty( $meta['noindex'] ) ) {
			$existing = PostMeta::is_noindex( $post_id );
			if ( $overwrite || ! $existing ) {
				PostMeta::set_noindex( $post_id, true );
				$imported[] = 'noindex';
			} else {
				$skipped[] = 'noindex';
			}
		}

		// Import nofollow — same rule: only explicit nofollow.
		if ( ! empty( $meta['nofollow'] ) ) {
			$existing = PostMeta::is_nofollow( $post_id );
			if ( $overwrite || ! $existing ) {
				PostMeta::set_nofollow( $post_id, true );
				$imported[] = 'nofollow';
			} else {
				$skipped[] = 'nofollow';
			}
		}

		return array(
			'success'  => true,
			'imported' => $imported,
			'skipped'  => $skipped,
		);
	}

	/**
	 * Import meta from all posts
	 *
	 * @param string $provider Provider name
	 * @param bool   $overwrite Whether to overwrite existing SEOvault meta
	 * @param int    $offset Offset for batch processing
	 * @param int    $limit Limit for batch processing
	 * @return array Import result
	 */
	public static function import_all( $provider = null, $overwrite = false, $offset = 0, $limit = self::BATCH_SIZE ) {
		if ( null === $provider ) {
			$provider = \SEOvaultSEO\Compatibility\Detector::detect_active_provider();
		}

		if ( \SEOvaultSEO\Compatibility\Detector::PROVIDER_NONE === $provider ) {
			return array(
				'success'  => false,
				'message'  => 'No other SEO plugin detected',
				'total'    => 0,
				'imported' => 0,
				'skipped'  => 0,
			);
		}

		$meta_key = Reader::get_meta_key_for_provider( $provider );
		if ( empty( $meta_key ) ) {
			return array(
				'success'  => false,
				'message'  => 'Could not determine meta key for provider',
				'total'    => 0,
				'imported' => 0,
				'skipped'  => 0,
			);
		}

		$args = array(
			'post_type'      => array( 'post', 'page' ),
			'post_status'    => 'any',
			'posts_per_page' => $limit,
			'offset'         => $offset,
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
			'meta_query'     => array(
				array(
					'key'     => $meta_key,
					'compare' => 'EXISTS',
				),
			),
		);

		$posts = get_posts( $args );
		$total = count( $posts );

		if ( 0 === $total ) {
			return array(
				'success'  => true,
				'message'  => 'No posts found with SEO meta from other plugins',
				'total'    => 0,
				'imported' => 0,
				'skipped'  => 0,
				'offset'   => $offset,
				'has_more' => false,
			);
		}

		$imported_count = 0;
		$skipped_count  = 0;
		$results        = array();

		foreach ( $posts as $post ) {
			$result = self::import_post( $post->ID, $provider, $overwrite );
			if ( $result['success'] ) {
				$imported_count += count( $result['imported'] );
				$skipped_count  += count( $result['skipped'] );
				$results[]       = array(
					'post_id'    => $post->ID,
					'post_title' => $post->post_title,
					'imported'   => $result['imported'],
					'skipped'    => $result['skipped'],
				);
			}
		}

		$has_more = $total === $limit;

		return array(
			'success'  => true,
			'message'  => sprintf( 'Processed %d posts', $total ),
			'total'    => $total,
			'imported' => $imported_count,
			'skipped'  => $skipped_count,
			'results'  => $results,
			'offset'   => $offset + $limit,
			'has_more' => $has_more,
		);
	}

	/**
	 * Get import summary
	 *
	 * @param string $provider Provider name
	 * @return array
	 */
	public static function get_summary( $provider = null ) {
		if ( null === $provider ) {
			$provider = \SEOvaultSEO\Compatibility\Detector::detect_active_provider();
		}

		$count = Reader::count_posts_with_meta( $provider );

		return array(
			'provider'          => $provider,
			'count'             => $count,
			'batch_size'        => self::BATCH_SIZE,
			'estimated_batches' => ceil( $count / self::BATCH_SIZE ),
		);
	}
}
