<?php
/**
 * Service class for shared WhatsApp Authentication logic (OTP & Interactive List)
 * Reduces duplication across Login, Registration, and Checkout.
 *
 * @package automation-web-platform
 */

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


/**
 * Class WAWP_WhatsApp_Auth_Service
 */
class WAWP_WhatsApp_Auth_Service {

	/**
	 * Send WhatsApp Authentication (Auto-decides between OTP and Interactive List)
	 *
	 * @param string   $phone Recipient phone number.
	 * @param array    $settings Module settings (login, signup, or checkout).
	 * @param object   $instance The selected instance object.
	 * @param string   $context The calling module context (e.g., 'Signup', 'Login').
	 * @param int|null $user_id Optional User ID for logging.
	 * @return array Standard response [success, wawp_auth_id, whatsapp_auth_type, message].
	 */
	public static function send_auth( $phone, $settings, $instance, $context = 'General', $user_id = null ) {
		if ( ! $instance || empty( $instance->instance_id ) ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'No active WhatsApp instance selected.', 'automation-web-platform' ),
			);
		}

		if ( ! class_exists( 'WAWP_Senders' ) ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'WhatsApp API driver not found.', 'automation-web-platform' ),
			);
		}

		// Normalize settings keys based on prefixes if the generic keys are not directly present.
		$key_mappings = array(
			'whatsapp_auth_type'          => array(
				'wawp_checkout_wa_auth_type',
				'wawp_auth_wa_auth_type',
				'wawp_signup_wa_auth_type',
				'wawp_phone_bar_whatsapp_auth_type',
			),
			'whatsapp_list_title'         => array(
				'wawp_checkout_wa_list_title',
				'wawp_auth_wa_list_title',
				'wawp_signup_wa_list_title',
				'wawp_phone_bar_whatsapp_list_title',
			),
			'whatsapp_list_desc'          => array(
				'wawp_checkout_wa_list_desc',
				'wawp_auth_wa_list_desc',
				'wawp_signup_wa_list_desc',
				'wawp_phone_bar_whatsapp_list_desc',
			),
			'whatsapp_list_footer'        => array(
				'wawp_checkout_wa_list_footer',
				'wawp_auth_wa_list_footer',
				'wawp_signup_wa_list_footer',
				'wawp_phone_bar_whatsapp_list_footer',
			),
			'whatsapp_list_button'        => array(
				'wawp_checkout_wa_list_button',
				'wawp_auth_wa_list_button',
				'wawp_signup_wa_list_button',
				'wawp_phone_bar_whatsapp_list_button',
			),
			'whatsapp_list_item1'         => array(
				'wawp_checkout_wa_list_item1',
				'wawp_auth_wa_list_item1',
				'wawp_signup_wa_list_item1',
				'wawp_phone_bar_whatsapp_list_item1',
			),
			'whatsapp_list_item1_desc'    => array(
				'wawp_checkout_wa_list_item1_desc',
				'wawp_auth_wa_list_item1_desc',
				'wawp_signup_wa_list_item1_desc',
				'wawp_phone_bar_whatsapp_list_item1_desc',
			),
			'whatsapp_list_item2'         => array(
				'wawp_checkout_wa_list_item2',
				'wawp_auth_wa_list_item2',
				'wawp_signup_wa_list_item2',
				'wawp_phone_bar_whatsapp_list_item2',
			),
			'whatsapp_list_item2_desc'    => array(
				'wawp_checkout_wa_list_item2_desc',
				'wawp_auth_wa_list_item2_desc',
				'wawp_signup_wa_list_item2_desc',
				'wawp_phone_bar_whatsapp_list_item2_desc',
			),
			'whatsapp_otp_lang_type'      => array(
				'wawp_checkout_wa_otp_lang_type',
				'wawp_auth_wa_otp_lang_type',
				'wawp_signup_wa_otp_lang_type',
				'wawp_phone_bar_whatsapp_otp_lang_type',
			),
			'whatsapp_otp_custom_lang'    => array(
				'wawp_checkout_wa_otp_custom_lang',
				'wawp_auth_wa_otp_custom_lang',
				'wawp_signup_wa_otp_custom_lang',
				'wawp_phone_bar_whatsapp_otp_custom_lang',
			),
			'whatsapp_otp_footer_enabled' => array(
				'wawp_checkout_wa_otp_foot_en',
				'wawp_auth_wa_otp_foot_en',
				'wawp_signup_wa_otp_foot_en',
				'wawp_phone_bar_whatsapp_otp_footer_enabled',
			),
			'whatsapp_otp_footer'         => array(
				'wawp_checkout_wa_otp_foot',
				'wawp_auth_wa_otp_foot',
				'wawp_signup_wa_otp_foot',
				'wawp_phone_bar_whatsapp_otp_footer',
			),
		);

		foreach ( $key_mappings as $generic_key => $specific_keys ) {
			if ( ! isset( $settings[ $generic_key ] ) || '' === $settings[ $generic_key ] ) {
				foreach ( $specific_keys as $s_key ) {
					if ( isset( $settings[ $s_key ] ) && '' !== $settings[ $s_key ] ) {
						$settings[ $generic_key ] = $settings[ $s_key ];
						break;
					}
				}
			}
		}

		$auth_type = ! empty( $settings['whatsapp_auth_type'] ) ? $settings['whatsapp_auth_type'] : 'otp';

		if ( 'list' === $auth_type ) {
			$default_title       = esc_html__( 'Secure Verification', 'automation-web-platform' );
			$default_description = esc_html__( 'Verify your identity to continue.', 'automation-web-platform' );
			$default_item1       = esc_html__( 'Approve Request', 'automation-web-platform' );
			$default_item1_desc  = esc_html__( 'This is my verification attempt', 'automation-web-platform' );
			$default_item2       = esc_html__( 'Reject & Report', 'automation-web-platform' );
			$default_item2_desc  = esc_html__( 'I don\'t recognize this', 'automation-web-platform' );

			if ( 'Checkout' === $context ) {
				$default_description = esc_html__( 'Please confirm your identity to complete checkout.', 'automation-web-platform' );
				$default_item1       = esc_html__( 'Approve Order', 'automation-web-platform' );
				$default_item1_desc  = esc_html__( 'Verify this transaction', 'automation-web-platform' );
				$default_item2       = esc_html__( 'Reject & Cancel', 'automation-web-platform' );
				$default_item2_desc  = esc_html__( 'Cancel this request', 'automation-web-platform' );
			} elseif ( 'Login' === $context ) {
				$default_title       = esc_html__( 'Secure Login', 'automation-web-platform' );
				$default_description = esc_html__( 'Please confirm your identity to continue.', 'automation-web-platform' );
				$default_item1       = esc_html__( 'Approve Login', 'automation-web-platform' );
				$default_item1_desc  = esc_html__( 'Verify this is you', 'automation-web-platform' );
				$default_item2       = esc_html__( 'Reject & Report', 'automation-web-platform' );
				$default_item2_desc  = esc_html__( 'Secure your account', 'automation-web-platform' );
			} elseif ( 'Signup' === $context ) {
				$default_title       = esc_html__( 'Create Account', 'automation-web-platform' );
				$default_description = esc_html__( 'Verify your phone number to sign up.', 'automation-web-platform' );
				$default_item1       = esc_html__( 'Approve Signup', 'automation-web-platform' );
				$default_item1_desc  = esc_html__( 'Confirm my new account', 'automation-web-platform' );
				$default_item2       = esc_html__( 'Reject & Cancel', 'automation-web-platform' );
				$default_item2_desc  = esc_html__( 'Cancel registration', 'automation-web-platform' );
			}

			$list_title = ! empty( $settings['whatsapp_list_title'] ) ? $settings['whatsapp_list_title'] : $default_title;
			$list_desc  = ! empty( $settings['whatsapp_list_desc'] ) ? $settings['whatsapp_list_desc'] : $default_description;
			$list_btn   = ! empty( $settings['whatsapp_list_button'] ) ? $settings['whatsapp_list_button'] : esc_html__( 'Choose Action', 'automation-web-platform' );
			$list_foot  = ! empty( $settings['whatsapp_list_footer'] ) ? $settings['whatsapp_list_footer'] : esc_html__( 'Secure authentication via Wawp', 'automation-web-platform' );
			$item1      = ! empty( $settings['whatsapp_list_item1'] ) ? $settings['whatsapp_list_item1'] : $default_item1;
			$item1_desc = ! empty( $settings['whatsapp_list_item1_desc'] ) ? $settings['whatsapp_list_item1_desc'] : $default_item1_desc;
			$item2      = ! empty( $settings['whatsapp_list_item2'] ) ? $settings['whatsapp_list_item2'] : $default_item2;
			$item2_desc = ! empty( $settings['whatsapp_list_item2_desc'] ) ? $settings['whatsapp_list_item2_desc'] : $default_item2_desc;

			// Dynamically translate standard English defaults if they match exactly.
			if ( 'Secure Verification' === $list_title ) {
				$list_title = __( 'Secure Verification', 'automation-web-platform' ); }
			if ( 'Secure Login' === $list_title ) {
				$list_title = __( 'Secure Login', 'automation-web-platform' ); }
			if ( 'Secure Registration' === $list_title ) {
				$list_title = __( 'Secure Registration', 'automation-web-platform' ); }
			if ( 'Secure Authentication' === $list_title ) {
				$list_title = __( 'Secure Authentication', 'automation-web-platform' ); }
			if ( 'Create Account' === $list_title ) {
				$list_title = __( 'Create Account', 'automation-web-platform' ); }

			if ( 'Verify your identity to continue' === $list_desc ) {
				$list_desc = __( 'Verify your identity to continue', 'automation-web-platform' ); }
			if ( 'Verify your identity to continue.' === $list_desc ) {
				$list_desc = __( 'Verify your identity to continue.', 'automation-web-platform' ); }
			if ( 'Please confirm your identity to continue.' === $list_desc ) {
				$list_desc = __( 'Please confirm your identity to continue.', 'automation-web-platform' ); }
			if ( 'Please confirm your identity to complete checkout.' === $list_desc ) {
				$list_desc = __( 'Please confirm your identity to complete checkout.', 'automation-web-platform' ); }
			if ( 'Verify your phone number to sign up.' === $list_desc ) {
				$list_desc = __( 'Verify your phone number to sign up.', 'automation-web-platform' ); }

			if ( 'Choose Action' === $list_btn ) {
				$list_btn = __( 'Choose Action', 'automation-web-platform' ); }
			if ( 'Secure authentication via Wawp' === $list_foot ) {
				$list_foot = __( 'Secure authentication via Wawp', 'automation-web-platform' ); }
			if ( 'Authorized by Wawp Engine' === $list_foot ) {
				$list_foot = __( 'Authorized by Wawp Engine', 'automation-web-platform' ); }

			if ( 'Approve Request' === $item1 ) {
				$item1 = __( 'Approve Request', 'automation-web-platform' ); }
			if ( 'Approve Order' === $item1 ) {
				$item1 = __( 'Approve Order', 'automation-web-platform' ); }
			if ( 'Approve Login' === $item1 ) {
				$item1 = __( 'Approve Login', 'automation-web-platform' ); }
			if ( 'Approve Signup' === $item1 ) {
				$item1 = __( 'Approve Signup', 'automation-web-platform' ); }

			if ( 'This is my verification attempt' === $item1_desc ) {
				$item1_desc = __( 'This is my verification attempt', 'automation-web-platform' ); }
			if ( 'This is my login attempt' === $item1_desc ) {
				$item1_desc = __( 'This is my login attempt', 'automation-web-platform' ); }
			if ( 'Verify this transaction' === $item1_desc ) {
				$item1_desc = __( 'Verify this transaction', 'automation-web-platform' ); }
			if ( 'Verify this is you' === $item1_desc ) {
				$item1_desc = __( 'Verify this is you', 'automation-web-platform' ); }
			if ( 'Confirm my new account' === $item1_desc ) {
				$item1_desc = __( 'Confirm my new account', 'automation-web-platform' ); }

			if ( 'Reject & Report' === $item2 ) {
				$item2 = __( 'Reject & Report', 'automation-web-platform' ); }
			if ( 'Reject & Cancel' === $item2 ) {
				$item2 = __( 'Reject & Cancel', 'automation-web-platform' ); }
			if ( 'Reject & Stop' === $item2 ) {
				$item2 = __( 'Reject & Stop', 'automation-web-platform' ); }

			if ( 'I don\'t recognize this' === $item2_desc || 'I don\'t recognize this' === stripslashes( $item2_desc ) ) {
				$item2_desc = __( 'I don\'t recognize this', 'automation-web-platform' ); }
			if ( 'Cancel this request' === $item2_desc ) {
				$item2_desc = __( 'Cancel this request', 'automation-web-platform' ); }
			if ( 'Cancel this attempt' === $item2_desc ) {
				$item2_desc = __( 'Cancel this attempt', 'automation-web-platform' ); }
			if ( 'Secure your account' === $item2_desc ) {
				$item2_desc = __( 'Secure your account', 'automation-web-platform' ); }
			if ( 'Cancel registration' === $item2_desc ) {
				$item2_desc = __( 'Cancel registration', 'automation-web-platform' ); }

			// Send Interactive List.
			$list_data = array(
				'title'       => $list_title,
				'description' => $list_desc,
				'button'      => $list_btn,
				'footer'      => $list_foot,
				'item1'       => array(
					'title'       => $item1,
					'description' => $item1_desc,
				),
				'item2'       => array(
					'title'       => $item2,
					'description' => $item2_desc,
				),
			);

			try {
				$response = wawp_messenger()->send_auth_list( $phone, $instance->instance_id, $instance->access_token, $list_data );
			} catch ( \Throwable $e ) {
				return array(
					'success' => false,
					'message' => 'Fatal Error: ' . $e->getMessage(),
				);
			}

			if ( self::is_success( $response ) ) {
				$auth_id = $response['full_response']['auth_id'] ?? ( $response['full_response']['id'] ?? ( $response['full_response']['job_id'] ?? '' ) );
				self::log_auth_event( 'success', $phone, $instance, $context, $auth_id, '', $response['full_response'] ?? array(), $user_id, 'list' );
				return array(
					'success'            => true,
					'wawp_auth_id'       => $auth_id,
					'whatsapp_auth_type' => 'list',
					'message'            => esc_html__( 'Verification list sent to your WhatsApp.', 'automation-web-platform' ),
				);
			}
		} else {
			// Resolve OTP language from settings.
			$extra_params = self::resolve_otp_extra_params( $settings );

			// Send OTP.
			$response = wawp_messenger()->send_otp( $phone, $instance->instance_id, $instance->access_token, $extra_params );
			if ( self::is_success( $response ) ) {
				$auth_id = $response['full_response']['auth_id'] ?? ( $response['full_response']['id'] ?? ( $response['full_response']['job_id'] ?? '' ) );
				self::log_auth_event( 'success', $phone, $instance, $context, $auth_id, '', $response['full_response'] ?? array(), $user_id, 'otp' );
				return array(
					'success'            => true,
					'wawp_auth_id'       => $auth_id,
					'whatsapp_auth_type' => 'otp',
					'message'            => esc_html__( 'OTP sent to your WhatsApp.', 'automation-web-platform' ),
				);
			}
		}

		$error_msg = $response['message'] ?? esc_html__( 'Failed to send WhatsApp authentication.', 'automation-web-platform' );
		self::log_auth_event( 'error', $phone, $instance, $context, '', $error_msg, $response['full_response'] ?? array(), $user_id );

		return array(
			'success' => false,
			'message' => $error_msg,
		);
	}

	/**
	 * Resolve OTP extra parameters (lang, footer) from module settings.
	 *
	 * @param array $settings Module settings containing whatsapp_otp_lang_type, whatsapp_otp_custom_lang, etc.
	 * @return array Extra parameters to pass to the OTP API call.
	 */
	private static function resolve_otp_extra_params( $settings ) {
		$extra_params = array();

		// Resolve language.
		$lang_type = ! empty( $settings['whatsapp_otp_lang_type'] ) ? $settings['whatsapp_otp_lang_type'] : 'site';

		switch ( $lang_type ) {
			case 'custom':
				// Use the explicitly specified custom language code.
				if ( ! empty( $settings['whatsapp_otp_custom_lang'] ) ) {
					$extra_params['lang'] = substr( sanitize_text_field( $settings['whatsapp_otp_custom_lang'] ), 0, 5 );
				}
				break;

			case 'user':
				// Use the current user's WordPress locale preference.
				$user_locale = '';
				if ( is_user_logged_in() ) {
					$user_locale = get_user_locale();
				}
				if ( empty( $user_locale ) ) {
					$user_locale = get_locale();
				}
				$extra_params['lang'] = substr( $user_locale, 0, 2 );
				break;

			case 'site':
			default:
				// Use the WordPress site locale.
				$site_locale          = get_locale();
				$extra_params['lang'] = substr( $site_locale, 0, 2 );
				break;
		}

		// Resolve footer.
		$footer_enabled = ! empty( $settings['whatsapp_otp_footer_enabled'] );
		if ( $footer_enabled && ! empty( $settings['whatsapp_otp_footer'] ) ) {
			$extra_params['footer_enabled'] = true;
			$extra_params['footer']         = $settings['whatsapp_otp_footer'];
		}

		return $extra_params;
	}

	/**
	 * Helper to check for success in API response
	 *
	 * @param array $response API response.
	 * @return bool
	 */
	private static function is_success( $response ) {
		if ( isset( $response['status'] ) && 'success' === $response['status'] ) {
			return true;
		}
		if ( isset( $response['full_response']['code'] ) && 'success' === $response['full_response']['code'] ) {
			return true;
		}
		if ( isset( $response['full_response']['status'] ) && 'success' === $response['full_response']['status'] ) {
			return true;
		}

		return false;
	}

	/**
	 * Log Authentication Events uniformly
	 *
	 * @param string $event     Event type.
	 * @param string $phone     Phone.
	 * @param object $instance  Instance.
	 * @param string $context   Context.
	 * @param string $auth_id   Auth ID.
	 * @param string $error     Error.
	 * @param array  $full_resp Full response.
	 * @param int    $user_id   User ID.
	 * @param string $auth_type Auth type.
	 */
	public static function log_auth_event( $event, $phone, $instance, $context, $auth_id = '', $error = '', $full_resp = array(), $user_id = null, $auth_type = 'otp' ) {
		if ( ! class_exists( 'WAWP_Database_Manager' ) ) {
			return;
		}

		if ( 'success' === $event ) {
			$type_label  = 'list' === $auth_type ? 'Interactive List Sent' : 'OTP Sent';
			$log_message = sprintf( '[%s] WhatsApp Auth Initiated: %s | AuthID: %s', $context, $type_label, $auth_id );
		} else {
			$log_message = sprintf( '[%s] Event: %s | Phone: %s | AuthID: %s', $context, strtoupper( $event ), $phone, $auth_id );
			if ( $error ) {
				$log_message .= ' | ' . $error;
			}
		}

		if ( ! $user_id && is_user_logged_in() ) {
			$user_id = get_current_user_id();
		}

		$status = $full_resp ? $full_resp : ( $error ? $error : 'success' );
		/* translators: 1: Context (Login/Signup), 2: Event Type */
		wawp_log_message( $phone, $log_message, sprintf( __( 'WhatsApp %1$s Request (%2$s)', 'automation-web-platform' ), $context, $event ), $status, $user_id, 'whatsapp' );
	}
}
