<?php
/**
 * Add Role Tool.
 *
 * Creates a new custom role with specified capabilities. Uses add_role()
 * and persists to database.
 *
 * @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://agenistrator.com/
 *
 * 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' ) ) {
	exit;
}

/**
 * Add_Role_Tool class.
 */
class Add_Role_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Create a new custom role with specified 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(
				'role_slug'    => array(
					'type'        => 'string',
					'description' => 'The role slug (machine name, lowercase with underscores)',
				),
				'display_name' => array(
					'type'        => 'string',
					'description' => 'The human-readable display name for the role',
				),
				'capabilities' => array(
					'type'        => 'array',
					'items'       => array( 'type' => 'string' ),
					'description' => 'Array of capability names to grant to this role',
				),
			),
			'required'   => array( 'role_slug', '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 ) {
		$role_slug    = sanitize_key( $args['role_slug'] );
		$display_name = sanitize_text_field( $args['display_name'] );
		$capabilities = (array) ( $args['capabilities'] ?? array() );

		if ( empty( $role_slug ) ) {
			return $this->error_response( 'Role slug is required' );
		}

		$wp_roles = wp_roles();
		if ( isset( $wp_roles->roles[ $role_slug ] ) ) {
			return $this->error_response( 'Role already exists: ' . $role_slug );
		}

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

		// Build capabilities array
		$caps = array();
		foreach ( $filtered_capabilities as $cap ) {
			$caps[ sanitize_key( $cap ) ] = true;
		}

		$result = add_role( $role_slug, $display_name, $caps );

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

		$response_data = array(
			'slug'             => $role_slug,
			'name'             => $display_name,
			'capabilities'     => array_keys( $caps ),
			'capability_count' => count( $caps ),
		);

		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 created successfully', $response_data );
	}
}
