<?php
/**
 * Finalize usage AJAX handler module for SiteStaffr widget.
 *
 * @package SiteStaffr
 */

class SiteStaffr_Widget_Finalize_Usage_Handler {

	/**
	 * AJAX handler for usage finalization.
	 *
	 * Sends finalized conversation duration to middleware billing endpoint.
	 *
	 * @since 0.14.2
	 * @param SiteStaffr_Widget $widget Widget instance.
	 * @param callable         $get_api_secret Callback returning API secret.
	 * @return void
	 */
	public static function ajax_finalize_usage( SiteStaffr_Widget $widget, callable $get_api_secret ) {
		// Security guard: nonce only.
		SiteStaffr_Public_Request_Guards::enforce_public_guards( array(
			'nonce_action' => 'sitestaffr_finalize_usage',
		) );

		$session_id = SiteStaffr_Public_Request_Guards::get_post_text_field( 'session_id' );
		$duration = SiteStaffr_Public_Request_Guards::get_post_absint( 'duration' );
		$contact_email = SiteStaffr_Public_Request_Guards::get_post_text_field( 'contact_email' );
		$contact_phone = SiteStaffr_Public_Request_Guards::get_post_text_field( 'contact_phone' );

		if ( empty( $session_id ) ) {
			wp_send_json_error( array(
				'message' => SiteStaffr_Public_Middleware_Client::msg_missing_required_field_session_id(),
			), 400 );
			return;
		}

		$account_id = get_option( 'sitestaffr_account_id', '' );
		$installation_id = get_option( 'sitestaffr_installation_id', '' );

		if ( empty( $account_id ) || empty( $installation_id ) ) {
			SiteStaffr_Logger::legacy( SiteStaffr_Public_Middleware_Client::log_prefix_finalize_usage() . 'Missing account_id or installation_id' );
			wp_send_json_error( array(
				'message' => SiteStaffr_Public_Middleware_Client::msg_billing_not_initialized_for_site(),
			), 412 );
			return;
		}

		$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_finalize_usage() . 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;
		}

		$middleware_url = $preflight_config['middleware_url'];
		if ( $preflight_config['missing_middleware_url'] ) {
			SiteStaffr_Logger::legacy( SiteStaffr_Public_Middleware_Client::log_prefix_finalize_usage() . 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;
		}

		$payload_array = SiteStaffr_Public_Middleware_Client::build_finalize_usage_payload(
			$account_id,
			$installation_id,
			$session_id,
			$duration,
			get_site_url()
		);

		$payload_json = wp_json_encode( $payload_array );

		$finalize_operation = SiteStaffr_Public_Middleware_Client::finalize_usage_request(
			$middleware_url,
			$payload_json,
			$api_secret
		);

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

		if ( ! $finalize_operation['ok'] ) {
			SiteStaffr_Logger::legacy(
				sprintf(
					SiteStaffr_Public_Middleware_Client::log_prefix_finalize_usage() . SiteStaffr_Public_Middleware_Client::log_fmt_middleware_returned_status_body(),
					$finalize_operation['status_body_for_log']
				)
			);
			wp_send_json_error( $finalize_operation['error_payload'], $finalize_operation['status_code'] );
			return;
		}

		$conversation_success = SiteStaffr_Public_Middleware_Client::build_conversation_success_payload(
			$account_id,
			$installation_id,
			$session_id,
			get_site_url(),
			$contact_email,
			$contact_phone
		);

		if ( ! $conversation_success['success'] ) {
			SiteStaffr_Logger::warning( '[ConversationSuccess] not firing: no valid contact' );
			wp_send_json_success( $finalize_operation['success_payload'] );
			return;
		}

		$conversation_success_payload_json = wp_json_encode( $conversation_success['payload'] );
		if ( false !== $conversation_success_payload_json ) {
			$conversation_success_operation = SiteStaffr_Public_Middleware_Client::conversation_success_request(
				$middleware_url,
				$conversation_success_payload_json,
				$api_secret
			);

			if ( ! $conversation_success_operation['ok'] ) {
				if ( 'request_error' === $conversation_success_operation['result'] ) {
					SiteStaffr_Logger::warning(
						SiteStaffr_Public_Middleware_Client::log_prefix_conversation_success()
						. SiteStaffr_Public_Middleware_Client::log_suffix_request_failed()
						. $conversation_success_operation['error_message']
					);
				} else {
					SiteStaffr_Logger::warning(
						sprintf(
							SiteStaffr_Public_Middleware_Client::log_prefix_conversation_success() . SiteStaffr_Public_Middleware_Client::log_fmt_middleware_returned_status_body(),
							$conversation_success_operation['status_body_for_log']
						)
					);
				}
			}
		}

		wp_send_json_success( $finalize_operation['success_payload'] );
	}
}
