<?php
/**
 * Update Themes Tool.
 *
 * Update one or more themes to their latest versions using Theme_Upgrader.
 * Supports updating specific themes or all themes with available updates.
 *
 * @package   Agenistrator
 * @since     1.0.0
 * @author    Alex Ruban <alex@maximum.guru>
 * @author    Maximum Software Inc <contact@maximum.software>
 * @license   GPL-3.0-only
 * @link      https://maximum.software/
 *
 * SPDX-FileCopyrightText: 2025-2026 Alex Ruban <alex@maximum.guru>
 * SPDX-FileCopyrightText: 2025-2026 Maximum Software Inc <contact@maximum.software>
 * SPDX-License-Identifier: GPL-3.0-only
 */

namespace Agenistrator;

// Direct access prevention
if ( ! defined( 'ABSPATH' ) ) {
	return;
}

/**
 * Update_Themes_Tool class.
 */
class Update_Themes_Tool extends Tool {

	/**
	 * Get the tool ID.
	 *
	 * @return string The tool ID.
	 * @since     1.0.0
	 */
	public function get_id() {
		return 'update_themes';
	}

	/**
	 * Get the tool name.
	 *
	 * @return string The tool name.
	 * @since     1.0.0
	 */
	public function get_name() {
		return __( 'Update Themes', 'agenistrator' );
	}

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Update one or more themes to their latest versions.';
	}

	/**
	 * Get additional description instructions for the LLM.
	 *
	 * @return string Additional instructions appended to description.
	 * @since     1.0.0
	 */
	public function get_description_instructions() {
		return 'Use `list_available_updates` to see which themes have updates available.';
	}

	/**
	 * Get the parameters schema for this tool.
	 *
	 * @return array Parameters schema in JSON Schema format.
	 * @since     1.0.0
	 */
	public function get_parameters() {
		return array(
			'type'       => 'object',
			'properties' => array(
				'themes' => array(
					'type'        => 'array',
					'description' => 'Array of theme slugs to update (e.g., ["twentytwentyfour", "astra"]). Use "all" as the only element to update all themes with available updates.',
					'items'       => array(
						'type' => 'string',
					),
				),
			),
			'required'   => array( 'themes' ),
		);
	}

	/**
	 * Check if the current user can execute this tool.
	 *
	 * @return bool True if the current user has permission.
	 * @since     1.0.0
	 */
	public function current_user_can_execute() {
		return current_user_can( 'update_themes' );
	}

	/**
	 * Check if this tool is read-only.
	 *
	 * @return bool True if the tool only reads data.
	 * @since     1.0.0
	 */
	public function is_read_only() {
		return false;
	}

	/**
	 * Execute the tool with the given arguments.
	 *
	 * @param array $args The tool arguments.
	 *
	 * @return array The tool execution result.
	 * @since     1.0.0
	 */
	protected function execute( $args ) {
		// Check if file modifications are disabled
		if ( ! wp_is_file_mod_allowed( 'theme_install' ) ) {
			return $this->error_response( 'File modifications are disabled' );
		}

		if ( ! isset( $args['themes'] ) || ! is_array( $args['themes'] ) || empty( $args['themes'] ) ) {
			return $this->error_response( 'themes parameter is required and must be a non-empty array' );
		}

		require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';

		wp_update_themes();
		$update_themes     = get_site_transient( 'update_themes' );
		$available_updates = ! empty( $update_themes->response ) ? $update_themes->response : array();

		if ( empty( $available_updates ) ) {
			return $this->success_response(
				'No theme updates available',
				array(
					'updated' => array(),
					'failed'  => array(),
				)
			);
		}

		// Determine which themes to update
		if ( count( $args['themes'] ) === 1 && strtolower( $args['themes'][0] ) === 'all' ) {
			$themes_to_update = array_keys( $available_updates );
		} else {
			$themes_to_update = array_filter(
				array_map( 'sanitize_text_field', $args['themes'] ),
				fn( $slug ) => isset( $available_updates[ $slug ] )
			);
		}

		if ( empty( $themes_to_update ) ) {
			return $this->error_response( 'No matching themes found with available updates' );
		}

		// Capture old versions and names before update
		$old_versions = array();
		$theme_names  = array();
		foreach ( $themes_to_update as $slug ) {
			$theme                 = wp_get_theme( $slug );
			$old_versions[ $slug ] = $theme->exists() ? $theme->get( 'Version' ) : 'unknown';
			$theme_names[ $slug ]  = $theme->exists() ? $theme->get( 'Name' ) : $slug;
		}

		// Perform bulk update
		$upgrader     = new \Theme_Upgrader( new \WP_Ajax_Upgrader_Skin() );
		$bulk_results = $upgrader->bulk_upgrade( $themes_to_update );

		wp_clean_themes_cache();

		// Process results
		$results = array(
			'updated' => array(),
			'failed'  => array(),
		);
		foreach ( $themes_to_update as $slug ) {
			$update_info = $available_updates[ $slug ];

			if ( isset( $bulk_results[ $slug ] ) && false !== $bulk_results[ $slug ] && ! is_wp_error( $bulk_results[ $slug ] ) ) {
				$updated_theme        = wp_get_theme( $slug );
				$results['updated'][] = array(
					'slug'        => $slug,
					'name'        => $theme_names[ $slug ],
					'old_version' => $old_versions[ $slug ],
					'new_version' => $updated_theme->exists() ? $updated_theme->get( 'Version' ) : $update_info['new_version'],
				);
			} else {
				$error               = is_wp_error( $bulk_results[ $slug ] ?? null )
					? $bulk_results[ $slug ]->get_error_message()
					: 'Update failed';
				$results['failed'][] = array(
					'slug'  => $slug,
					'name'  => $theme_names[ $slug ],
					'error' => $error,
				);
			}
		}

		$message = String_Utils::replace_tags(
			__( 'Theme update complete: {updated} updated, {failed} failed', 'agenistrator' ),
			array(
				'updated' => count( $results['updated'] ),
				'failed'  => count( $results['failed'] ),
			)
		);

		return empty( $results['failed'] )
			? $this->success_response( $message, $results )
			: $this->error_response( $message, $results );
	}
}
