<?php
/**
 * Components Page Class
 *
 * Manages components page functionality
 *
 * @package SmartyPress_AI_Engine
 * @since 1.0.0
 */

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

/**
 * Components Page class
 */
class SmartyPress_AI_Components_Page {

	/**
	 * Constructor
	 */
	public function __construct() {
		// Register REST API routes
		add_action( 'rest_api_init', array( $this, 'register_rest_routes' ), 10 );
	}

	/**
	 * Register REST API routes
	 */
	public function register_rest_routes() {
		// Get modules list
		register_rest_route(
			'smartypress/v1',
			'/modules',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_modules' ),
				'permission_callback' => array( $this, 'check_permissions' ),
			)
		);

		// Toggle module
		register_rest_route(
			'smartypress/v1',
			'/modules/(?P<module_id>[a-zA-Z0-9_-]+)/toggle',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'toggle_module' ),
				'permission_callback' => array( $this, 'check_permissions' ),
				'args'                => array(
					'module_id' => array(
						'required' => true,
						'type'     => 'string',
					),
					'enabled'   => array(
						'required' => true,
						'type'     => 'boolean',
					),
				),
			)
		);
	}

	/**
	 * Get modules list
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response|WP_Error
	 */
	public function get_modules( $request ) {
		global $smartypress_ai_plugin;
		$module_manager = $smartypress_ai_plugin ? $smartypress_ai_plugin->get_module_manager() : null;
		if ( ! $module_manager ) {
			return new WP_Error( 'no_module_manager', __( 'Module manager not available', 'smartypress-ai-engine' ), array( 'status' => 500 ) );
		}

		$modules_info = $module_manager->get_available_modules_info();

		return rest_ensure_response( $modules_info );
	}

	/**
	 * Toggle module
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response|WP_Error
	 */
	public function toggle_module( $request ) {
		$module_id = $request->get_param( 'module_id' );
		$enabled   = $request->get_param( 'enabled' );

		global $smartypress_ai_plugin;
		$settings_manager = $smartypress_ai_plugin ? $smartypress_ai_plugin->get_settings_manager() : null;
		if ( ! $settings_manager ) {
			return new WP_Error( 'no_settings_manager', __( 'Settings manager not available', 'smartypress-ai-engine' ), array( 'status' => 500 ) );
		}

		// Update module setting
		$settings_manager->update_module_setting( $module_id, 'enabled', $enabled );

		// Clear any caches if needed
		do_action( 'smartypress_ai_module_toggled', $module_id, $enabled );

		return rest_ensure_response(
			array(
				'success' => true,
				'module_id' => $module_id,
				'enabled' => $enabled,
			)
		);
	}

	/**
	 * Check permissions
	 *
	 * @return bool
	 */
	public function check_permissions() {
		return current_user_can( 'manage_options' );
	}
}

