<?php
/**
 * Delete Theme File Tool.
 *
 * Delete a file from a theme directory with path validation to prevent
 * deletion outside theme directory.
 *
 * @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;
}

/**
 * Delete_Theme_File_Tool class.
 */
class Delete_Theme_File_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Delete a file from a theme directory (cannot delete style.css).';
	}

	/**
	 * 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(
				'theme' => array(
					'type'        => 'string',
					'description' => 'Theme stylesheet (directory name) or theme name',
				),
				'file'  => array(
					'type'        => 'string',
					'description' => 'Relative path to the file to delete within the theme directory',
				),
			),
			'required'   => array( 'theme', 'file' ),
		);
	}

	/**
	 * 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( 'edit_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( 'capability_edit_themes' ) ) {
			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['theme'] ) || empty( trim( $args['theme'] ) ) ) {
			return $this->error_response( 'Theme identifier is required' );
		}
		if ( ! isset( $args['file'] ) || empty( trim( $args['file'] ) ) ) {
			return $this->error_response( 'File path is required' );
		}

		$theme_slug = sanitize_text_field( $args['theme'] );
		$file       = $args['file'];

		$theme = wp_get_theme( $theme_slug );

		// If not found by stylesheet, search by name
		if ( ! $theme->exists() ) {
			$all_themes = wp_get_themes();
			foreach ( $all_themes as $stylesheet => $t ) {
				if ( stripos( $t->get( 'Name' ), $theme_slug ) !== false ) {
					$theme      = $t;
					$theme_slug = $stylesheet;
					break;
				}
			}
		}

		if ( ! $theme->exists() ) {
			return $this->error_response( "Theme not found: {$theme_slug}" );
		}

		$theme_dir = $theme->get_stylesheet_directory();
		$file_path = $theme_dir . DIRECTORY_SEPARATOR . $file;

		// Validate file path is within theme directory
		$real_file_path = realpath( $file_path );
		$real_theme_dir = realpath( $theme_dir );
		if ( false === $real_file_path ) {
			return $this->error_response( 'File does not exist' );
		}
		if ( ! PHP_Utils::is_path_within( $real_file_path, $real_theme_dir ) ) {
			return $this->error_response( 'Invalid file path' );
		}

		// Prevent deletion of style.css (required for theme)
		if ( basename( $real_file_path ) === 'style.css' && dirname( $real_file_path ) === $real_theme_dir ) {
			return $this->error_response( 'Cannot delete style.css. Use uninstall_theme to remove the entire theme.' );
		}

		if ( ! is_file( $real_file_path ) ) {
			return $this->error_response( 'Path is not a file' );
		}

		// Delete the file
		// phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- TODO: possibly migrate to WP_Filesystem later
		if ( ! unlink( $real_file_path ) ) {
			return $this->error_response( 'Failed to delete file' );
		}

		return $this->success_response(
			'File deleted successfully',
			array(
				'theme' => $theme_slug,
				'file'  => $file,
			)
		);
	}
}
