<?php
/**
 * Capture Leads via AI (Premium Module)
 *
 * @package Replyan_AI
 */

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

final class Replyan_AI_Capture_Leads {
	public function register_hooks(): void {
		add_filter( 'replyan_ai_system_prompt', array( $this, 'override_prompt_for_extraction' ), 99, 2 );
		add_filter( 'replyan_ai_parse_response', array( $this, 'trigger_background_extraction' ), 10, 2 );
		add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) );
	}

	public function register_rest_routes(): void {
		register_rest_route(
			'replyan/v1',
			'/extract',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'rest_extract_leads' ),
				'permission_callback' => function( WP_REST_Request $request ) {
					$session_id = sanitize_text_field( wp_unslash( $request->get_param( 'session_id' ) ?? '' ) );
					$token      = sanitize_text_field( wp_unslash( $request->get_param( '_internal_token' ) ?? '' ) );

					if ( empty( $session_id ) || empty( $token ) ) {
						return false;
					}

					return hash_equals( wp_hash( 'replyan_extraction_' . $session_id ), $token );
				},
			)
		);
	}

	public function override_prompt_for_extraction( string $system_prompt, string $session_id ): string {
		// Only override when it's our background REST request
		// phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		if ( isset( $_POST['replyan_ai_is_extraction'] ) && $_POST['replyan_ai_is_extraction'] ) {
			return "You are a precise data extraction bot. Extract the customer's first name, last name, email, and phone number from their message. Return ONLY a valid JSON object in this EXACT format, and absolutely nothing else:\n{\"first_name\":\"\", \"last_name\":\"\", \"email\":\"\", \"phone\":\"\"}\nLeave missing values empty. Do not include markdown code blocks.";
		}
		return $system_prompt;
	}

	public function trigger_background_extraction( string $reply, string $session_id ): string {
		if ( ! $session_id ) {
			return $reply;
		}

		$is_intercepted = apply_filters( 'replyan_ai_intercept_message', false, $session_id );
		if ( $is_intercepted ) {
			return $reply;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Missing
		$user_message = isset( $_POST['message'] ) ? sanitize_text_field( wp_unslash( $_POST['message'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Missing
		$agent_id     = isset( $_POST['agent_id'] ) ? sanitize_text_field( wp_unslash( $_POST['agent_id'] ) ) : 0;

		if ( empty( $user_message ) ) {
			$request_body = file_get_contents( 'php://input' );
			if ( $request_body ) {
				$decoded = json_decode( $request_body, true );
				if ( is_array( $decoded ) ) {
					$user_message = sanitize_text_field( $decoded['message'] ?? '' );
					$agent_id     = sanitize_text_field( $decoded['agent_id'] ?? 0 );
				}
			}
		}

		if ( empty( $user_message ) ) {
			return $reply;
		}

		if ( class_exists( 'Replyan_AI_Logs' ) ) {
			Replyan_AI_Logs::log( "Triggering background REST extraction for session: {$session_id}" );
		}

		// Fire an incredibly fast non-blocking request to our REST API
		wp_remote_post( rest_url( 'replyan/v1/extract' ), array(
			'blocking'  => false,
			'timeout'   => 1,
			'sslverify' => false,
			'headers'   => array(
				'Content-Type' => 'application/json',
			),
			'body'      => wp_json_encode( array(
				'session_id'      => $session_id,
				'agent_id'        => $agent_id,
				'message'         => $user_message,
				'_internal_token' => wp_hash( 'replyan_extraction_' . $session_id ),
			) ),
		) );

		return $reply;
	}

	public function rest_extract_leads( WP_REST_Request $request ) {
		$session_id   = sanitize_text_field( wp_unslash( $request->get_param( 'session_id' ) ?? '' ) );
		$user_message = sanitize_text_field( wp_unslash( $request->get_param( 'message' ) ?? '' ) );
		
		if ( ! $session_id || ! $user_message ) {
			return new WP_Error( 'missing_params', 'Missing session or message', array( 'status' => 400 ) );
		}

		// if ( class_exists( 'Replyan_AI_Logs' ) ) {
		// 	Replyan_AI_Logs::log( "Background REST extraction started for message: {$user_message}" );
		// }

		if ( ! class_exists( 'Replyan_AI_AJAX' ) ) {
			require_once REPLYAN_AI_DIR . 'includes/class-replyan-ai-ajax.php';
		}

		$ajax = new Replyan_AI_AJAX();
		$settings = class_exists( 'Replyan_AI_Settings' ) ? Replyan_AI_Settings::get() : get_option( 'replyan_ai_admin_settings', array() );

		$agent_id = (int) ( $request->get_param( 'agent_id' ) ?? 0 );

		// Set extraction flag so the system prompt override filter fires.
		// phpcs:ignore WordPress.Variables.GlobalVariables.OverrideProhibited
		$_POST['replyan_ai_is_extraction'] = true;

		$response = $ajax->send_to_provider( $settings, $user_message, array(), $session_id, $agent_id );

		if ( is_wp_error( $response ) ) {
			if ( class_exists( 'Replyan_AI_Logs' ) ) {
				Replyan_AI_Logs::log( "REST BG Extraction Provider error: " . $response->get_error_message() );
			}
			return rest_ensure_response( array( 'success' => false ) );
		}

		$status_code = wp_remote_retrieve_response_code( $response );
		$body        = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( 200 > $status_code || 299 < $status_code ) {
			// if ( class_exists( 'Replyan_AI_Logs' ) ) {
			// 	Replyan_AI_Logs::log( "REST BG Extraction API Error code " . $status_code );
			// }
			return rest_ensure_response( array( 'success' => false ) );
		}

		$extraction_reply = '';
		if ( isset( $body['choices'][0]['message']['content'] ) ) {
			$extraction_reply = $body['choices'][0]['message']['content'];
		} elseif ( isset( $body['content'][0]['text'] ) ) {
			$extraction_reply = $body['content'][0]['text'];
		} elseif ( isset( $body['candidates'][0]['content']['parts'][0]['text'] ) ) {
			$extraction_reply = $body['candidates'][0]['content']['parts'][0]['text'];
		}
		// if ( class_exists( 'Replyan_AI_Logs' ) ) {
		// 	Replyan_AI_Logs::log( "REST BG Extraction Reply: " . $extraction_reply );
		// }
		// Clean up potential markdown formatting from AI output
		$cleaned_reply = preg_replace( '/```json\s*(.*?)\s*```/is', '$1', $extraction_reply );
		$cleaned_reply = trim( $cleaned_reply );

		$json_data = json_decode( $cleaned_reply, true );

		if ( json_last_error() !== JSON_ERROR_NONE ) {
			if ( class_exists( 'Replyan_AI_Logs' ) ) {
				Replyan_AI_Logs::log( "REST BG Extraction JSON Decode Error: " . json_last_error_msg() );
			}
		} elseif ( is_array( $json_data ) ) {
			$has_valid_keys = !empty($json_data['first_name']) || !empty($json_data['last_name']) || !empty($json_data['email']) || !empty($json_data['phone']);
			
			if ( $has_valid_keys && class_exists( 'Replyan_AI_Leads' ) ) {
				$saved = Replyan_AI_Leads::db_save_lead( $session_id, $json_data );
				// if ( class_exists( 'Replyan_AI_Logs' ) ) {
				// 	Replyan_AI_Logs::log( "REST BG Extraction: db_save_lead called. Result: " . ( $saved ? 'true' : 'false' ) );
				// }
			}
		}

		return rest_ensure_response( array( 'success' => true ) );
	}
}
