<?php
/**
 * Clone Role Tool.
 *
 * Clones an existing role to create a new one with the same capabilities.
 * Useful for creating customized variations of standard roles.
 *
 * @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;
}

/**
 * Clone_Role_Tool class.
 */
class Clone_Role_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Clone an existing role to create a new one with the same capabilities.';
	}

	/**
	 * 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(
				'source_role'      => array(
					'type'        => 'string',
					'description' => 'The role slug to clone from',
				),
				'new_role_slug'    => array(
					'type'        => 'string',
					'description' => 'The slug for the new role',
				),
				'new_display_name' => array(
					'type'        => 'string',
					'description' => 'The display name for the new role',
				),
			),
			'required'   => array( 'source_role', 'new_role_slug', 'new_display_name' ),
		);
	}

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

	/**
	 * 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 ) {
		$source_role_slug = sanitize_key( $args['source_role'] );
		$new_role_slug    = sanitize_key( $args['new_role_slug'] );
		$new_display_name = sanitize_text_field( $args['new_display_name'] );

		$wp_roles = wp_roles();

		if ( ! isset( $wp_roles->roles[ $source_role_slug ] ) ) {
			return $this->error_response( 'Source role not found: ' . $source_role_slug );
		}

		if ( isset( $wp_roles->roles[ $new_role_slug ] ) ) {
			return $this->error_response( 'New role slug already exists: ' . $new_role_slug );
		}

		$source_capabilities = $wp_roles->roles[ $source_role_slug ]['capabilities'];
		$source_granted_caps = array_keys( array_filter( $source_capabilities ) );

		// Filter out capabilities that require super admin in multisite
		$filtered_capabilities = WordPress_Utils::filter_grantable_capabilities( $source_granted_caps );
		$blocked_capabilities  = array_diff( $source_granted_caps, $filtered_capabilities );

		// Build capabilities array for the new role
		$new_caps = array();
		foreach ( $filtered_capabilities as $cap ) {
			$new_caps[ $cap ] = true;
		}

		$result = add_role( $new_role_slug, $new_display_name, $new_caps );

		if ( null === $result ) {
			return $this->error_response( 'Failed to create cloned role' );
		}

		$response_data = array(
			'source_role' => $source_role_slug,
			'new_role'    => array(
				'slug'             => $new_role_slug,
				'name'             => $new_display_name,
				'capabilities'     => $filtered_capabilities,
				'capability_count' => count( $filtered_capabilities ),
			),
		);

		if ( ! empty( $blocked_capabilities ) ) {
			$response_data['blocked_capabilities'] = $blocked_capabilities;
			$response_data['blocked_reason']       = 'These capabilities require super admin privileges to grant';
		}

		return $this->success_response( 'Role cloned successfully', $response_data );
	}
}
