<?php
/**
 * WordPress Plugin Integration Provider
 *
 * Handles integrations with WordPress plugins through direct object access.
 *
 * @package SureForms
 * @since 1.13.0
 */

namespace SRFM_Pro\Inc\Pro\Native_Integrations;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * WordPress Provider class.
 *
 * @since 1.13.0
 */
class WordPress_Provider extends Integration_Provider {
	/**
	 * Test integration connection by checking if plugin is installed/active
	 *
	 * @param array $credentials User credentials (not used for plugin integrations).
	 * @param array $auth_config Authentication configuration.
	 * @return array Test result.
	 * @since 1.13.0
	 */
	public function test_connection( $credentials, $auth_config = [] ) {
		// Unset parameters as they are not used for plugin integrations.
		unset( $credentials, $auth_config );
		$plugin_detection = $this->config['plugin_detection'] ?? [];

		if ( empty( $plugin_detection['class'] ) && empty( $plugin_detection['constant'] ) ) {
			return [
				'success' => false,
				'message' => __( 'Plugin detection configuration missing.', 'sureforms-pro' ),
			];
		}

		$is_active = $this->is_plugin_active();

		if ( $is_active ) {
			return [
				'success' => true,
				'message' => sprintf(
					// translators: %s: Plugin name from integration config.
					__( '%s plugin is active and ready for integration!', 'sureforms-pro' ),
					$this->config['integration']['name'] ?? 'Plugin'
				),
			];
		}

		return [
			'success' => false,
			'message' => sprintf(
				// translators: %s: Plugin name from integration config.
				__( '%s plugin is not installed or not active.', 'sureforms-pro' ),
				$this->config['integration']['name'] ?? 'Plugin'
			),
		];
	}

	/**
	 * Fetch select options using WordPress filters instead of API calls
	 *
	 * @param array $credentials User credentials (not used for plugin integrations).
	 * @param array $api_config API configuration containing filter information.
	 * @param array $parameters Optional parameters for the filter.
	 * @return array Options array.
	 * @since 1.13.0
	 */
	public function fetch_select_options( $credentials, $api_config, $parameters = [] ) {
		// Unset credentials as they are not used for plugin integrations.
		unset( $credentials );
		if ( empty( $api_config['filter'] ) ) {
			return [];
		}

		$filter_name = $api_config['filter'];

		// Apply WordPress filter for options discovery - using dynamic filter name from config.
		$options = apply_filters( 'srfm_' . $filter_name, [], $parameters, $this->provider_type );

		// Ensure we return an array.
		return is_array( $options ) ? $options : [];
	}

	/**
	 * Fetch dynamic fields using WordPress filters instead of API calls
	 *
	 * @param array $credentials User credentials (not used for plugin integrations).
	 * @param array $api_config API configuration containing filter information.
	 * @param array $parameters Parameters for the filter.
	 * @return array Fields array.
	 * @since 1.13.0
	 */
	public function fetch_dynamic_fields( $credentials, $api_config, $parameters = [] ) {
		// Unset the credentials as they are not used for plugin integrations.
		unset( $credentials );
		if ( empty( $api_config['filter'] ) ) {
			return [];
		}

		$filter_name = $api_config['filter'];

		// Apply WordPress filter for field discovery - using dynamic filter name from config.
		$fields = apply_filters( 'srfm_' . $filter_name, [], $parameters, $this->provider_type );

		// Ensure we return an array.
		return is_array( $fields ) ? $fields : [];
	}

	/**
	 * Check if the target plugin is active
	 *
	 * @return bool True if plugin is active, false otherwise.
	 * @since 1.13.0
	 */
	public function is_plugin_active() {
		$plugin_detection = $this->config['plugin_detection'] ?? [];

		// Check for class-based detection.
		if ( ! empty( $plugin_detection['class'] ) ) {
			return class_exists( $plugin_detection['class'] );
		}

		// Check for constant-based detection.
		if ( ! empty( $plugin_detection['constant'] ) ) {
			return defined( $plugin_detection['constant'] );
		}

		return false;
	}

	/**
	 * Execute plugin action through function call
	 *
	 * @param string $action_name Action to execute.
	 * @param array  $data Form data to process.
	 * @return array Result of action execution.
	 * @since 1.13.0
	 */
	public function execute_action( $action_name, $data ) {
		// Find the action configuration.
		$action_config = $this->get_action_config( $action_name );

		if ( ! $action_config ) {
			return [
				'success' => false,
				'message' => __( 'Action configuration not found.', 'sureforms-pro' ),
			];
		}

		// Check if handler is specified.
		if ( empty( $action_config['handler'] ) ) {
			return [
				'success' => false,
				'message' => __( 'No handler specified for this action.', 'sureforms-pro' ),
			];
		}

		$handler_config = $action_config['handler'];

		// Support for action-based handlers.
		if ( isset( $handler_config['type'] ) && 'action' === $handler_config['type'] && isset( $handler_config['action'] ) ) {
			$action_name = $handler_config['action'];

			try {
				// Initialize global results storage.
				if ( ! isset( $GLOBALS['srfm_action_results'] ) ) {
					$GLOBALS['srfm_action_results'] = [];
				}

				// Execute the WordPress action.
				do_action( 'srfm_' . $action_name, $data );

				// Retrieve the result from global storage.
				$result = $GLOBALS['srfm_action_results'][ 'srfm_' . $action_name ] ?? null;

				if ( null === $result ) {
					return [
						'success' => false,
						'message' => sprintf(
							// translators: %s: Action name.
							__( 'No handler responded to action: %s', 'sureforms-pro' ),
							$action_name
						),
					];
				}

				if ( is_wp_error( $result ) ) {
					return [
						'success' => false,
						'message' => $result->get_error_message(),
					];
				}

				return [
					'success' => true,
					'message' => __( 'Action executed successfully.', 'sureforms-pro' ),
					'data'    => $result,
				];

			} catch ( \Exception $e ) {
				return [
					'success' => false,
					'message' => sprintf(
						// translators: %s: Error message.
						__( 'Action execution failed: %s', 'sureforms-pro' ),
						$e->getMessage()
					),
				];
			}
		}

		return [
			'success' => false,
			'message' => __( 'Invalid handler configuration. Expected action-based handler with type and action specified.', 'sureforms-pro' ),
		];
	}

	/**
	 * Map provider field type to SureForms field type using JSON configuration
	 *
	 * @param string $provider_type Provider field type.
	 * @return string SureForms field type.
	 * @since 1.13.0
	 */
	protected function map_field_type( $provider_type ) {
		$field_mappings = $this->config['field_mappings'] ?? [];
		return $field_mappings[ $provider_type ] ?? 'text';
	}

	/**
	 * Process API response - not used for plugin integrations but required by abstract class
	 *
	 * @param array  $response API response data.
	 * @param string $response_type Type of response to process.
	 * @param array  $config API configuration.
	 * @return array Processed response.
	 * @since 1.13.0
	 */
	protected function process_api_response( $response, $response_type, $config ) {
		// Unet parameters as they are not used for plugin integrations.
		unset( $response_type, $config );
		// Plugin integrations don't use API responses,
		// data is processed directly through filters.
		return is_array( $response ) ? $response : [];
	}

	/**
	 * Get action configuration by name
	 *
	 * @param string $action_name Action name to find.
	 * @return array|null Action configuration or null if not found.
	 * @since 1.13.0
	 */
	private function get_action_config( $action_name ) {
		$actions = $this->config['actions'] ?? [];

		foreach ( $actions as $action ) {
			if ( isset( $action['name'] ) && $action['name'] === $action_name ) {
				return $action;
			}
		}

		return null;
	}
}
