<?php
/**
 * Realtime session AJAX handler module for SiteStaffr widget.
 *
 * @package SiteStaffr
 */

class SiteStaffr_Widget_Realtime_Session_Handler {

	/**
	 * AJAX handler for realtime session provisioning.
	 *
	 * @since 0.13.22
	 * @param SiteStaffr_Widget $widget Widget instance.
	 * @param string           $ip_address Client IP address.
	 * @param callable         $get_api_secret Callback returning API secret.
	 * @param callable         $get_realtime_custom_instructions Callback returning custom instructions.
	 * @param callable         $enrich_realtime_business_info Callback enriching business info payload.
	 * @return void
	 */
	public static function ajax_get_realtime_session( SiteStaffr_Widget $widget, $ip_address, callable $get_api_secret, callable $get_realtime_custom_instructions, callable $enrich_realtime_business_info ) {
		// Security guards: nonce, honeypot, ban, per-IP rate limit.
		SiteStaffr_Public_Request_Guards::enforce_public_guards( array(
			'nonce_action' => 'sitestaffr_realtime_session',
			'ip'           => $ip_address,
			'honeypot'     => true,
			'ban_check'    => true,
			'rate_limit'   => 20,
		) );

		// Get API secret for HMAC signature (per-site or global)
		$preflight_config = SiteStaffr_Public_Middleware_Client::get_public_preflight_config( $get_api_secret() );
		$api_secret = $preflight_config['api_secret'];
		if ( $preflight_config['missing_api_secret'] ) {
			SiteStaffr_Logger::legacy( SiteStaffr_Public_Middleware_Client::log_prefix_realtime_session_ajax() . SiteStaffr_Public_Middleware_Client::log_suffix_missing_api_secret() );
			wp_send_json_error( array(
				'message' => SiteStaffr_Public_Middleware_Client::msg_config_missing_api_secret(),
			), SiteStaffr_Public_Middleware_Client::http_500() );
			return;
		}

		// Get site token
		$site_token = get_option( 'sitestaffr_site_token' );
		if ( empty( $site_token ) ) {
			SiteStaffr_Logger::legacy( SiteStaffr_Public_Middleware_Client::log_prefix_realtime_session_ajax() . SiteStaffr_Public_Middleware_Client::log_suffix_missing_site_token() );
			wp_send_json_error( array(
				'message' => SiteStaffr_Public_Middleware_Client::msg_config_missing_site_token(),
			), SiteStaffr_Public_Middleware_Client::http_500() );
			return;
		}
		$account_id = get_option( 'sitestaffr_account_id', '' );
		$installation_id = get_option( 'sitestaffr_installation_id', '' );

		// Fetch business info locally (avoid middleware → WordPress callback)
		$saved_settings = get_option( 'sitestaffr_settings', array() );
		$widget_settings = SiteStaffr_Widget_Settings_Provider::get_widget_settings();

		$business_info = array(
			'business_name'        => isset( $saved_settings['business_name'] ) ? $saved_settings['business_name'] : '',
			'business_description' => isset( $saved_settings['business_context'] ) ? $saved_settings['business_context'] : '',
			'business_hours'       => isset( $saved_settings['business_hours'] ) ? $saved_settings['business_hours'] : '',
			'business_phone'       => isset( $saved_settings['business_phone'] ) ? $saved_settings['business_phone'] : '',
			'custom_greeting'      => isset( $saved_settings['custom_greeting'] ) ? sanitize_text_field( $saved_settings['custom_greeting'] ) : '',
			'custom_greeting_tone' => isset( $saved_settings['custom_greeting_tone'] ) ? sanitize_key( $saved_settings['custom_greeting_tone'] ) : 'warm_neutral',
			'custom_instructions'       => $get_realtime_custom_instructions( $saved_settings ),
			'custom_instructions_user'  => SiteStaffr_Business_Enrichment::get_user_custom_instructions(),
			'ai_voice'             => isset( $widget_settings['ai_voice'] ) ? $widget_settings['ai_voice'] : 'marin',
			'notification_email'       => ! empty( $saved_settings['notification_email'] ) ? $saved_settings['notification_email'] : get_option( 'admin_email' ),
			'collect_contact'          => isset( $saved_settings['ai_collect_contact'] ) ? (bool) $saved_settings['ai_collect_contact'] : true,
			'disregard_personal_info'  => isset( $saved_settings['ai_disregard_personal_info'] ) ? (bool) $saved_settings['ai_disregard_personal_info'] : false,
		);
		$business_info = $enrich_realtime_business_info( $business_info );
		$business_info = SiteStaffr_Business_Enrichment::attach_hot_chunks( $business_info, 'voice' );

		// Build request body with business info included
		$request_body = SiteStaffr_Public_Middleware_Client::build_realtime_session_request_body(
			$site_token,
			get_site_url(),
			$business_info,
			sanitize_text_field( $account_id ),
			sanitize_text_field( $installation_id )
		);

		// Build signed request payload
		$payload = wp_json_encode( $request_body );

		// Make authenticated request to middleware
		$middleware_url = $preflight_config['middleware_url'];
		if ( $preflight_config['missing_middleware_url'] ) {
			SiteStaffr_Logger::legacy( SiteStaffr_Public_Middleware_Client::log_prefix_realtime_session_ajax() . SiteStaffr_Public_Middleware_Client::log_suffix_missing_middleware_url() );
			wp_send_json_error( array(
				'message' => SiteStaffr_Public_Middleware_Client::msg_config_missing_middleware_url(),
			), SiteStaffr_Public_Middleware_Client::http_500() );
			return;
		}

		$realtime_operation = SiteStaffr_Public_Middleware_Client::realtime_session_request(
			$middleware_url,
			$payload,
			$api_secret
		);

		if ( 'request_error' === $realtime_operation['result'] ) {
			SiteStaffr_Logger::legacy(
				SiteStaffr_Public_Middleware_Client::log_prefix_realtime_session_ajax() .
				SiteStaffr_Public_Middleware_Client::log_suffix_request_failed() .
				$realtime_operation['error_message']
			);
			wp_send_json_error( $realtime_operation['error_payload'], $realtime_operation['status_code'] );
			return;
		}

		if ( 'middleware_error' === $realtime_operation['result'] ) {
			SiteStaffr_Logger::legacy( sprintf(
				SiteStaffr_Public_Middleware_Client::log_prefix_realtime_session_ajax() . SiteStaffr_Public_Middleware_Client::log_fmt_middleware_returned_status_body(),
				$realtime_operation['status_body_for_log']
			) );
			wp_send_json_error( $realtime_operation['error_payload'], $realtime_operation['status_code'] );
			return;
		}

		if ( 'invalid_json' === $realtime_operation['result'] ) {
			SiteStaffr_Logger::legacy( SiteStaffr_Public_Middleware_Client::log_prefix_realtime_session_ajax() . SiteStaffr_Public_Middleware_Client::log_suffix_invalid_json_response_from_middleware() );
			wp_send_json_error( $realtime_operation['error_payload'], $realtime_operation['status_code'] );
			return;
		}

		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			SiteStaffr_Logger::legacy( sprintf(
				SiteStaffr_Public_Middleware_Client::log_prefix_realtime_session_ajax() . 'Session created successfully for IP %s',
				$ip_address
			) );
		}

		wp_send_json_success( $realtime_operation['success_payload'], $realtime_operation['status_code'] );
	}
}
