<?php //phpcs:ignore
/**
 * Options Action.
 */

namespace PRECO\Includes\Admin;

defined( 'ABSPATH' ) || exit;

use PRECO\Includes\Preco;

/**
 * OurPlugins class.
 */
class OurPlugins {

	/**
	 * Setup class.
	 */
	public function __construct() {
		add_action( 'wp_ajax_preco_install_plugin', array( $this, 'preco_install_plugin_callback' ) );
	}

	/**
	 * Handles plugin installation and activation via AJAX.
	 *
	 * @return void
	 */
	public function preco_install_plugin_callback() {
		$nonce  = isset( $_POST['wpnonce'] ) ? sanitize_key( wp_unslash( $_POST['wpnonce'] ) ) : '';
		$plugin = isset( $_POST['plugin'] ) ? sanitize_text_field( wp_unslash( $_POST['plugin'] ) ) : '';

		if ( ! wp_verify_nonce( $nonce, 'wp_rest' ) || ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error(
				array(
					'message' => __( 'Invalid request.', 'wow-ai-product-recommendations' ),
				)
			);
			return;
		}

		if ( ! $plugin ) {
			wp_send_json_error(
				array(
					'message' => __( 'No plugin specified.', 'wow-ai-product-recommendations' ),
				)
			);
			return;
		}

		$res = Preco::install_and_active_plugin( $plugin );

		wp_send_json_success(
			array(
				'message' => $res,
			)
		);
	}
}
