<?php
// admin/class-sifency-installer-admin.php

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

/**
 * Class Sifency_Installer_Admin
 *
 * Renders a modern, AJAX-powered admin page to recommend and install other plugins.
 * This class is designed to be rendered by another admin menu class.
 */
final class Sifency_Installer_Admin {

	/**
	 * The single instance of the class.
	 * @var Sifency_Installer_Admin|null
	 */
	private static $_instance = null;

	/**
	 * The hook suffix for the admin page where this content is rendered.
	 * This MUST be set from the outside for assets to load correctly.
	 * @var string
	 */
	private $page_hook_suffix = '';

	/**
	 * Ensures only one instance of the class is loaded.
	 *
	 * @return Sifency_Installer_Admin - Main instance.
	 */
	public static function instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	/**
	 * Constructor.
	 */
	private function __construct() {
		$this->init_hooks();
	}

	/**
	 * Initializes all the WordPress hooks.
	 */
	private function init_hooks() {
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
		add_action( 'wp_ajax_sifency_install_plugin', [ $this, 'handle_ajax_plugin_action' ] );
	}

	/**
	 * This is required for this class to know on which page to load its CSS and JS.
	 *
	 * @param string $hook_suffix The hook suffix of the page.
	 */
	public function set_page_hook_suffix( $hook_suffix ) {
		$this->page_hook_suffix = $hook_suffix;
	}

	/**
	 * Enqueues assets.
	 *
	 * @param string $hook The current admin page hook.
	 */
	public function enqueue_assets( $hook ) {
		if ( empty( $this->page_hook_suffix ) || $this->page_hook_suffix !== $hook ) {
			return;
		}
		wp_enqueue_script( 'jquery' );
	}

	/**
	 * Renders the admin page HTML content and the inline JavaScript.
	 */
	public function render_admin_page() {
		if ( ! function_exists( 'get_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		?>
		<div class="sifency-installer-wrap">
			<div class="sifency-installer-cards-container">
				<?php
				$plugins = $this->get_recommended_plugins();
				foreach ( $plugins as $plugin ) {
					$this->render_plugin_card( $plugin );
				}
				?>
			</div>
		</div>

		<?php

		$js_data = [
			'ajax_url' => admin_url( 'admin-ajax.php' ),
			'nonce'    => wp_create_nonce( 'sifency_install_nonce' ),
			'texts'    => [
				'installing' => __( 'Installing...', 'sifency-addons' ),
				'activating' => __( 'Activating...', 'sifency-addons' ),
				'activated'  => __( 'Activated', 'sifency-addons' ),
				'error'      => __( 'An error occurred. Please try again.', 'sifency-addons' ),
			],
		];
		?>
		<script type="text/javascript">
			// Define the object directly. This guarantees it exists for the script below.
			const sifencyInstaller = <?php echo wp_json_encode( $js_data ); ?>;

			(function ($) {
				'use strict';

				$(document).ready(function () {
					const installer = {
						container: $('.sifency-installer-cards-container'),

						init: function () {
							if (this.container.length) {
								this.bindEvents();
							}
						},

						bindEvents: function () {
							this.container.on('click', '.plugin-action-btn', this.handleButtonClick.bind(this));
						},

						handleButtonClick: function (e) {
							e.preventDefault();
							
							const $button = $(e.currentTarget);

							if ($button.hasClass('disabled') || $button.hasClass('processing')) {
								return;
							}

							const pluginData = {
								slug: $button.data('slug'),
								mainFile: $button.data('mainfile'),
								action: $button.data('action'),
							};
							
							const originalText = $button.find('.btn-text').text();

							this.setButtonState($button, 'processing');
							this.performAjaxRequest($button, pluginData, originalText);
						},

						performAjaxRequest: function ($button, pluginData, originalText) {
							$.ajax({
								url: sifencyInstaller.ajax_url,
								type: 'POST',
								dataType: 'json',
								data: {
									action: 'sifency_install_plugin',
									nonce: sifencyInstaller.nonce,
									task: pluginData.action,
									slug: pluginData.slug,
									main_file: pluginData.mainFile
								},
								success: (response) => {
									if (response.success) {
										this.setButtonState($button, 'activated');
									} else {
										alert('Error: ' + response.data.message);
										this.setButtonState($button, 'error', originalText);
									}
								},
								error: (xhr) => {
									alert(sifencyInstaller.texts.error);
									console.error('AJAX Error:', xhr.responseText);
									this.setButtonState($button, 'error', originalText);
								}
							});
						},
						
						setButtonState: function ($button, state, originalText = '') {
							const $btnText = $button.find('.btn-text');
							const action = $button.data('action');

							$button.removeClass('processing').prop('disabled', false);

							switch (state) {
								case 'processing':
									$button.addClass('processing').prop('disabled', true);
									$btnText.text(action === 'install' ? sifencyInstaller.texts.installing : sifencyInstaller.texts.activating);
									break;
									
								case 'activated':
									$button.removeClass('install-btn activate-btn').addClass('activated-btn disabled').prop('disabled', true);
									$button.data('action', '');
									$btnText.text(sifencyInstaller.texts.activated);
									break;
									
								case 'error':
									$btnText.text(originalText);
									break;
							}
						}
					};

					installer.init();
				});

			})(jQuery);
		</script>
		<?php
	}

	/**
	 * Renders a single plugin card.
	 * @param array $plugin The plugin data.
	 */
	private function render_plugin_card( $plugin ) {
		$status     = $this->get_plugin_status( $plugin['main_file'] );
		$button_txt = __( 'Install & Activate', 'sifency-addons' );
		$button_cls = 'install-btn';
		$action     = 'install';
		$disabled   = '';

		switch ( $status ) {
			case 'active':
				$button_txt = __( 'Activated', 'sifency-addons' );
				$button_cls = 'activated-btn sifency-admin-btn';
				$disabled   = 'disabled';
				$action     = '';
				break;
			case 'inactive':
				$button_txt = __( 'Activate', 'sifency-addons' );
				$button_cls = 'activate-btn sifency-admin-btn';
				$action     = 'activate';
				break;
		}
		?>
		<div class="sifency-installer-card">
			<div class="sifency-installer-card-header">
				<div class="sifency-installer-card-icon"><img src="<?php echo esc_url( $plugin['icon'] ); ?>" alt="<?php echo esc_attr( $plugin['name'] ); ?>"></div>
				<h3 class="sifency-installer-card-title"><?php echo esc_html( $plugin['name'] ); ?></h3>
			</div>
			<p class="sifency-installer-card-desc"><?php echo esc_html( $plugin['description'] ); ?></p>
			<div class="sifency-installer-card-footer">
				<button class="button button-primary plugin-action-btn <?php echo esc_attr( $button_cls ); ?>" data-slug="<?php echo esc_attr( $plugin['slug'] ); ?>" data-mainfile="<?php echo esc_attr( $plugin['main_file'] ); ?>" data-action="<?php echo esc_attr( $action ); ?>" <?php echo esc_html($disabled); ?>>
					<span class="btn-text"><?php echo esc_html( $button_txt ); ?></span>
					<span class="spinner"></span>
				</button>
			</div>
		</div>
		<?php
	}

	/**
	 * Defines the list of recommended plugins.
	 * @return array
	 */
	private function get_recommended_plugins() {
		return [
			[
				'name'        => 'Elementor',
				'slug'        => 'elementor',
				'main_file'   => 'elementor/elementor.php',
				'description' => 'The most advanced frontend drag & drop page builder. Create high-end, pixel perfect websites.',
				'icon'        => 'https://ps.w.org/elementor/assets/icon-128x128.gif?rev=3111597',
			],
			[
				'name'        => 'WooCommerce',
				'slug'        => 'woocommerce',
				'main_file'   => 'woocommerce/woocommerce.php',
				'description' => 'An eCommerce toolkit that helps you sell anything. Beautifully.',
				'icon'        => 'https://ps.w.org/woocommerce/assets/icon-256x256.png',
			],
		];
	}

	/**
	 * Checks the status of a plugin.
	 *
	 * @param string $plugin_main_file The plugin's main file (e.g., 'woocommerce/woocommerce.php').
	 * @return string 'active', 'inactive', or 'not_installed'.
	 */
	private function get_plugin_status( $plugin_main_file ) {
		$all_plugins = get_plugins();
		if ( isset( $all_plugins[ $plugin_main_file ] ) ) {
			return is_plugin_active( $plugin_main_file ) ? 'active' : 'inactive';
		}
		return 'not_installed';
	}

	/**
	 * Handles the AJAX request to install or activate a plugin.
	 */
	public function handle_ajax_plugin_action() {
		check_ajax_referer( 'sifency_install_nonce', 'nonce' );

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

		$action    = 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'] ) : '';

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

		if ( 'install' === $action ) {
			$this->ajax_install_plugin( $slug, $main_file );
		} elseif ( 'activate' === $action ) {
			$this->ajax_activate_plugin( $main_file );
		} else {
			wp_send_json_error( [ 'message' => __( 'Invalid action.', 'sifency-addons' ) ], 400 );
		}
	}

	/**
	 * Helper to handle plugin installation via AJAX.
	 *
	 * @param string $slug The plugin slug.
	 * @param string $main_file The plugin's main file path.
	 */
	private function ajax_install_plugin( $slug, $main_file ) {
		include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
		include_once ABSPATH . 'wp-admin/includes/plugin-install.php';

		$api = plugins_api( 'plugin_information', [ 'slug' => $slug, 'fields' => [ 'sections' => false ] ] );
		if ( is_wp_error( $api ) ) {
			wp_send_json_error( [ 'message' => $api->get_error_message() ] );
		}

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

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

		// Installation successful, now activate it.
		wp_cache_flush(); // Flush cache to ensure WP sees the new plugin.
		$this->ajax_activate_plugin( $main_file );
	}

	/**
	 * Helper function to activate a plugin and send a consistent JSON response.
	 *
	 * @param string $main_file The plugin's main file path.
	 */
	private function ajax_activate_plugin( $main_file ) {
		$result = activate_plugin( $main_file );

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

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

// Instantiate the class.
Sifency_Installer_Admin::instance();