<?php
/**
 * API Handler Trait.
 *
 * @package automation-web-platform
 */

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

/**
 * Trait WAWP_API_Handler.
 * Provides boilerplate for handling AJAX and REST API requests securely.
 */
trait WAWP_API_Handler {

	/**
	 * Send JSON success response.
	 *
	 * @param string $message Success message.
	 * @param array  $data    Extra data.
	 */
	protected function send_success( $message = '', $data = array() ) {
		$response = array( 'success' => true );
		if ( $message ) {
			$response['message'] = $message;
		}
		if ( ! empty( $data ) ) {
			$response['data'] = $data;
		}

		if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
			return rest_ensure_response( $response );
		}

		wp_send_json_success( $response );
	}

	/**
	 * Send JSON error response.
	 *
	 * @param string $message Error message.
	 * @param int    $code    HTTP status code.
	 * @param array  $data    Extra data.
	 */
	protected function send_error( $message, $code = 400, $data = array() ) {
		$response = array(
			'success' => false,
			'message' => $message,
		);
		if ( ! empty( $data ) ) {
			$response['data'] = $data;
		}

		if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
			return new WP_Error(
				'wawp_rest_error',
				$message,
				array(
					'status' => $code,
					'data'   => $data,
				)
			);
		}

		wp_send_json_error( $response, $code );
	}

	/**
	 * Verify standard WordPress nonce.
	 *
	 * @param string $action Nonce action name.
	 * @param string $key    Nonce field key.
	 * @return bool
	 */
	protected function verify_nonce( $action, $key = 'security' ) {
		if ( ! isset( $_REQUEST[ $key ] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_REQUEST[ $key ] ) ), $action ) ) {
			$this->send_error( esc_html__( 'Invalid security token.', 'automation-web-platform' ), 403 );
			return false;
		}
		return true;
	}

	/**
	 * Check if current user has standard WAWP management capabilities.
	 *
	 * @return bool
	 */
	protected function verify_admin_capability() {
		if ( ! current_user_can( WAWP_CAPABILITY ) ) {
			$this->send_error( esc_html__( 'Insufficient permissions.', 'automation-web-platform' ), 403 );
			return false;
		}
		return true;
	}

	/**
	 * Handle API Request dynamically.
	 *
	 * @param string|WP_REST_Request $request Request data.
	 * @param string                 $method  Method name to call.
	 * @return mixed
	 * @throws \Exception If the API method is invalid.
	 */
	protected function handle_api_request( $request, $method ) {
		try {
			if ( ! method_exists( $this, $method ) ) {
				throw new \Exception( esc_html__( 'Invalid API method.', 'automation-web-platform' ) );
			}

			// Parse data.
			$data = array();
			if ( is_a( $request, 'WP_REST_Request' ) ) {
				$data = $request->get_params();
			} else {
				$data = filter_input_array( INPUT_POST, FILTER_DEFAULT );
				if ( ! $data ) {
					$data = filter_input_array( INPUT_GET, FILTER_DEFAULT );
				}
				$data = $data ? $data : array();
			}

			$result = $this->$method( $data );

			if ( is_wp_error( $result ) ) {
				return $this->send_error( $result->get_error_message(), 400, $result->get_error_data() );
			}

			if ( is_array( $result ) ) {
				if ( isset( $result['success'] ) && ! $result['success'] ) {
					return $this->send_error( $result['message'] ?? esc_html__( 'Action failed.', 'automation-web-platform' ) );
				}
				return $this->send_success( $result['message'] ?? '', $result );
			}

			return $this->send_success();

		} catch ( \Exception $e ) {
			return $this->send_error( $e->getMessage() );
		}
	}
}
