<?php
/**
 * This file is part of the Wisewand WordPress plugin.
 *
 * Migration Validator - Validates project brief configuration before migration.
 *
 * @package Wisewand
 * @since 2.8.0
 * @license GPL-2.0-or-later
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */
namespace Wisewand\Migration;

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Wisewand\Utils\Options;
use Wisewand\Logging\Logger;

// phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log -- error_log() is only used within WP_DEBUG conditionals for debugging

/**
 * Migration Validator
 *
 * Validates system readiness for brief config migration.
 * Auto-completes migration when API key and project ID are configured.
 *
 * @package Wisewand
 * @since 2.8.0
 */
class Migration_Validator {

	/**
	 * Legacy options to be deleted after migration.
	 *
	 * Shared with Migration_Executor via this constant.
	 *
	 * @since 2.8.6
	 * @var array
	 */
	const LEGACY_OPTIONS = array(
		'wisewand_default_use_toc',
		'wisewand_default_use_faq',
		'wisewand_default_use_bulletlist',
		'wisewand_default_use_infotable',
		'wisewand_default_use_boldkeywords',
		'wisewand_default_use_externalsources',
		'wisewand_default_use_summary',
		'wisewand_default_use_blockquotes',
		'wisewand_default_use_image',
		'wisewand_default_use_inlineimages',
		'wisewand_default_inline_images_count',
		'wisewand_default_inline_images_ratio',
		'wisewand_default_inline_images_use_palette',
		'wisewand_default_inline_images_primary_color',
		'wisewand_default_inline_images_secondary_color',
		'wisewand_default_use_social',
		'wisewand_default_use_audio',
		'wisewand_default_image_ratio',
		'wisewand_default_image_use_palette',
		'wisewand_default_image_primary_color',
		'wisewand_default_image_secondary_color',
		'wisewand_default_audio_voice_fr',
		'wisewand_default_audio_voice_en',
		'wisewand_default_use_internallinks',
		'wisewand_default_use_indexed_pages_internal_links',
		'wisewand_default_internal_links_wp_status',
	);

	/**
	 * Options manager
	 *
	 * @since 2.8.0
	 * @var Options
	 */
	private $options;

	/**
	 * Logger instance
	 *
	 * @since 2.8.0
	 * @var Logger
	 */
	private $logger;

	/**
	 * Constructor
	 *
	 * @since 2.8.0
	 * @param Options $options Options manager.
	 * @param Logger  $logger  Logger instance.
	 */
	public function __construct( Options $options, Logger $logger ) {
		$this->options = $options;
		$this->logger  = $logger;
	}

	/**
	 * Check if migration is needed
	 *
	 * Auto-completes migration when prerequisites are met:
	 * - Fresh install (no legacy options) → mark completed immediately.
	 * - Legacy data + API key + project ID → auto-complete with cleanup.
	 *
	 * @since 2.8.0
	 * @return bool True if migration needed, false if already completed.
	 */
	public function is_migration_needed() {
		if ( get_option( 'wisewand_brief_config_migration_completed', false ) ) {
			return false;
		}

		// Check if any legacy options exist.
		$has_legacy = false;
		foreach ( self::LEGACY_OPTIONS as $option ) {
			if ( false !== get_option( $option, false ) ) {
				$has_legacy = true;
				break;
			}
		}

		// No legacy data (fresh install) → auto-complete.
		if ( ! $has_legacy ) {
			$this->mark_migration_completed();
			return false;
		}

		// Legacy data exists + prerequisites met → auto-complete with cleanup.
		$project_id = $this->options->get( 'wisewand_default_project_id', '' );
		$api_key    = $this->options->get( 'wisewand_api_key', '' );

		if ( ! empty( $project_id ) && ! empty( $api_key ) ) {
			$this->auto_complete_migration();
			return false;
		}

		return true;
	}

	/**
	 * Get validation status with detailed results
	 *
	 * Only called when is_migration_needed() returns true (i.e., API key or
	 * project ID is missing). Reports what's missing for UI display.
	 *
	 * @since 2.8.0
	 * @return array Validation results with blocking issues.
	 */
	public function get_validation_status() {
		$status = array(
			'blocking_issues' => array(),
		);

		// Check 1: Project ID.
		$project_id = $this->options->get( 'wisewand_default_project_id', '' );
		if ( empty( $project_id ) ) {
			$status['blocking_issues'][] = __( 'Please select a Wisewand project in Settings', 'wisewand-ai-content-writer-seo-content-generator' );
		}

		// Check 2: API Key.
		$api_key = $this->options->get( 'wisewand_api_key', '' );
		if ( empty( $api_key ) ) {
			$status['blocking_issues'][] = __( 'Please add your Wisewand API key in Settings', 'wisewand-ai-content-writer-seo-content-generator' );
		}

		return $status;
	}

	/**
	 * Auto-complete migration by deleting legacy options.
	 *
	 * @since 2.8.6
	 */
	private function auto_complete_migration() {
		foreach ( self::LEGACY_OPTIONS as $option ) {
			delete_option( $option );
		}
		$this->mark_migration_completed();

		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			error_log( 'Wisewand: Migration auto-completed — legacy options removed' );
		}
	}

	/**
	 * Mark migration as completed.
	 *
	 * @since 2.8.6
	 */
	private function mark_migration_completed() {
		update_option( 'wisewand_brief_config_migration_completed', true );
		update_option( 'wisewand_brief_config_migration_date', time() );
	}
}
