<?php
/**
 * Create Theme Tool.
 *
 * Create a new WordPress theme with minimal required files (style.css, index.php).
 * Supports child theme creation with parent theme reference.
 *
 * @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;
}

/**
 * Create_Theme_Tool class.
 */
class Create_Theme_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Create a new WordPress theme with minimal required files (style.css with header, index.php).';
	}

	/**
	 * 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(
				'name'        => array(
					'type'        => 'string',
					'description' => 'The theme name (e.g., "My Custom Theme")',
				),
				'description' => array(
					'type'        => 'string',
					'description' => 'A brief description of the theme',
				),
				'author'      => array(
					'type'        => 'string',
					'description' => 'Author name (defaults to current user display name)',
				),
				'version'     => array(
					'type'        => 'string',
					'description' => 'Initial version (defaults to "1.0.0")',
				),
				'block_theme' => array(
					'type'        => 'boolean',
					'description' => 'Create a block theme instead of a classic theme (default: false)',
				),
				'activate'    => array(
					'type'        => 'boolean',
					'description' => 'Whether to activate the theme after creation (default: false)',
				),
			),
			'required'   => array( 'name', 'description' ),
		);
	}

	/**
	 * 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( 'install_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;
	}

	/**
	 * Get the default enabled status for this tool.
	 *
	 * @return bool True if enabled by default, false otherwise.
	 * @since     1.0.0
	 */
	public function get_default_enabled_status() {
		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' );
		}

		// Check if file editing is disabled
		if ( defined( 'DISALLOW_FILE_EDIT' ) && DISALLOW_FILE_EDIT ) {
			return $this->error_response( 'File editing is disabled (DISALLOW_FILE_EDIT is set)' );
		}

		if ( ! isset( $args['name'] ) || empty( trim( $args['name'] ) ) ) {
			return $this->error_response( 'Theme name is required' );
		}
		if ( ! isset( $args['description'] ) || empty( trim( $args['description'] ) ) ) {
			return $this->error_response( 'Theme description is required' );
		}

		$name        = sanitize_text_field( $args['name'] );
		$description = sanitize_text_field( $args['description'] );
		$slug        = sanitize_title( $name );
		$version     = isset( $args['version'] ) ? sanitize_text_field( $args['version'] ) : '1.0.0';
		$block_theme = isset( $args['block_theme'] ) ? (bool) $args['block_theme'] : false;
		$activate    = isset( $args['activate'] ) ? (bool) $args['activate'] : false;

		// Get author from args or current user
		if ( isset( $args['author'] ) && ! empty( trim( $args['author'] ) ) ) {
			$author = sanitize_text_field( $args['author'] );
		} else {
			$current_user = wp_get_current_user();
			$author       = $current_user->display_name;
		}

		$theme_dir = get_theme_root() . DIRECTORY_SEPARATOR . $slug;

		// Check if theme directory already exists
		if ( file_exists( $theme_dir ) ) {
			return $this->error_response( "Theme directory already exists: {$slug}" );
		}

		// Create theme directory
		if ( ! wp_mkdir_p( $theme_dir ) ) {
			return $this->error_response( 'Failed to create theme directory' );
		}

		$text_domain   = $slug;
		$files_created = array();

		// Create style.css with theme header
		$style_content  = "/*\n";
		$style_content .= "Theme Name: {$name}\n";
		$style_content .= "Description: {$description}\n";
		$style_content .= "Version: {$version}\n";
		$style_content .= "Author: {$author}\n";
		$style_content .= "Text Domain: {$text_domain}\n";
		$style_content .= "*/\n";

		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- TODO: possibly migrate to WP_Filesystem later
		if ( file_put_contents( $theme_dir . '/style.css', $style_content ) === false ) {
			$this->cleanup_directory( $theme_dir );
			return $this->error_response( 'Failed to create style.css' );
		}
		$files_created[] = 'style.css';

		if ( $block_theme ) {
			$this->create_block_theme_files( $theme_dir, $files_created );
		} else {
			$this->create_classic_theme_files( $theme_dir, $files_created );
		}

		$result = array(
			'slug'          => $slug,
			'directory'     => $theme_dir,
			'type'          => $block_theme ? 'block' : 'classic',
			'files_created' => $files_created,
			'activated'     => false,
		);

		// Activate if requested
		if ( $activate ) {
			switch_theme( $slug );
			$result['activated'] = ( get_stylesheet() === $slug );
		}

		return $this->success_response( 'Theme created successfully', $result );
	}

	private function create_classic_theme_files( $theme_dir, &$files_created ) {
		$index_content = "<?php\n// Silence is golden.\nget_header();\nthe_content();\nget_footer();\n";
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- TODO: possibly migrate to WP_Filesystem later
		file_put_contents( $theme_dir . '/index.php', $index_content );
		$files_created[] = 'index.php';
	}

	private function create_block_theme_files( $theme_dir, &$files_created ) {
		wp_mkdir_p( $theme_dir . '/templates' );
		wp_mkdir_p( $theme_dir . '/parts' );
		$files_created[] = 'templates/';
		$files_created[] = 'parts/';

		// phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- Using json_encode() directly to avoid wp_json_encode_options filter interference; theme.json must have predictable format.
		$theme_json = json_encode(
			array(
				'$schema'  => 'https://schemas.wp.org/trunk/theme.json',
				'version'  => 2,
				'settings' => new \stdClass(),
			),
			JSON_PRETTY_PRINT
		);
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- TODO: possibly migrate to WP_Filesystem later
		file_put_contents( $theme_dir . '/theme.json', $theme_json );
		$files_created[] = 'theme.json';

		$index_html = "<!-- wp:template-part {\"slug\":\"header\"} /-->\n<!-- wp:post-content /-->\n<!-- wp:template-part {\"slug\":\"footer\"} /-->";
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- TODO: possibly migrate to WP_Filesystem later
		file_put_contents( $theme_dir . '/templates/index.html', $index_html );
		$files_created[] = 'templates/index.html';
	}

	private function cleanup_directory( $dir ) {
		$files = array_diff( scandir( $dir ), array( '.', '..' ) );
		foreach ( $files as $file ) {
			$path = $dir . DIRECTORY_SEPARATOR . $file;
			// phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- TODO: possibly migrate to WP_Filesystem later
			is_dir( $path ) ? $this->cleanup_directory( $path ) : unlink( $path );
		}
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- TODO: possibly migrate to WP_Filesystem later
		rmdir( $dir );
	}
}
