<?php

namespace NeurogenesisTheme\Core\Admin\Actions;

use NeurogenesisTheme\Helpers\RecommendedPlugin;

defined( 'ABSPATH' ) || exit;

/**
 * AJAX handler for installing and activating the recommended plugin.
 */
final class RecommendedPluginAjax {

	public function __construct() {
		add_action( 'wp_ajax_neurogenesis_theme_install_recommended_plugin', array( $this, 'install_recommended_plugin' ) );
	}

	public function install_recommended_plugin(): void {
		check_ajax_referer( 'neurogenesis_theme_recommended_plugin', 'nonce' );

		$status = RecommendedPlugin::get_status();

		if ( 'not_installed' === $status && ! current_user_can( 'install_plugins' ) ) {
			wp_send_json_error(
				array( 'message' => __( 'You do not have permission to install plugins.', 'thinko' ) ),
				403
			);
		}

		if ( 'inactive' === $status && ! current_user_can( 'activate_plugins' ) ) {
			wp_send_json_error(
				array( 'message' => __( 'You do not have permission to activate plugins.', 'thinko' ) ),
				403
			);
		}

		$result = RecommendedPlugin::install_and_activate();

		if ( is_wp_error( $result ) ) {
			$status = 'install_in_progress' === $result->get_error_code() ? 429 : 400;
			wp_send_json_error( array( 'message' => $result->get_error_message() ), $status );
		}

		$response = array_merge( $result, RecommendedPlugin::get_card_data() );

		if ( ! empty( $result['installed'] ) && 'inactive' === ( $result['status'] ?? '' ) ) {
			$response['notice'] = true;
		}

		// Recompute after activation: plugin owns the menu (admin.php), theme Appearance page is gone.
		if ( 'active' === ( $response['status'] ?? '' ) ) {
			$dashboard_url = neurogenesis_theme_generate_page_url( 'dashboard' );
			$response['dashboard_url'] = $dashboard_url;
			$response['redirect_url']  = (string) apply_filters(
				'neurogenesis_theme_onboarding_import_url',
				$dashboard_url
			);
		}

		wp_send_json_success( $response );
	}
}
