<?php

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

require_once AIEO_DIR . 'includes/seo/class-aieo-seo-importer.php';

class AIEO_DMM_SEO_Import extends AIEO_DMM_Module_Base {

	const LAST_OPTION = 'aieo_seo_import_last';

	public function get_id()       { return 'seo_import'; }
	public function get_label()    { return __( 'Migrate from AIOSEO', 'ai-eshop-optimizer' ); }
	public function get_priority() { return 10; }
	public function get_group()    { return 'seo'; }
	public function get_section()  { return 'tools'; }

	public function register_hooks() {
		add_action( 'wp_ajax_aieo_seo_import_run', array( $this, 'ajax_import_run' ) );
		add_action( 'wp_ajax_aieo_seo_verify_parity', array( $this, 'ajax_verify_parity' ) );
	}

	
	public function ajax_verify_parity() {
		AIEO_DMM::verify_ajax_request();
		if ( ! class_exists( 'AIEO_SEO_Verify' ) ) {
			wp_send_json_error( array( 'message' => __( 'Verify engine unavailable.', 'ai-eshop-optimizer' ) ) );
		}
		wp_send_json_success( AIEO_SEO_Verify::run_sample() );
	}

	public function render_subtab() {
		$this->render_template(
			'seo/import.php',
			array(
				'available' => class_exists( 'AIEO_SEO_Importer' ) && AIEO_SEO_Importer::available(),
				'counts'    => class_exists( 'AIEO_SEO_Importer' ) ? AIEO_SEO_Importer::counts() : array( 'posts' => 0, 'terms' => 0 ),
				'report'    => class_exists( 'AIEO_SEO_Importer' ) ? AIEO_SEO_Importer::mapping_report() : array(),
				'last'      => (array) get_option( self::LAST_OPTION, array() ),
				'nonce'     => wp_create_nonce( AIEO_DMM::NONCE_ACTION ),
				'ajax'      => admin_url( 'admin-ajax.php' ),
			)
		);
	}

	
	public function ajax_import_run() {
		AIEO_DMM::verify_ajax_request();
		
		if ( ! current_user_can( 'manage_woocommerce' ) && ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions for a store-wide import.', 'ai-eshop-optimizer' ) ) );
		}
		if ( ! class_exists( 'AIEO_SEO_Importer' ) ) {
			wp_send_json_error( array( 'message' => __( 'Importer unavailable.', 'ai-eshop-optimizer' ) ) );
		}

		$phase = isset( $_POST['phase'] ) ? sanitize_key( wp_unslash( $_POST['phase'] ) ) : 'posts';
		$after = isset( $_POST['after_id'] ) ? (int) $_POST['after_id'] : 0;

		
		
		if ( 'options' === $phase ) {
			$opt                       = AIEO_SEO_Importer::import_options();
			$last                      = (array) get_option( self::LAST_OPTION, array() );
			$last['settings_imported'] = ! empty( $opt['imported'] );
			$last['finished_at']       = time();
			update_option( self::LAST_OPTION, $last, false );
			wp_send_json_success( array( 'phase' => 'options', 'done' => true, 'imported' => 0, 'stripped' => 0, 'last_id' => 0, 'options' => $opt ) );
		}

		if ( 'terms' === $phase ) {
			$res = AIEO_SEO_Importer::import_terms_chunk( $after, 200 );
		} else {
			$phase = 'posts';
			if ( 0 === $after ) {
				delete_option( self::LAST_OPTION ); 
			}
			$res = AIEO_SEO_Importer::import_posts_chunk( $after, 200 );
		}
		$res['phase'] = $phase;

		
		$last                      = (array) get_option( self::LAST_OPTION, array() );
		$last[ $phase . '_imported' ] = (int) ( $last[ $phase . '_imported' ] ?? 0 ) + (int) $res['imported'];
		$last['stripped']          = (int) ( $last['stripped'] ?? 0 ) + (int) $res['stripped'];
		$last['skipped']           = (int) ( $last['skipped'] ?? 0 ) + (int) $res['skipped'];
		$last['finished_at']       = time();
		update_option( self::LAST_OPTION, $last, false );

		wp_send_json_success( $res );
	}
}
