<?php
/**
 * REST API controller: /chat proxy and /config endpoint.
 *
 * @package BOOSAIAS_For_WooCommerce
 */

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

class BOOSAIAS_Rest_Controller {

	private $namespace = 'boosaias/v1';

	public function init() {
		add_action( 'rest_api_init', array( $this, 'register_routes' ) );
	}

	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/chat',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'handle_chat' ),
				'permission_callback' => '__return_true',
			)
		);

		register_rest_route(
			$this->namespace,
			'/config',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'handle_config' ),
				'permission_callback' => '__return_true',
			)
		);

		register_rest_route(
			$this->namespace,
			'/lead',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'handle_lead' ),
				'permission_callback' => '__return_true',
			)
		);
	}

	public function handle_chat( WP_REST_Request $request ) {
		if ( ! $this->verify_nonce( $request ) ) {
			return new WP_REST_Response( array( 'error' => array( 'code' => 'unauthorized', 'message' => 'Invalid nonce.' ) ), 401 );
		}

		if ( ! $this->check_rate_limit() ) {
			return new WP_REST_Response(
				array( 'error' => array( 'code' => 'rate_limited', 'message' => 'Too many requests.' ) ),
				429
			);
		}

		$body = array(
			'conversation_id' => sanitize_text_field( $request->get_param( 'conversation_id' ) ?? '' ),
			'message'         => sanitize_text_field( $request->get_param( 'message' ) ?? '' ),
			'page_url'        => esc_url_raw( $request->get_param( 'page_url' ) ?? '' ),
		);

		if ( empty( $body['message'] ) ) {
			return new WP_REST_Response( array( 'error' => array( 'code' => 'bad_request', 'message' => 'Message is required.' ) ), 400 );
		}

		$client   = new BOOSAIAS_Api_Client();
		$response = $client->post( '/api/chat', $body, 15 );

		if ( is_wp_error( $response ) ) {
			return new WP_REST_Response( array( 'error' => array( 'code' => 'internal', 'message' => 'Backend unavailable.' ) ), 502 );
		}

		$code = wp_remote_retrieve_response_code( $response );
		$data = json_decode( wp_remote_retrieve_body( $response ), true );

		return new WP_REST_Response( $data, $code );
	}

	public function handle_config( WP_REST_Request $request ) {
		$license_data = get_transient( 'boosaias_license_data' );
		$plan         = is_array( $license_data ) ? ( $license_data['plan'] ?? 'free' ) : 'free';

		return new WP_REST_Response( array(
			'welcomeMessage' => get_option( 'boosaias_welcome_message', '' ),
			'widgetColor'    => get_option( 'boosaias_widget_color', '#2271b1' ),
			'language'       => get_option( 'boosaias_language', 'uk' ),
			'plan'           => $plan,
		) );
	}

	public function handle_lead( WP_REST_Request $request ) {
		if ( ! $this->verify_nonce( $request ) ) {
			return new WP_REST_Response( array( 'error' => array( 'code' => 'unauthorized', 'message' => 'Invalid nonce.' ) ), 401 );
		}

		if ( ! $this->check_rate_limit() ) {
			return new WP_REST_Response(
				array( 'error' => array( 'code' => 'rate_limited', 'message' => 'Too many requests.' ) ),
				429
			);
		}

		$body = array(
			'conversation_id' => sanitize_text_field( $request->get_param( 'conversation_id' ) ?? '' ),
			'name'            => sanitize_text_field( $request->get_param( 'name' ) ?? '' ),
			'contact'         => sanitize_text_field( $request->get_param( 'contact' ) ?? '' ),
			'question'        => sanitize_text_field( $request->get_param( 'question' ) ?? '' ),
			'page_url'        => esc_url_raw( $request->get_param( 'page_url' ) ?? '' ),
		);

		$client   = new BOOSAIAS_Api_Client();
		$response = $client->post( '/api/lead', $body, 15 );

		if ( is_wp_error( $response ) ) {
			return new WP_REST_Response( array( 'error' => array( 'code' => 'internal', 'message' => 'Backend unavailable.' ) ), 502 );
		}

		$code = wp_remote_retrieve_response_code( $response );
		$data = json_decode( wp_remote_retrieve_body( $response ), true );

		return new WP_REST_Response( $data, $code );
	}

	private function verify_nonce( WP_REST_Request $request ) {
		return (bool) wp_verify_nonce( $request->get_header( 'X-WP-Nonce' ), 'wp_rest' );
	}

	private function check_rate_limit() {
		$ip  = $this->get_client_ip();
		$key = 'boosaias_rl_' . md5( $ip );
		$count = (int) get_transient( $key );

		if ( $count >= 20 ) {
			return false;
		}

		if ( 0 === $count ) {
			set_transient( $key, 1, 5 * MINUTE_IN_SECONDS );
		} else {
			set_transient( $key, $count + 1, 5 * MINUTE_IN_SECONDS );
		}

		return true;
	}

	private function get_client_ip() {
		// Only trust CF-Connecting-IP (Cloudflare-specific, cannot be spoofed client-side).
		// HTTP_X_FORWARDED_FOR is intentionally ignored — it can be injected by the client.
		if ( ! empty( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ) {
			return sanitize_text_field( wp_unslash( $_SERVER['HTTP_CF_CONNECTING_IP'] ) );
		}
		return sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ?? '' ) );
	}
}
