<?php
/**
 * Global helper functions for the WAWP plugin.
 *
 * @package automation-web-platform
 */

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

if ( ! function_exists( 'wawp' ) ) {
	/**
	 * Main instance of WAWP.
	 *
	 * @return WAWP
	 */
	function wawp() {
		return WAWP::instance();
	}
}

if ( ! function_exists( 'wawp_connector' ) ) {
	/**
	 * Global helper to get the WAWP Connector instance.
	 *
	 * @return WAWP_Connector
	 */
	function wawp_connector() {
		if ( ! empty( wawp()->connector ) ) {
			return wawp()->connector;
		}
		// Create a dynamic safety fallback to prevent fatal crashes when Pro is not active.
		return new class() {
			/**
			 * Fallback call handler for dynamic proxy.
			 *
			 * @param string $name Method name.
			 * @param array  $args Arguments.
			 * @return bool
			 */
			public function __call( $name, $args ) {
				unset( $args );
				$senders = wawp()->get_wawp_setting( 'wawp_senders_enabled', array() );
				if ( ! is_array( $senders ) ) {
					$senders = array();
				}

				switch ( $name ) {
					case 'get_connection_status':
						return array(
							'hasToken'    => false,
							'banned'      => false,
							'notLoggedIn' => true,
							'siteActive'  => false,
						);
					case 'is_email_sender_enabled':
						return ! empty( $senders['email'] );
					case 'is_block_manager_active':
						return ! isset( $senders['block'] ) ? true : ! empty( $senders['block'] );
					case 'is_whatsapp_sender_enabled':
						return ! isset( $senders['wa'] ) ? true : ! empty( $senders['wa'] );
					case 'is_meta_sender_enabled':
						return ! empty( $senders['meta'] );
					case 'is_firebase_sender_enabled':
						return ! empty( $senders['firebase'] );
				}

				return false;
			}
		};
	}
}

if ( ! function_exists( 'wawp_get_user_data' ) ) {
	/**
	 * Global helper to get the current user data from WAWP.
	 *
	 * @param bool $force_refresh Whether to force refresh.
	 * @return array
	 */
	function wawp_get_user_data( $force_refresh = false ) {
		return wawp()->get_user_data( $force_refresh );
	}
}

if ( ! function_exists( 'wawp_is_feature_allowed' ) ) {
	/**
	 * Check if a specific feature is allowed for the current site plan.
	 *
	 * @param string $feature   Feature key.
	 * @param array  $user_data User data (optional).
	 * @return bool
	 */
	function wawp_is_feature_allowed( $feature, $user_data = null ) {
		if ( ! $user_data ) {
			$user_data = wawp_get_user_data();
		}

		if ( ! is_array( $user_data ) ) {
			return false;
		}

		// 1. Check direct root level option (e.g. "abandoned_cart_recovery_enabled" => "enabled")
		if ( isset( $user_data[ $feature ] ) ) {
			$val = $user_data[ $feature ];
			return 'enabled' === $val || true === $val || 1 === (int) $val || '1' === $val;
		}

		// Try with _enabled suffix.
		$with_suffix = $feature . '_enabled';
		if ( isset( $user_data[ $with_suffix ] ) ) {
			$val = $user_data[ $with_suffix ];
			return 'enabled' === $val || true === $val || 1 === (int) $val || '1' === $val;
		}

		// Try without _enabled suffix.
		$no_suffix = preg_replace( '/_enabled$/', '', $feature );
		if ( isset( $user_data[ $no_suffix ] ) ) {
			$val = $user_data[ $no_suffix ];
			return 'enabled' === $val || true === $val || 1 === (int) $val || '1' === $val;
		}

		// 2. Fallback to plan_features nested array
		if ( isset( $user_data['plan_features'] ) && is_array( $user_data['plan_features'] ) ) {
			if ( ! empty( $user_data['plan_features'][ $feature ] ) ) {
				return true;
			}
			if ( ! empty( $user_data['plan_features'][ $with_suffix ] ) ) {
				return true;
			}
			if ( ! empty( $user_data['plan_features'][ $no_suffix ] ) ) {
				return true;
			}
		}

		// 3. Fallback to Pro status check.
		if ( wawp_connector()->is_pro( $user_data ) ) {
			return true;
		}

		return false;
	}
}
if ( ! function_exists( 'wawp_get_feature_restrictions' ) ) {
	/**
	 * Returns a mapping of settings keys to their plan feature keys.
	 *
	 * @return array
	 */
	function wawp_get_feature_restrictions() {
		return array(
			WAWP_Settings_Registry::ABANDONED_CARTS_ENABLED => 'abandoned_cart_recovery',
			WAWP_Settings_Registry::CAMPAIGNS_ENABLED      => 'segmented_notifications',
			WAWP_Settings_Registry::MULTILANG_ENABLED      => 'multilingual_support',
			WAWP_Settings_Registry::SUB_NOTIFS_ENABLED     => 'subscription_alerts',
			WAWP_Settings_Registry::EMAIL_TEMPLATES_ENABLED => 'email_templates',
			WAWP_Settings_Registry::EMAIL_TRACKING_ENABLED => 'activity_log',
			WAWP_Settings_Registry::UNIFIED_LOG_ENABLED    => 'activity_log',
			WAWP_Settings_Registry::CHECKOUT_OTP_ENABLED   => 'checkout_verification',
			WAWP_Settings_Registry::SYSTEM_INFO_ENABLED    => 'system_information',
			WAWP_Settings_Registry::CHAT_WIDGET_ENABLED    => 'whatsapp_chat_button',
			WAWP_Settings_Registry::NOTIFICATIONS_ENABLED  => 'advanced_notifications',
			WAWP_Settings_Registry::COUNTRYCODE_ENABLED    => 'countrycode_cache',
			WAWP_Settings_Registry::PASSWORDLESS_LOGIN_ENABLED => 'login_with_otp',
			WAWP_Settings_Registry::SIGNUP_ENABLED         => 'registration_form_builder',
			WAWP_Settings_Registry::CUSTOM_PAGES_ENABLED   => 'authentication_pages',
			WAWP_Settings_Registry::GOOGLE_RECAPTCHA_ENABLED => 'google_recaptcha',
		);
	}
}

if ( ! function_exists( 'wawp_send_message' ) ) {
	/**
	 * Global function to send a message.
	 *
	 * @param string $phone   Phone.
	 * @param string $message Message.
	 * @param array  $args    Args.
	 * @return array
	 */
	function wawp_send_message( $phone, $message, $args = array() ) {
		$args['message'] = $message;
		$success         = wawp_messenger()->send( $phone, $args );

		return array(
			'status'  => $success ? 'success' : 'error',
			'message' => $success ? esc_html__( 'Message processed by Messaging Service', 'automation-web-platform' ) : esc_html__( 'Failed to process message', 'automation-web-platform' ),
		);
	}
}

if ( ! function_exists( 'wawp_send_otp' ) ) {
	/**
	 * Global function to send OTP.
	 *
	 * @param string $instance_id  Instance ID.
	 * @param string $access_token Access Token.
	 * @param string $recipient    Recipient phone.
	 * @param array  $extra_params Optional extra parameters (lang, footer, footer_enabled).
	 * @return array
	 */
	function wawp_send_otp( $instance_id, $access_token, $recipient, $extra_params = array() ) {
		return WAWP_Senders::send_otp( $instance_id, $access_token, $recipient, $extra_params );
	}
}

if ( ! function_exists( 'wawp_verify_otp' ) ) {
	/**
	 * Global function to verify OTP.
	 *
	 * @param string $instance_id  Instance ID.
	 * @param string $access_token Access Token.
	 * @param string $auth_id      Auth ID.
	 * @param string $phone        Phone.
	 * @param string $otp          OTP code.
	 * @return array
	 */
	function wawp_verify_otp( $instance_id, $access_token, $auth_id, $phone, $otp ) {
		return WAWP_Senders::verify_otp( $instance_id, $access_token, $auth_id, $phone, $otp );
	}
}

if ( ! function_exists( 'wawp_init' ) ) {
	/**
	 * Global initialization helper.
	 *
	 * @return WAWP
	 */
	function wawp_init() {
		return wawp();
	}
}

if ( ! function_exists( 'wawp_otp' ) ) {
	/**
	 * Global helper function to access the OTP service.
	 *
	 * @return WAWP_OTP_Service
	 */
	function wawp_otp() {
		return WAWP_OTP_Service::get_instance();
	}
}
if ( ! function_exists( 'wawp_messenger' ) ) {
	/**
	 * Global helper function to access the Messaging service.
	 *
	 * @return WAWP_Messaging_Service
	 */
	function wawp_messenger() {
		return WAWP_Messaging_Service::get_instance();
	}
}
