<?php
namespace WpRigel\Commandify;

defined( 'ABSPATH' ) || exit;

/**
 * Register installation commands
 * Hooks into commandify_register_commands at priority 50 (after other commands)
 */
add_action(
	'commandify_register_commands',
	function () {
		// Install Plugin.
		commandify_register_command(
			array(
				'id'          => 'install-plugin',
				'title'       => __( 'Install Plugin', 'commandify' ),
				'description' => __( 'Search and install plugins from WordPress.org', 'commandify' ),
				'type'        => 'search',
				'callback'    => 'WpRigel\Commandify\search_plugins_callback',
				'category'    => 'plugins',
				'icon'        => 'dashicons-admin-plugins',
				'keywords'    => array( 'install', 'plugin', 'add', 'download' ),
				'capability'  => 'install_plugins',
				'priority'    => 50,
				'placeholder' => __( 'Search WordPress.org plugins...', 'commandify' ),
				'min_chars'   => 3,
				'debounce'    => 500,
			)
		);

		// Install Theme.
		commandify_register_command(
			array(
				'id'          => 'install-theme',
				'title'       => __( 'Install Theme', 'commandify' ),
				'description' => __( 'Search and install themes from WordPress.org', 'commandify' ),
				'type'        => 'search',
				'callback'    => 'WpRigel\Commandify\search_themes_callback',
				'category'    => 'themes',
				'icon'        => 'dashicons-admin-appearance',
				'keywords'    => array( 'install', 'theme', 'add', 'download' ),
				'capability'  => 'install_themes',
				'priority'    => 45,
				'placeholder' => __( 'Search WordPress.org themes...', 'commandify' ),
				'min_chars'   => 3,
				'debounce'    => 500,
			)
		);
	}
);

// Callback functions.
function search_plugins_callback( $query ) {
	// Require at least 3 characters.
	if ( strlen( $query ) < 3 ) {
		return array();
	}

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

	// Cache for 5 minutes.
	$cache_key = 'commandify_plugin_search_' . md5( $query );
	$cached    = get_transient( $cache_key );
	if ( false !== $cached ) {
		return $cached;
	}

	$args = array(
		'search'   => sanitize_text_field( $query ),
		'per_page' => 10,
		'fields'   => array(
			'short_description' => true,
			'icons'             => true,
			'active_installs'   => true,
			'rating'            => true,
			'downloaded'        => true,
		),
	);

	$api = plugins_api( 'query_plugins', $args );

	if ( is_wp_error( $api ) ) {
		return array();
	}

	$results = array();

	if ( empty( $api->plugins ) ) {
		return array();
	}

	foreach ( $api->plugins as $plugin ) {
		// Convert to object if it's an array.
		$plugin = (object) $plugin;

		// Decode any HTML entities in plugin name for display in React.
		$plugin_name = html_entity_decode( $plugin->name, ENT_QUOTES, get_bloginfo( 'charset' ) );

		$is_installed = is_plugin_installed( $plugin->slug );
		$plugin_file  = $is_installed ? get_plugin_file( $plugin->slug ) : false;
		$is_active    = $is_installed && $plugin_file && is_plugin_active( $plugin_file );

		$status_text = $is_active ? __( 'Active', 'commandify' ) : ( $is_installed ? __( 'Installed', 'commandify' ) : __( 'Not Installed', 'commandify' ) );
		/* translators: %s: Number of active installations */
		$installs_text = sprintf( __( '%s+ installs', 'commandify' ), number_format_i18n( $plugin->active_installs ) );

		$actions = array();

		if ( ! $is_installed ) {
			$actions[] = array(
				'id'                   => 'install-plugin-' . $plugin->slug,
				'title'                => __( 'Install', 'commandify' ),
				'type'                 => 'action',
				'icon'                 => 'dashicons-download',
				'has_dynamic_callback' => true,
				'loading_message'      => __( 'Installing plugin...', 'commandify' ),
			);
		} else {
			$actions[] = array(
				'id'       => 'view-plugin-' . $plugin->slug,
				'title'    => __( 'View Details', 'commandify' ),
				'type'     => 'navigation',
				'callback' => admin_url( 'plugin-install.php?tab=plugin-information&plugin=' . $plugin->slug ),
				'icon'     => 'dashicons-info',
			);

			if ( ! $is_active ) {
				$actions[] = array(
					'id'                   => 'activate-plugin-' . $plugin->slug,
					'title'                => __( 'Activate', 'commandify' ),
					'type'                 => 'action',
					'icon'                 => 'dashicons-yes',
					'has_dynamic_callback' => true,
				);
			} else {
				$actions[] = array(
					'id'                   => 'deactivate-plugin-' . $plugin->slug,
					'title'                => __( 'Deactivate', 'commandify' ),
					'type'                 => 'action',
					'icon'                 => 'dashicons-no',
					'has_dynamic_callback' => true,
				);
			}
		}//end if

		// Get plugin icon.
		$icon  = 'dashicons-admin-plugins';
		$icons = is_array( $plugin->icons ) ? $plugin->icons : (array) $plugin->icons;
		if ( ! empty( $icons ) ) {
			if ( isset( $icons['1x'] ) ) {
				$icon = $icons['1x'];
			} elseif ( isset( $icons['svg'] ) ) {
				$icon = $icons['svg'];
			} elseif ( isset( $icons['2x'] ) ) {
				$icon = $icons['2x'];
			}
		}

		$results[] = array(
			'id'          => 'plugin-' . $plugin->slug,
			'title'       => $plugin_name,
			/* translators: 1: Status text, 2: Install/download count, 3: Star rating */
			'description' => sprintf( __( '%1$s • %2$s • %3$s★', 'commandify' ), $status_text, $installs_text, number_format_i18n( $plugin->rating / 20, 1 ) ),
			'type'        => 'submenu',
			'icon'        => $icon,
			'category'    => 'plugins',
			'actions'     => $actions,
			'plugin_slug' => $plugin->slug,
		// Store slug for post-install refresh
		);
	}//end foreach

	// Cache the results for 5 minutes.
	set_transient( $cache_key, $results, 5 * MINUTE_IN_SECONDS );

	return $results;
}

function search_themes_callback( $query ) {
	// Require at least 3 characters.
	if ( strlen( $query ) < 3 ) {
		return array();
	}

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

	// Cache for 5 minutes.
	$cache_key = 'commandify_theme_search_' . md5( $query );
	$cached    = get_transient( $cache_key );
	if ( false !== $cached ) {
		return $cached;
	}

	$args = array(
		'search'   => sanitize_text_field( $query ),
		'per_page' => 10,
		'fields'   => array(
			'description' => true,
			'downloaded'  => true,
			'rating'      => true,
		),
	);

	$api = themes_api( 'query_themes', $args );

	if ( is_wp_error( $api ) ) {
		return array();
	}

	if ( empty( $api->themes ) ) {
		return array();
	}

	$results = array();

	foreach ( $api->themes as $theme ) {
		// Convert to object if it's an array.
		$theme = (object) $theme;

		// Decode any HTML entities in theme name for display in React.
		$theme_name = html_entity_decode( $theme->name, ENT_QUOTES, get_bloginfo( 'charset' ) );

		$is_installed = wp_get_theme( $theme->slug )->exists();
		$is_active    = $is_installed && ( get_stylesheet() === $theme->slug || get_template() === $theme->slug );

		$status_text = $is_active ? __( 'Active', 'commandify' ) : ( $is_installed ? __( 'Installed', 'commandify' ) : __( 'Not Installed', 'commandify' ) );
		/* translators: %s: Number of downloads */
		$downloads_text = sprintf( __( '%s downloads', 'commandify' ), number_format_i18n( $theme->downloaded ) );

		$actions = array();

		if ( ! $is_installed ) {
			$actions[] = array(
				'id'                   => 'install-theme-' . $theme->slug,
				'title'                => __( 'Install', 'commandify' ),
				'type'                 => 'action',
				'icon'                 => 'dashicons-download',
				'has_dynamic_callback' => true,
				'loading_message'      => __( 'Installing theme...', 'commandify' ),
			);
		} else {
			$actions[] = array(
				'id'       => 'view-theme-' . $theme->slug,
				'title'    => __( 'View Details', 'commandify' ),
				'type'     => 'navigation',
				'callback' => admin_url( 'theme-install.php?theme=' . $theme->slug ),
				'icon'     => 'dashicons-info',
			);

			if ( ! $is_active ) {
				$actions[] = array(
					'id'                   => 'activate-theme-' . $theme->slug,
					'title'                => __( 'Activate', 'commandify' ),
					'type'                 => 'action',
					'icon'                 => 'dashicons-yes',
					'has_dynamic_callback' => true,
					'loading_message'      => __( 'Activating theme...', 'commandify' ),
				);
			}
		}//end if

		// Get theme screenshot/thumbnail URL
		$icon = 'dashicons-admin-appearance';
		if ( ! empty( $theme->screenshot_url ) ) {
			// Add https: protocol if URL starts with //
			$icon = str_starts_with( $theme->screenshot_url, '//' ) ? 'https:' . $theme->screenshot_url : $theme->screenshot_url;
		} elseif ( ! empty( $theme->screenshots ) && is_array( $theme->screenshots ) && ! empty( $theme->screenshots[0] ) ) {
			$icon = str_starts_with( $theme->screenshots[0], '//' ) ? 'https:' . $theme->screenshots[0] : $theme->screenshots[0];
		}

		$results[] = array(
			'id'          => 'theme-' . $theme->slug,
			'title'       => $theme_name,
			/* translators: 1: Status text, 2: Install/download count, 3: Star rating */
			'description' => sprintf( __( '%1$s • %2$s • %3$s★', 'commandify' ), $status_text, $downloads_text, number_format_i18n( $theme->rating / 20, 1 ) ),
			'type'        => 'submenu',
			'icon'        => $icon,
			'category'    => 'themes',
			'actions'     => $actions,
			'theme_slug'  => $theme->slug,
		// Store slug for post-install refresh
		);
	}//end foreach

	// Cache the results for 5 minutes.
	set_transient( $cache_key, $results, 5 * MINUTE_IN_SECONDS );

	return $results;
}

function is_plugin_installed( $slug ) {
	if ( ! function_exists( 'get_plugins' ) ) {
		require_once ABSPATH . 'wp-admin/includes/plugin.php';
	}

	$plugin_file = get_plugin_file( $slug );
	return $plugin_file && file_exists( WP_PLUGIN_DIR . '/' . $plugin_file );
}

function get_plugin_file( $slug ) {
	if ( ! function_exists( 'get_plugins' ) ) {
		require_once ABSPATH . 'wp-admin/includes/plugin.php';
	}

	$plugins = get_plugins();

	foreach ( $plugins as $plugin_file => $plugin_data ) {
		if ( strpos( $plugin_file, $slug . '/' ) === 0 || $plugin_file === $slug . '.php' ) {
			return $plugin_file;
		}
	}

	// Check if slug.php exists directly
	if ( file_exists( WP_PLUGIN_DIR . '/' . $slug . '.php' ) ) {
		return $slug . '.php';
	}

	// Check if slug/slug.php exists
	if ( file_exists( WP_PLUGIN_DIR . '/' . $slug . '/' . $slug . '.php' ) ) {
		return $slug . '/' . $slug . '.php';
	}

	return false;
}
