<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
class Sifency_Addons_Plugin_Installer_Ajax {

	public function __construct() {
		add_action( 'wp_ajax_sifency_install_plugin', array( $this, 'handle_ajax_request' ) );
	}

	/**
	 * Main AJAX Handler
	 */
	public function handle_ajax_request() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'sifency_install_nonce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security verification failed.', 'sifency-addons' ) ), 403 );
		}

		if ( ! current_user_can( 'install_plugins' ) ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission to perform this action.', 'sifency-addons' ) ), 403 );
		}

		$task         = isset( $_POST['task'] ) ? sanitize_key( $_POST['task'] ) : '';
		$slug         = isset( $_POST['slug'] ) ? sanitize_key( $_POST['slug'] ) : '';
		$main_file    = isset( $_POST['main_file'] ) ? sanitize_text_field( $_POST['main_file'] ) : '';
		$source       = isset( $_POST['source'] ) ? sanitize_key( $_POST['source'] ) : 'repo';
		$download_url = isset( $_POST['download_url'] ) ? esc_url_raw( $_POST['download_url'] ) : '';

		if ( empty( $task ) || empty( $slug ) || empty( $main_file ) ) {
			wp_send_json_error( array( 'message' => __( 'Missing required parameters.', 'sifency-addons' ) ), 400 );
		}

		if ( 'install' === $task ) {
			$this->install_plugin( $slug, $main_file, $source, $download_url );
		} elseif ( 'activate' === $task ) {
			$this->activate_plugin( $main_file );
		} else {
			wp_send_json_error( array( 'message' => __( 'Invalid action.', 'sifency-addons' ) ), 400 );
		}
	}

	/**
	 * Installs a plugin from WP Repo or External URL.
	 */
	private function install_plugin( $slug, $main_file, $source, $download_url ) {
		include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
		include_once ABSPATH . 'wp-admin/includes/plugin-install.php';

		$url = '';

		if ( 'external' === $source && ! empty( $download_url ) ) {
			$url = $download_url;
		} else {
			$api = plugins_api(
				'plugin_information',
				array(
					'slug'   => $slug,
					'fields' => array( 'sections' => false ),
				)
			);
			if ( is_wp_error( $api ) ) {
				wp_send_json_error( array( 'message' => $api->get_error_message() ) );
			}
			$url = $api->download_link;
		}

		$upgrader = new Plugin_Upgrader( new WP_Ajax_Upgrader_Skin() );
		$result   = $upgrader->install( $url );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		} elseif ( is_null( $result ) ) {
			wp_send_json_error( array( 'message' => __( 'Unable to connect to the filesystem. Please confirm your credentials.', 'sifency-addons' ) ) );
		} elseif ( ! $result ) {
			wp_send_json_error( array( 'message' => __( 'Plugin installation failed.', 'sifency-addons' ) ) );
		}

		wp_cache_flush();

		$this->activate_plugin( $main_file );
	}

	/**
	 * Activates a plugin.
	 */
	private function activate_plugin( $main_file ) {
		if ( ! file_exists( WP_PLUGIN_DIR . '/' . $main_file ) ) {
			wp_send_json_error( array( 'message' => __( 'Plugin file not found. Installation might have failed.', 'sifency-addons' ) ) );
		}

		$result = activate_plugin( $main_file );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success( array( 'message' => __( 'Plugin activated successfully.', 'sifency-addons' ) ) );
	}
}

// Initialize the AJAX handler
new Sifency_Addons_Plugin_Installer_Ajax();
