<?php
/**
 * SEO Analyzer — admin page rendering and AJAX handlers
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\SeoAnalyzer;

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

class AdminPage {

	/**
	 * Instance.
	 *
	 * @var AdminPage|null
	 */
	private static $instance = null;

	/**
	 * Get singleton.
	 *
	 * @return AdminPage
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {}

	/**
	 * Initialize hooks.
	 */
	public static function init() {
		$instance = self::get_instance();
		add_action( 'wp_ajax_seovaultseo_run_analyzer', array( __CLASS__, 'ajax_run_analyzer' ) );
		add_action( 'wp_ajax_seovaultseo_clear_analyzer', array( __CLASS__, 'ajax_clear_analyzer' ) );
	}

	/**
	 * AJAX: Run all SEO analyzer tests.
	 */
	public static function ajax_run_analyzer() {
		check_ajax_referer( 'seovaultseo_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'seovault-ai' ) ) );
		}

		$analyzer = SeoAnalyzer::get_instance();
		$results  = $analyzer->run_tests();

		wp_send_json_success( self::format_response( $results, $analyzer ) );
	}

	/**
	 * AJAX: Clear stored analyzer results.
	 */
	public static function ajax_clear_analyzer() {
		check_ajax_referer( 'seovaultseo_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'seovault-ai' ) ) );
		}

		$analyzer = SeoAnalyzer::get_instance();
		$analyzer->clear_results();

		wp_send_json_success( array( 'message' => __( 'Results cleared.', 'seovault-ai' ) ) );
	}

	/**
	 * Format results for AJAX response.
	 *
	 * @param array       $results  Raw results.
	 * @param SeoAnalyzer $analyzer Analyzer instance.
	 * @return array
	 */
	private static function format_response( $results, $analyzer ) {
		$metrics = $analyzer->get_metrics( $results );
		$grouped = $analyzer->sort_by_category( $results );
		$date    = $analyzer->get_last_checked_date();

		return array(
			'grouped' => $grouped,
			'metrics' => $metrics,
			'date'    => $date,
		);
	}

	/**
	 * Render the SEO Analyzer admin page.
	 */
	public static function render() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'seovault-ai' ) );
		}

		$analyzer = SeoAnalyzer::get_instance();
		$stored   = $analyzer->load_stored_results();
		$has_data = false !== $stored;

		$initial_data = array();
		if ( $has_data ) {
			$initial_data = self::format_response( $stored, $analyzer );
		}

		\SEOvaultSEO\Admin\Dashboard::render_global_header( __( 'SEO Analyzer', 'seovault-ai' ), admin_url( 'admin.php?page=seovault-ai' ) );
		?>

			<p class="seovaultseo-analyzer-intro">
				<?php esc_html_e( 'Run a comprehensive site-wide SEO audit. The analyzer checks your site configuration, content optimization, technical SEO, and performance factors.', 'seovault-ai' ); ?>
			</p>

			<div id="seovaultseo-analyzer-app"
				data-nonce="<?php echo esc_attr( wp_create_nonce( 'seovaultseo_admin' ) ); ?>"
				data-ajax-url="<?php echo esc_attr( admin_url( 'admin-ajax.php' ) ); ?>"
				data-has-data="<?php echo $has_data ? '1' : '0'; ?>"
				data-initial-data="<?php echo esc_attr( wp_json_encode( $initial_data ) ); ?>"
			>
				<!-- Score header -->
				<div class="seovaultseo-analyzer-header">
					<div class="seovaultseo-analyzer-score-wrap">
						<div class="seovaultseo-analyzer-score-circle" id="seovaultseo-score-circle">
							<svg viewBox="0 0 120 120" class="seovaultseo-score-svg">
								<circle class="seovaultseo-score-bg" cx="60" cy="60" r="52" />
								<circle class="seovaultseo-score-fill" cx="60" cy="60" r="52" id="seovaultseo-score-arc" />
							</svg>
							<div class="seovaultseo-score-text">
								<span class="seovaultseo-score-number" id="seovaultseo-score-number">—</span>
								<span class="seovaultseo-score-label"><?php esc_html_e( 'Score', 'seovault-ai' ); ?></span>
							</div>
						</div>
						<div class="seovaultseo-analyzer-score-info">
							<div class="seovaultseo-analyzer-grade" id="seovaultseo-analyzer-grade"></div>
							<div class="seovaultseo-analyzer-last-run" id="seovaultseo-analyzer-last-run"></div>
						</div>
					</div>

					<div class="seovaultseo-analyzer-actions">
						<button type="button" class="button button-primary button-hero" id="seovaultseo-run-analyzer">
							<span class="dashicons dashicons-update"></span>
							<?php esc_html_e( 'Run SEO Analysis', 'seovault-ai' ); ?>
						</button>
						<button type="button" class="button button-secondary" id="seovaultseo-clear-analyzer" style="display:none;">
							<span class="dashicons dashicons-trash"></span>
							<?php esc_html_e( 'Clear Results', 'seovault-ai' ); ?>
						</button>
					</div>
				</div>

				<!-- Status summary -->
				<div class="seovaultseo-analyzer-summary" id="seovaultseo-analyzer-summary" style="display:none;">
					<div class="seovaultseo-summary-stat seovaultseo-summary-ok">
						<span class="dashicons dashicons-yes-alt"></span>
						<span class="seovaultseo-summary-count" id="seovaultseo-summary-ok">0</span>
						<span class="seovaultseo-summary-label"><?php esc_html_e( 'Passed', 'seovault-ai' ); ?></span>
					</div>
					<div class="seovaultseo-summary-stat seovaultseo-summary-fail">
						<span class="dashicons dashicons-no-alt"></span>
						<span class="seovaultseo-summary-count" id="seovaultseo-summary-fail">0</span>
						<span class="seovaultseo-summary-label"><?php esc_html_e( 'Failed', 'seovault-ai' ); ?></span>
					</div>
					<div class="seovaultseo-summary-stat seovaultseo-summary-warning">
						<span class="dashicons dashicons-warning"></span>
						<span class="seovaultseo-summary-count" id="seovaultseo-summary-warning">0</span>
						<span class="seovaultseo-summary-label"><?php esc_html_e( 'Warnings', 'seovault-ai' ); ?></span>
					</div>
				</div>

				<!-- Loading state -->
				<div class="seovaultseo-analyzer-loading" id="seovaultseo-analyzer-loading" style="display:none;">
					<span class="spinner is-active"></span>
					<p><?php esc_html_e( 'Running SEO tests...', 'seovault-ai' ); ?></p>
				</div>

				<!-- Empty state -->
				<div class="seovaultseo-analyzer-empty" id="seovaultseo-analyzer-empty">
					<span class="dashicons dashicons-search"></span>
					<p><?php esc_html_e( 'Click "Run SEO Analysis" to start a site-wide audit.', 'seovault-ai' ); ?></p>
				</div>

				<!-- Results container -->
				<div class="seovaultseo-analyzer-results" id="seovaultseo-analyzer-results" style="display:none;"></div>
			</div>
		<?php
		\SEOvaultSEO\Admin\Dashboard::render_global_footer();
	}
}
