<?php
/**
 * Dashboard API Class
 *
 * REST API endpoints for dashboard functionality
 *
 * @package SmartyPress_AI_Engine
 * @since 1.0.0
 */

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

/**
 * Dashboard API class
 */
class SmartyPress_AI_Dashboard_API {

	/**
	 * Plugin slug for AI Thumbnails Maker
	 *
	 * @var string
	 */
	private $thumbnails_plugin_slug = 'ai-thumbnails-maker';

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'rest_api_init', array( $this, 'register_rest_routes' ), 10 );
	}

	/**
	 * Register REST API routes
	 */
	public function register_rest_routes() {
		// Check plugin status
		register_rest_route(
			'smartypress/v1',
			'/dashboard/check-thumbnails-plugin',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'check_thumbnails_plugin' ),
				'permission_callback' => array( $this, 'check_permissions' ),
			)
		);

		// Install plugin
		register_rest_route(
			'smartypress/v1',
			'/dashboard/install-thumbnails-plugin',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'install_thumbnails_plugin' ),
				'permission_callback' => array( $this, 'check_permissions' ),
			)
		);

		// Activate plugin
		register_rest_route(
			'smartypress/v1',
			'/dashboard/activate-thumbnails-plugin',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'activate_thumbnails_plugin' ),
				'permission_callback' => array( $this, 'check_permissions' ),
			)
		);
	}

	/**
	 * Check if AI Thumbnails Maker plugin is installed and active
	 *
	 * @return WP_REST_Response
	 */
	public function check_thumbnails_plugin() {
		$plugin_file = $this->thumbnails_plugin_slug . '/' . $this->thumbnails_plugin_slug . '.php';
		
		if ( ! function_exists( 'get_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		$all_plugins = get_plugins();
		$is_installed = isset( $all_plugins[ $plugin_file ] );
		$is_active = is_plugin_active( $plugin_file );

		$status = 'not-installed';
		if ( $is_active ) {
			$status = 'active';
		} elseif ( $is_installed ) {
			$status = 'installed';
		}

		return rest_ensure_response(
			array(
				'status' => $status,
				'installed' => $is_installed,
				'active' => $is_active,
			)
		);
	}

	/**
	 * Install AI Thumbnails Maker plugin
	 *
	 * @return WP_REST_Response|WP_Error
	 */
	public function install_thumbnails_plugin() {
		if ( ! current_user_can( 'install_plugins' ) ) {
			return new WP_Error( 'insufficient_permissions', __( 'You do not have permission to install plugins.', 'smartypress-ai-engine' ), array( 'status' => 403 ) );
		}

		// Check if plugin is already installed
		$plugin_file = $this->thumbnails_plugin_slug . '/' . $this->thumbnails_plugin_slug . '.php';
		if ( file_exists( WP_PLUGIN_DIR . '/' . $plugin_file ) ) {
			return rest_ensure_response(
				array(
					'success' => true,
					'message' => __( 'Plugin is already installed.', 'smartypress-ai-engine' ),
					'already_installed' => true,
				)
			);
		}

		// Include required files
		if ( ! function_exists( 'download_url' ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}
		if ( ! function_exists( 'install_plugin' ) ) {
			require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
			require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
		}

		// Get plugin info from WordPress.org
		$api = plugins_api(
			'plugin_information',
			array(
				'slug' => $this->thumbnails_plugin_slug,
				'fields' => array(
					'short_description' => false,
					'sections' => false,
					'requires' => false,
					'rating' => false,
					'ratings' => false,
					'downloaded' => false,
					'last_updated' => false,
					'added' => false,
					'tags' => false,
					'compatibility' => false,
					'homepage' => false,
					'donate_link' => false,
				),
			)
		);

		if ( is_wp_error( $api ) ) {
			return new WP_Error( 'plugin_info_failed', $api->get_error_message(), array( 'status' => 500 ) );
		}

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

		if ( is_wp_error( $result ) ) {
			return new WP_Error( 'plugin_install_failed', $result->get_error_message(), array( 'status' => 500 ) );
		}

		if ( ! $result ) {
			return new WP_Error( 'plugin_install_failed', __( 'Plugin installation failed.', 'smartypress-ai-engine' ), array( 'status' => 500 ) );
		}

		// Try to activate after installation
		$activate_result = $this->activate_thumbnails_plugin_internal();

		return rest_ensure_response(
			array(
				'success' => true,
				'message' => __( 'Plugin installed successfully.', 'smartypress-ai-engine' ),
				'activated' => ! is_wp_error( $activate_result ),
			)
		);
	}

	/**
	 * Activate AI Thumbnails Maker plugin
	 *
	 * @return WP_REST_Response|WP_Error
	 */
	public function activate_thumbnails_plugin() {
		if ( ! current_user_can( 'activate_plugins' ) ) {
			return new WP_Error( 'insufficient_permissions', __( 'You do not have permission to activate plugins.', 'smartypress-ai-engine' ), array( 'status' => 403 ) );
		}

		$result = $this->activate_thumbnails_plugin_internal();

		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response(
			array(
				'success' => true,
				'message' => __( 'Plugin activated successfully.', 'smartypress-ai-engine' ),
			)
		);
	}

	/**
	 * Internal method to activate plugin
	 *
	 * @return bool|WP_Error
	 */
	private function activate_thumbnails_plugin_internal() {
		$plugin_file = $this->thumbnails_plugin_slug . '/' . $this->thumbnails_plugin_slug . '.php';
		
		if ( ! file_exists( WP_PLUGIN_DIR . '/' . $plugin_file ) ) {
			return new WP_Error( 'plugin_not_found', __( 'Plugin is not installed.', 'smartypress-ai-engine' ) );
		}

		if ( ! function_exists( 'activate_plugin' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		$result = activate_plugin( $plugin_file );

		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return true;
	}

	/**
	 * Check permissions
	 *
	 * @return bool
	 */
	public function check_permissions() {
		return current_user_can( 'manage_options' );
	}
}

