<?php
/**
 * Ability: wp-agent/disable-power
 *
 * Panic switch living in the CORE plugin so the verified core can shut the
 * Developer/Staging power mode (wp-agent-power) off even if that plugin
 * misbehaves. Functional: the execute callback deactivates the wp-agent-power
 * plugin via deactivate_plugins(), so exec-php and every other power ability is
 * unregistered from the next request on. It lives in the core plugin by design,
 * so the kill-switch survives even a misbehaving power plugin.
 *
 * @package WPAgentCompanion
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

function wpagent_ability_disable_power(): array {
	return array(
		'label'               => __( 'Developer-/Staging-Modus abschalten (Panik)', 'wp-agent-companion' ),
		'description'         => __( 'Panik-Schalter im Kern-Plugin. Deaktiviert den Roh-Zugriffs-Modus (wp-agent-power) sofort, falls installiert.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type' => 'object',
		),
		'output_schema'       => array(
			'type'       => 'object',
			'properties' => array(
				'power_installed' => array( 'type' => 'boolean' ),
				'disabled'        => array( 'type' => 'boolean' ),
				'note'            => array( 'type' => 'string' ),
			),
		),
		'execute_callback'    => 'wpagent_exec_disable_power',
		'permission_callback' => 'wpagent_perm_activate_plugins',
		'meta'                => array(
			'show_in_rest' => true,
			'annotations'  => array(
				'readonly'    => false,
				'destructive' => false,
				'idempotent'  => true,
			),
		),
	);
}

/**
 * @param mixed $input
 * @return array
 */
function wpagent_exec_disable_power( $input = null ) {
	$slug = 'wp-agent-power/wp-agent-power.php';
	if ( ! function_exists( 'is_plugin_active' ) ) {
		require_once ABSPATH . 'wp-admin/includes/plugin.php';
	}
	$installed = is_file( WP_PLUGIN_DIR . '/' . $slug );
	$active    = is_plugin_active( $slug );
	if ( $active ) {
		deactivate_plugins( $slug );
	}

	return array(
		'power_installed' => $installed,
		'disabled'        => true,
		'note'            => $active
			? __( 'wp-agent-power wurde deaktiviert.', 'wp-agent-companion' )
			: (
				$installed
					? __( 'wp-agent-power war bereits deaktiviert.', 'wp-agent-companion' )
					: __( 'wp-agent-power ist nicht installiert; nichts abzuschalten.', 'wp-agent-companion' )
			),
	);
}
