<?php
/**
 * Schema Architecture V2 onboarding guidance (fresh vs upgrade).
 *
 * Keeps guidance short: explain automatic basics, ask for identity, and
 * route upgraded sites to the migration report instead of a schema wizard.
 *
 * @package SEOvaultSEO\Schema
 */

namespace SEOvaultSEO\Schema;

use SEOvaultSEO\Admin\SchemaMigrationAdmin;
use SEOvaultSEO\Compatibility\Detector;
use SEOvaultSEO\Core\Options;

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

/**
 * Copy and routing helpers for schema-aware first-run guidance.
 */
class SchemaOnboardingGuidance {

	/**
	 * User meta / option key for dismissed schema guidance notice.
	 */
	const DISMISS_OPTION = 'schema_onboarding_notice_dismissed';

	/**
	 * Admin-post action to dismiss the schema guidance notice.
	 */
	const ACTION_DISMISS = 'seovaultseo_dismiss_schema_onboarding';

	/**
	 * Nonce action for dismiss.
	 */
	const NONCE_DISMISS = 'seovaultseo_dismiss_schema_onboarding';

	/**
	 * Canonical fresh-install schema explanation.
	 *
	 * @return string
	 */
	public static function automatic_basics_copy() {
		return __(
			'SEOvault automatically adds basic schema for your site and pages. Add FAQ, HowTo, Recipe, Event, Course, Job, Review, or Software schema only when that content really exists.',
			'seovault-ai'
		);
	}

	/**
	 * Short note that extras are intentional (not a type checklist).
	 *
	 * @return string
	 */
	public static function additional_schema_copy() {
		return __(
			'Additional schema is added from individual posts, SEOvault blocks, or narrowly targeted templates — not by selecting every type for the whole site.',
			'seovault-ai'
		);
	}

	/**
	 * Whether this site should prefer migration review over fresh onboarding.
	 *
	 * @return bool
	 */
	public static function should_route_to_migration() {
		return SchemaMigration::should_show_notice() || SchemaMigration::is_restore_available();
	}

	/**
	 * Preferred post-activation destination URL.
	 *
	 * @param bool $onboarding_done Whether the general onboarding wizard is done/skipped.
	 * @return string
	 */
	public static function activation_redirect_url( $onboarding_done ) {
		if ( self::should_route_to_migration() ) {
			return SchemaMigrationAdmin::review_url();
		}

		if ( ! $onboarding_done ) {
			return admin_url( 'admin.php?page=seovault-ai-onboarding' );
		}

		if ( SchemaArchitectureSettings::is_onboarding_pending() ) {
			return admin_url( 'admin.php?page=seovault-ai-general&tab=vtab-schema' );
		}

		return admin_url( 'admin.php?page=seovault-ai' );
	}

	/**
	 * Whether the short schema guidance admin notice should render.
	 *
	 * @return bool
	 */
	public static function should_show_schema_notice() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return false;
		}

		if ( self::should_route_to_migration() ) {
			return false;
		}

		if ( ! SchemaArchitectureSettings::is_onboarding_pending() ) {
			return false;
		}

		if ( self::is_notice_dismissed() ) {
			return false;
		}

		return true;
	}

	/**
	 * Whether the schema guidance notice was dismissed.
	 *
	 * @return bool
	 */
	public static function is_notice_dismissed() {
		return 'yes' === (string) Options::get( self::DISMISS_OPTION, 'no' );
	}

	/**
	 * Dismiss the schema guidance notice.
	 *
	 * @return void
	 */
	public static function dismiss_notice() {
		Options::set( self::DISMISS_OPTION, 'yes', false );
	}

	/**
	 * Register admin-post dismiss handler.
	 *
	 * @return void
	 */
	public static function init() {
		add_action( 'admin_post_' . self::ACTION_DISMISS, array( __CLASS__, 'handle_dismiss' ) );
	}

	/**
	 * Handle dismiss request.
	 *
	 * @return void
	 */
	public static function handle_dismiss() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'seovault-ai' ) );
		}

		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), self::NONCE_DISMISS ) ) {
			wp_die( esc_html__( 'Security check failed.', 'seovault-ai' ) );
		}

		self::dismiss_notice();
		wp_safe_redirect( admin_url( 'admin.php?page=seovault-ai' ) );
		exit;
	}

	/**
	 * Clear dismissed flag (e.g. fresh install re-arm).
	 *
	 * @return void
	 */
	public static function reset_notice_dismissal() {
		Options::delete( self::DISMISS_OPTION );
	}

	/**
	 * Mark schema identity guidance complete.
	 *
	 * @return void
	 */
	public static function mark_identity_guidance_complete() {
		Options::set( SchemaArchitectureSettings::OPTION_ONBOARDING_PENDING, 'no', false );
	}

	/**
	 * Apply publisher identity from onboarding entity type.
	 *
	 * @param string $entity_type person|organization|both.
	 * @return bool
	 */
	public static function apply_publisher_identity( $entity_type ) {
		$entity_type = is_string( $entity_type ) ? strtolower( $entity_type ) : '';
		if ( 'person' === $entity_type ) {
			$ok = SchemaArchitectureSettings::set_publisher_identity( 'person' );
		} elseif ( 'both' === $entity_type ) {
			$ok = SchemaArchitectureSettings::set_publisher_identity( 'both' );
		} else {
			$ok = SchemaArchitectureSettings::set_publisher_identity( 'organization' );
		}

		if ( $ok ) {
			self::mark_identity_guidance_complete();
		}

		return $ok;
	}

	/**
	 * Competing SEO plugin note for activation/onboarding (escaped later).
	 *
	 * @return string Empty when none detected.
	 */
	public static function competitor_notice_copy() {
		$detector    = Detector::get_status();
		$competitors = array();
		if ( ! empty( $detector['competitors'] ) && is_array( $detector['competitors'] ) ) {
			foreach ( $detector['competitors'] as $competitor ) {
				if ( is_string( $competitor ) && '' !== $competitor ) {
					$competitors[] = $competitor;
				} elseif ( is_array( $competitor ) && ! empty( $competitor['name'] ) ) {
					$competitors[] = (string) $competitor['name'];
				}
			}
		}

		if ( empty( $competitors ) ) {
			return '';
		}

		return sprintf(
			/* translators: %s: competing plugin names. */
			__( 'Another SEO plugin was detected (%s). Keep it active until you import all needed SEO data. Step 5 imports global settings; post and term metadata can be imported from General > Tools. After importing, deactivate the other plugin to prevent duplicate output.', 'seovault-ai' ),
			implode( ', ', $competitors )
		);
	}

	/**
	 * Activation notice primary CTA label/url pair.
	 *
	 * @return array{url:string,label:string,secondary_url?:string,secondary_label?:string}
	 */
	public static function activation_cta() {
		if ( self::should_route_to_migration() ) {
			return array(
				'url'             => SchemaMigrationAdmin::review_url(),
				'label'           => __( 'Review schema migration', 'seovault-ai' ),
				'secondary_url'   => admin_url( 'admin.php?page=seovault-ai' ),
				'secondary_label' => __( 'Go to Dashboard', 'seovault-ai' ),
			);
		}

		$onboarding_done = (bool) get_option( 'seovaultseo_onboarding_completed', false )
			|| (bool) get_option( 'seovaultseo_onboarding_skipped', false );

		if ( ! $onboarding_done ) {
			return array(
				'url'             => admin_url( 'admin.php?page=seovault-ai-onboarding' ),
				'label'           => __( 'Start setup', 'seovault-ai' ),
				'secondary_url'   => admin_url( 'admin.php?page=seovault-ai' ),
				'secondary_label' => __( 'Go to Dashboard', 'seovault-ai' ),
			);
		}

		return array(
			'url'             => admin_url( 'admin.php?page=seovault-ai-general&tab=vtab-schema' ),
			'label'           => __( 'Review schema settings', 'seovault-ai' ),
			'secondary_url'   => admin_url( 'admin.php?page=seovault-ai' ),
			'secondary_label' => __( 'Go to Dashboard', 'seovault-ai' ),
		);
	}
}
