<?php
/**
 * Main Senders Manager for Automation Web Platform.
 * Handles different sending channels (WhatsApp, Meta, Firebase, Email).
 *
 * @package automation-web-platform
 */

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


/**
 * Class WAWP_Senders
 *
 * @package automation-web-platform
 */
class WAWP_Senders {
	use WAWP_Security_Trait;
	use WAWP_Settings_Handler;
	use WAWP_Logging_Trait;
	use WAWP_Phone_Helper_Trait;

	/* Tracking IDs feature flag */
	const OPT_TRACKING_IDS = WAWP_Settings_Registry::TRACKING_IDS_ENABLED;
	const DEF_TRACKING_IDS = 1;

	const SENDER_DEFAULTS = array(
		'email'    => 1,
		'wa'       => 1,
		'meta'     => 0,
		'firebase' => 0,
		'block'    => 1,
	);

	const RESTRICTION_MAP = array(
		'wa'       => 'wawp_sender_enabled',
		'meta'     => 'meta_api_sender_enabled',
		'firebase' => 'firebase_sms_enabled',
		'email'    => 'email_smtp_enabled',
		'block'    => 'block_manager_enabled',
	);

	/**
	 * Tracking IDs enabled state.
	 *
	 * @var bool|null
	 */
	private static $tracking_ids_on = null;

	/**
	 * Database Manager.
	 *
	 * @var WAWP_Database_Manager
	 */
	private $database_manager;

	/**
	 * WAWP Instance.
	 *
	 * @var WAWP
	 */
	protected $wawp;

	/**
	 * DB Instance.
	 *
	 * @var WAWP_Database_Manager
	 */
	protected $db;

	/**
	 * Connector Instance.
	 *
	 * @var WAWP_Connector
	 */
	protected $connector;

	/**
	 * WhatsApp Sender.
	 *
	 * @var WAWP_Senders
	 */
	public $whatsapp_sender;

	/**
	 * Meta Sender.
	 *
	 * @var WAWP_Meta_Sender
	 */
	public $meta_sender;

	/**
	 * Firebase Sender.
	 *
	 * @var WAWP_Firebase_Sender
	 */
	public $firebase_sender;

	/**
	 * Email Sender.
	 *
	 * @var WAWP_Email_Sender
	 */
	public $email_sender;

	/**
	 * WAWP_Senders constructor.
	 */
	public function __construct() {
		$this->wawp             = WAWP::instance();
		$this->db               = $this->wawp->db;
		$this->connector        = $this->wawp->connector;
		$this->database_manager = $this->db;

		$this->database_manager->migrate_awp_tables_to_wawp();

		$enabled = $this->get_senders_enabled();

		if ( ! empty( $enabled['wa'] ) ) {
			$this->whatsapp_sender = $this;
		}

		if ( ! empty( $enabled['meta'] ) && class_exists( 'WAWP_Meta_Sender' ) ) {
			$this->meta_sender = new WAWP_Meta_Sender( $this );
		}

		if ( ! empty( $enabled['firebase'] ) && class_exists( 'WAWP_Firebase_Sender' ) ) {
			$this->firebase_sender = new WAWP_Firebase_Sender( $this );
		}

		if ( ! empty( $enabled['email'] ) ) {
			$this->email_sender = new WAWP_Email_Sender( $this );
		}

		$this->init();
		add_action( 'admin_init', array( $this, 'handle_auto_setup' ) );
	}

	/**
	 * Initialize hooks.
	 */
	/**
	 * Initialize hooks.
	 */
	public function init() {
		$page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_SPECIAL_CHARS );
		$page = $page ? $page : '';

		if ( is_admin() && $page && 0 === strpos( $page, 'wawp' ) ) {
			$this->enforce_sender_restrictions();
		}

		add_action( 'admin_notices', array( $this, 'admin_notices' ) );
	}

	/**
	 * Enforce sender restrictions based on user data.
	 */
	private function enforce_sender_restrictions() {
		$ud = wawp_get_user_data();
		if ( ! is_array( $ud ) ) {
			return;
		}

		$senders_raw  = $this->get_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED );
		$enabled      = $this->get_senders_enabled();
		$needs_update = ! is_array( $senders_raw );
		$allowed      = $this->get_sender_allowed_map( $ud );

		foreach ( $allowed as $key => $is_allowed ) {
			if ( ! $is_allowed && ! empty( $enabled[ $key ] ) ) {
				$enabled[ $key ] = 0;
				$needs_update    = true;
			}
		}

		if ( $needs_update ) {
			$this->update_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED, $enabled );
		}
	}

	/**
	 * Get a toggle setting.
	 *
	 * @param string $option      Option key.
	 * @param int    $default_val Default value.
	 * @return bool Toggle value.
	 */
	private function get_toggle( $option, $default_val = 1 ) {
		return (bool) $this->get_wawp_setting( $option, $default_val );
	}

	/**
	 * Get the currently enabled senders array (with defaults applied).
	 *
	 * @return array Enabled senders.
	 */
	private function get_senders_enabled() {
		$raw = $this->get_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED );
		return is_array( $raw ) ? wp_parse_args( $raw, self::SENDER_DEFAULTS ) : self::SENDER_DEFAULTS;
	}

	/**
	 * Build a map of sender keys to whether the addon allows them.
	 *
	 * @param array|null $ud Optional user data. If null, fetched automatically.
	 * @return array Allowed map.
	 */
	private function get_sender_allowed_map( $ud = null ) {
		if ( null === $ud ) {
			$ud = wawp_get_user_data();
		}
		if ( ! is_array( $ud ) ) {
			return array();
		}
		$map = array();
		foreach ( self::RESTRICTION_MAP as $key => $ud_key ) {
			// Force wa, email and block to be allowed for everyone.
			if ( in_array( $key, array( 'wa', 'email', 'block' ), true ) ) {
				$map[ $key ] = true;
				continue;
			}
			$map[ $key ] = wawp_is_feature_allowed( $ud_key, $ud );
		}
		return $map;
	}

	/**
	 * Get settings data for React.
	 *
	 * @return array Settings data.
	 */
	public function get_react_settings_data() {
		return array(
			'enabled' => $this->get_senders_enabled(),
			'allowed' => $this->get_sender_allowed_map(),
			'i18n'    => array(
				'sendersTitle'       => __( 'Senders & Messaging', 'automation-web-platform' ),
				'sendersSubtitle'    => __( 'Configure your communication gateways and optimize your messaging engagement.', 'automation-web-platform' ),
				'proVersion'         => __( 'PRO', 'automation-web-platform' ),
				'btnSettings'        => __( 'Settings', 'automation-web-platform' ),
				'btnUpgrade'         => __( 'Upgrade', 'automation-web-platform' ),
				'btnActivate'        => __( 'Activate', 'automation-web-platform' ),
				'activeSenders'      => __( 'Active Senders', 'automation-web-platform' ),
				'activeSendersDesc'  => __( 'Manage your primary communication channels and their individual settings.', 'automation-web-platform' ),
				'messagingTools'     => __( 'Messaging Tools', 'automation-web-platform' ),
				'messagingToolsDesc' => __( 'Optimize your message delivery, tracking, and professional appearance.', 'automation-web-platform' ),
				'metaName'           => __( 'WhatsApp API', 'automation-web-platform' ),
				'metaDesc'           => __( 'Official Meta API for scalable, high-volume business messaging automation.', 'automation-web-platform' ),
				'firebaseName'       => __( 'Firebase SMS', 'automation-web-platform' ),
				'firebaseDesc'       => __( 'Send OTP messages using Google Firebase for secured authentication.', 'automation-web-platform' ),
				'waName'             => __( 'WhatsApp Web', 'automation-web-platform' ),
				'waDesc'             => __( 'Connect your personal WhatsApp for automated notifications and OTPs.', 'automation-web-platform' ),
				'emailName'          => __( 'Email (SMTP)', 'automation-web-platform' ),
				'emailDesc'          => __( 'Send transactional emails via your custom SMTP server for reliability.', 'automation-web-platform' ),
				'blockManagerName'   => __( 'Block Manager', 'automation-web-platform' ),
				'blockManagerDesc'   => __( 'Easily manage and block specific phone numbers from receiving automated messages.', 'automation-web-platform' ),
				'trackingIdsName'    => __( 'Unique Message IDs', 'automation-web-platform' ),
				'trackingIdsDesc'    => __( 'Append unique tracking IDs to every message for better analytics and delivery monitoring.', 'automation-web-platform' ),
				'activityHubName'    => __( 'Activity Hub', 'automation-web-platform' ),
				'activityHubDesc'    => __( 'Real-time logging of all automated interactions and system events for debugging and tracking.', 'automation-web-platform' ),
				'emailTrackingName'  => __( 'Email Open Tracking', 'automation-web-platform' ),
				'emailTrackingDesc'  => __( 'Know exactly when your customers open your transactional emails to measure engagement.', 'automation-web-platform' ),
				'emailTemplatesName' => __( 'Email Templates', 'automation-web-platform' ),
				'emailTemplatesDesc' => __( 'Use a drag-and-drop builder to create professional, high-converting email communications.', 'automation-web-platform' ),
				'toastSaved'         => __( 'Settings saved successfully', 'automation-web-platform' ),
				'toastFailed'        => __( 'Failed to save settings', 'automation-web-platform' ),
				'toastUpdated'       => __( 'Updated successfully', 'automation-web-platform' ),
				'toastError'         => __( 'An error occurred', 'automation-web-platform' ),
				'toastNetwork'       => __( 'Network error', 'automation-web-platform' ),
				'tabOverview'        => __( 'Senders Overview', 'automation-web-platform' ),
				'tabTools'           => __( 'Messaging Tools', 'automation-web-platform' ),
			),
		);
	}

	/**
	 * Render the React dashboard container.
	 */
	public function render_admin_page() {
		echo '<div id="wawp-dashboard-root"></div>';
	}

	/**
	 * Render admin notices.
	 */
	public function admin_notices() {
		// 1. Handle standard settings updated notice from WordPress core
		$settings_updated = filter_input( INPUT_GET, 'settings-updated', FILTER_SANITIZE_SPECIAL_CHARS );
		if ( 'true' === $settings_updated ) {

			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved successfully.', 'automation-web-platform' ) . '</p></div>';
		}

		// 2. Handle our secure transient-based notices
		$notice_data = get_transient( 'wawp_admin_notice_' . get_current_user_id() );
		if ( $notice_data ) {
			delete_transient( 'wawp_admin_notice_' . get_current_user_id() );
			$message = isset( $notice_data['message'] ) ? $notice_data['message'] : '';
			$type    = isset( $notice_data['type'] ) ? $notice_data['type'] : 'success';
			if ( $message ) {
				echo '<div class="notice notice-' . esc_attr( $type ) . ' is-dismissible wawp-admin-notice"><p>' . esc_html( $message ) . '</p></div>';
			}
		}

		$senders_enabled = $this->get_senders_enabled();
		$allowed         = $this->get_sender_allowed_map();

		$notice_map = array(
			'email'    => esc_html__( 'Email/SMTP sender is currently enabled but the addon is not active. Please activate the addon or disable the sender.', 'automation-web-platform' ),
			'wa'       => esc_html__( 'WhatsApp sender is currently enabled but the addon is not active. Please activate the addon or disable the sender.', 'automation-web-platform' ),
			'meta'     => esc_html__( 'Meta WhatsApp sender is currently enabled but the addon is not active. Please activate the addon or disable the sender.', 'automation-web-platform' ),
			'block'    => esc_html__( 'Block Manager is currently enabled but the addon is not active. Please activate the addon or disable the sender.', 'automation-web-platform' ),
			'firebase' => esc_html__( 'Firebase Sender is currently enabled but the addon is not active. Please activate the addon or disable the sender.', 'automation-web-platform' ),
		);

		foreach ( $notice_map as $key => $msg ) {
			if ( ! ( isset( $allowed[ $key ] ) && $allowed[ $key ] ) && ! empty( $senders_enabled[ $key ] ) ) {
				echo '<div class="notice notice-warning is-dismissible"><p>' . esc_html( $msg ) . '</p></div>';
			}
		}
	}

	/**
	 * Nonce action.
	 *
	 * @var string
	 */
	protected $nonce_action = 'wawp_whatsapp_sender_nonce';

	/**
	 * Get WhatsApp React settings data.
	 *
	 * @return array Settings data.
	 */
	public function get_whatsapp_react_settings_data() {
		$instances = WAWP()->instance_manager->get_all_instances();
		$formatted = array();
		if ( $instances ) {
			foreach ( $instances as $inst ) {
				$formatted[] = array(
					'id'           => $inst->id,
					'name'         => $inst->name,
					'instance_id'  => $inst->instance_id,
					'access_token' => $inst->access_token,
					'status'       => $inst->status,
					'message'      => $inst->message,
				);
			}
		}

		return array(
			'instances' => $formatted,
			'urls'      => array(
				'autoSetup'        => wawp_connector()->get_auto_setup_url( 'whatsapp-web' ),
				'connectNewNumber' => 'https://app.wawp.net/linked-numbers?domain=' . rawurlencode( wawp_connector()->get_site_domain() ) . '&return_url=' . rawurlencode( admin_url( 'admin.php?page=wawp&wawp_auto_setup=1&_wpnonce=' . wp_create_nonce( 'wawp_auto_setup_nonce' ) . '&wawp_section=whatsapp-web-sender' ) ),
			),
			'i18n'      => array(
				'title'                         => esc_html__( 'WhatsApp Web', 'automation-web-platform' ),
				'subtitle'                      => esc_html__( 'Manage your WhatsApp Web instances and check their connection status.', 'automation-web-platform' ),
				'addInstance'                   => esc_html__( 'Add Instance', 'automation-web-platform' ),
				'instanceName'                  => esc_html__( 'Instance Name', 'automation-web-platform' ),
				'instanceId'                    => esc_html__( 'Instance ID', 'automation-web-platform' ),
				'accessToken'                   => esc_html__( 'Access Token', 'automation-web-platform' ),
				'status'                        => esc_html__( 'Status', 'automation-web-platform' ),
				'actions'                       => esc_html__( 'Actions', 'automation-web-platform' ),
				'online'                        => esc_html__( 'Online', 'automation-web-platform' ),
				'offline'                       => esc_html__( 'Offline', 'automation-web-platform' ),
				'paused'                        => esc_html__( 'Paused', 'automation-web-platform' ),
				'checking'                      => esc_html__( 'Checking...', 'automation-web-platform' ),
				'scanQrCode'                    => esc_html__( 'Scan QR Code', 'automation-web-platform' ),
				'failed'                        => esc_html__( 'Failed', 'automation-web-platform' ),
				'stopped'                       => esc_html__( 'Stopped', 'automation-web-platform' ),
				'unknown'                       => esc_html__( 'Unknown', 'automation-web-platform' ),
				'testMessage'                   => esc_html__( 'Send Test Message', 'automation-web-platform' ),
				'delete'                        => esc_html__( 'Delete', 'automation-web-platform' ),
				'edit'                          => esc_html__( 'Edit', 'automation-web-platform' ),
				'save'                          => esc_html__( 'Save Changes', 'automation-web-platform' ),
				'cancel'                        => esc_html__( 'Cancel', 'automation-web-platform' ),
				'phoneNumber'                   => __( 'Phone Number (with country code)', 'automation-web-platform' ),
				'message'                       => esc_html__( 'Message', 'automation-web-platform' ),
				'send'                          => esc_html__( 'Send Message', 'automation-web-platform' ),
				'refresh'                       => esc_html__( 'Refresh All', 'automation-web-platform' ),
				'noInstances'                   => esc_html__( 'No WhatsApp instances found. Click "Add Instance" to connect your first account.', 'automation-web-platform' ),
				'setupAuto'                     => esc_html__( 'Setup Automatically', 'automation-web-platform' ),
				'setupManual'                   => esc_html__( 'Setup Manually', 'automation-web-platform' ),
				'successAdd'                    => esc_html__( 'Instance added successfully.', 'automation-web-platform' ),
				'successDelete'                 => esc_html__( 'Instance deleted successfully.', 'automation-web-platform' ),
				'successUpdate'                 => esc_html__( 'Instance updated successfully.', 'automation-web-platform' ),
				'successRefresh'                => esc_html__( 'Instances status refreshed.', 'automation-web-platform' ),
				'error'                         => esc_html__( 'An error occurred.', 'automation-web-platform' ),
				'waWebTitle'                    => esc_html__( 'WhatsApp Web', 'automation-web-platform' ),
				'waWebDesc'                     => esc_html__( 'Connect your personal WhatsApp for automated orders notifications.', 'automation-web-platform' ),
				'connectedNumbers'              => esc_html__( 'Connected Numbers', 'automation-web-platform' ),
				'sync'                          => esc_html__( 'Sync', 'automation-web-platform' ),
				'waWebSlotsDesc'                => esc_html__( 'Connect and manage your WhatsApp Web instances for automated notifications.', 'automation-web-platform' ),
				'addNewInstance'                => esc_html__( 'Add New Instance', 'automation-web-platform' ),
				'addNewInstanceManually'        => esc_html__( 'Connect Instance', 'automation-web-platform' ),
				'connectPhonePrefix'            => esc_html__( 'Connect your phone via', 'automation-web-platform' ),
				'connectPhoneSuffix'            => esc_html__( 'or add credentials manually.', 'automation-web-platform' ),
				'rapidConnection'               => esc_html__( 'Rapid Connection', 'automation-web-platform' ),
				'rapidConnectionDesc'           => __( 'Open your Wawp app, go to Settings > Link Device and scan the QR.', 'automation-web-platform' ),
				'getQrCode'                     => esc_html__( 'Get QR Code', 'automation-web-platform' ),
				'manualCredentials'             => esc_html__( 'Manual Credentials', 'automation-web-platform' ),
				'friendlyName'                  => esc_html__( 'Friendly Name', 'automation-web-platform' ),
				'connectBtn'                    => esc_html__( 'Connect', 'automation-web-platform' ),
				'noInstancesFound'              => esc_html__( 'No Instances Found', 'automation-web-platform' ),
				'selectSendersPlaceholder'      => esc_html__( 'Select senders...', 'automation-web-platform' ),
				'connectFirstWa'                => esc_html__( 'Connect your first WhatsApp number to begin.', 'automation-web-platform' ),
				'sendTestMessage'               => esc_html__( 'Send Test Delivery', 'automation-web-platform' ),
				'checkConnection'               => esc_html__( 'Force Status Link', 'automation-web-platform' ),
				'modifyCredentials'             => esc_html__( 'Modify Credentials', 'automation-web-platform' ),
				'aboutData'                     => esc_html__( 'Inspect Session Data', 'automation-web-platform' ),
				'disconnectInstance'            => esc_html__( 'Disconnect Instance', 'automation-web-platform' ),
				'securityToken'                 => esc_html__( 'Security Token', 'automation-web-platform' ),
				'name'                          => esc_html__( 'Name', 'automation-web-platform' ),
				'chooseWaSender'                => esc_html__( 'Feature Routing & Mappings', 'automation-web-platform' ),
				'chooseWaSenderDesc'            => esc_html__( 'Define which connected number handles each automated flow.', 'automation-web-platform' ),
				'notifUser'                     => esc_html__( 'Users WhatsApp Notifications', 'automation-web-platform' ),
				'customerFlow'                  => esc_html__( 'Customer Flow', 'automation-web-platform' ),
				'notifUserDesc'                 => esc_html__( 'Choose numbers for sending notifications to USERS/Customers.', 'automation-web-platform' ),
				'customerNotifActiveMessage'    => __( '<b>{count}</b> instance(s) will handle customer notifications. Multi-sender routing ensures high delivery rates.', 'automation-web-platform' ),
				'customerNotifInactiveMessage'  => esc_html__( 'Critical: No senders selected for customer notifications. High risk of delivery failure.', 'automation-web-platform' ),
				'notifAdmin'                    => esc_html__( 'Admins WhatsApp Notifications', 'automation-web-platform' ),
				'systemFlow'                    => esc_html__( 'System Flow', 'automation-web-platform' ),
				'notifAdminDesc'                => esc_html__( 'Choose numbers for sending notification events to SITE ADMINS.', 'automation-web-platform' ),
				'adminNotifActiveMessage'       => __( '<b>{count}</b> instance(s) will handle system alerts. Ensuring admins stay informed about site events.', 'automation-web-platform' ),
				'adminNotifInactiveMessage'     => esc_html__( 'Warning: No senders selected for admin notifications. You might miss important system alerts.', 'automation-web-platform' ),
				'primaryTransactionalFlows'     => esc_html__( 'Primary Transactional Flows', 'automation-web-platform' ),
				'loginWa'                       => esc_html__( 'OTP Login', 'automation-web-platform' ),
				'verificationDeliveryDesc'      => esc_html__( 'Verification delivery for existing accounts.', 'automation-web-platform' ),
				'loginOtpActiveMessage'         => esc_html__( 'Secure OTP delivery is active for existing user accounts.', 'automation-web-platform' ),
				'loginOtpInactiveMessage'       => esc_html__( 'Login routing is disabled. Users will fallback to default methods.', 'automation-web-platform' ),
				'signupOtp'                     => esc_html__( 'New User Verify', 'automation-web-platform' ),
				'newRegistrationDesc'           => esc_html__( 'Authentication for new registration attempts.', 'automation-web-platform' ),
				'signupOtpActiveMessage'        => esc_html__( 'New user verification is active. Ensuring only valid numbers can register.', 'automation-web-platform' ),
				'signupOtpInactiveMessage'      => esc_html__( 'Registration routing is disabled. OTP will not be sent to new users via WhatsApp.', 'automation-web-platform' ),
				'wawpCheckout'                  => esc_html__( 'Checkout Confirmation', 'automation-web-platform' ),
				'checkoutOtpDesc'               => esc_html__( 'Order validation and checkout verification.', 'automation-web-platform' ),
				'checkoutOtpActiveMessage'      => esc_html__( 'WooCommerce checkout verification is active for high-security orders.', 'automation-web-platform' ),
				'checkoutOtpInactiveMessage'    => esc_html__( 'Checkout verification is currently inactive for this channel.', 'automation-web-platform' ),
				'generalSystemSender'           => esc_html__( 'General System Sender', 'automation-web-platform' ),
				'generalSystemSenderDesc'       => esc_html__( 'Used for system operations, direct messages, and general automation tasks.', 'automation-web-platform' ),
				'generalActiveMessage'          => esc_html__( 'System sender is active for general automation and background tasks.', 'automation-web-platform' ),
				'generalInactiveMessage'        => esc_html__( 'No general sender selected. Some automated background tasks might fail.', 'automation-web-platform' ),
				'updateCredentials'             => esc_html__( 'Update Credentials', 'automation-web-platform' ),
				'updateCredentialsDesc'         => esc_html__( 'Update your WhatsApp instance API credentials.', 'automation-web-platform' ),
				'updateConfigBtn'               => esc_html__( 'Update Config', 'automation-web-platform' ),
				'done'                          => esc_html__( 'DONE', 'automation-web-platform' ),
				'checkPhoneNow'                 => esc_html__( 'Check your phone now!', 'automation-web-platform' ),
				'testDeliverySentTo'            => esc_html__( 'Test delivery sent successfully to', 'automation-web-platform' ),
				'openWaPreview'                 => esc_html__( 'Open WhatsApp to Preview', 'automation-web-platform' ),
				'remoteAccountDetails'          => esc_html__( 'Remote Account Details', 'automation-web-platform' ),
				'remoteAccountDetailsDesc'      => esc_html__( 'Live session and account metadata from the global API.', 'automation-web-platform' ),
				'closeMetadataInspector'        => esc_html__( 'Close Metadata Inspector', 'automation-web-platform' ),
				'addingInstanceToast'           => esc_html__( 'Adding instance...', 'automation-web-platform' ),
				'instanceAddedToast'            => esc_html__( 'Instance added successfully', 'automation-web-platform' ),
				'failedAddInstanceToast'        => esc_html__( 'Failed to add instance', 'automation-web-platform' ),
				'errorOccurredToast'            => esc_html__( 'An error occurred', 'automation-web-platform' ),
				'updatingInstanceToast'         => esc_html__( 'Updating instance...', 'automation-web-platform' ),
				'instanceUpdatedToast'          => esc_html__( 'Instance updated successfully', 'automation-web-platform' ),
				'failedUpdateInstanceToast'     => esc_html__( 'Failed to update instance', 'automation-web-platform' ),
				'confirmDeleteInstance'         => esc_html__( 'Are you sure you want to delete this instance?', 'automation-web-platform' ),
				'deletingInstanceToast'         => esc_html__( 'Deleting instance...', 'automation-web-platform' ),
				'instanceDeletedToast'          => esc_html__( 'Instance deleted', 'automation-web-platform' ),
				'failedDeleteInstanceToast'     => esc_html__( 'Failed to delete instance', 'automation-web-platform' ),
				'refreshingInstanceStatusToast' => esc_html__( 'Refreshing instance status...', 'automation-web-platform' ),
				'statusUpdatedToast'            => esc_html__( 'Status updated', 'automation-web-platform' ),
				'failedCheckStatusToast'        => esc_html__( 'Failed to check status', 'automation-web-platform' ),
				'sendingTestDeliveryToast'      => esc_html__( 'Sending secure test delivery...', 'automation-web-platform' ),
				'testMessageSentToast'          => esc_html__( 'Test message sent', 'automation-web-platform' ),
				'failedSendTestToast'           => esc_html__( 'Failed to send test message', 'automation-web-platform' ),
				'fetchingAccountDataToast'      => esc_html__( 'Fetching account data...', 'automation-web-platform' ),
				'dataFetchedToast'              => esc_html__( 'Data fetched successfully', 'automation-web-platform' ),
				'failedFetchDataToast'          => esc_html__( 'Failed to fetch data.', 'automation-web-platform' ),
				'errorFetchDataToast'           => esc_html__( 'An error occurred while fetching data.', 'automation-web-platform' ),
				'saving'                        => esc_html__( 'Saving Changes...', 'automation-web-platform' ),
				'synchronized'                  => esc_html__( 'All Changes Saved', 'automation-web-platform' ),
				'unsaved'                       => esc_html__( 'Unsaved Changes', 'automation-web-platform' ),
				'close'                         => esc_html__( 'Close', 'automation-web-platform' ),
			),
		);
	}

	/**
	 * Handle auto setup for WhatsApp instances.
	 */
	public function handle_auto_setup() {
		if ( ! isset( $_GET['wawp_auto_setup'] ) || ! wawp_connector()->has_auth() ) {
			return;
		}

		$nonce_valid = false;
		if ( isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'wawp_auto_setup_nonce' ) ) {
			$nonce_valid = true;
		}

		if ( ! $nonce_valid ) {
			if ( ! isset( $_POST['wawp_confirm_setup'] ) || ! isset( $_POST['wawp_setup_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['wawp_setup_nonce'] ), 'wawp_confirm_setup_action' ) ) {
				// Show a secure confirmation page to prevent CSRF.
				$instance_id  = isset( $_GET['instance_id'] ) ? sanitize_text_field( wp_unslash( $_GET['instance_id'] ) ) : '';
				$access_token = isset( $_GET['access_token'] ) ? sanitize_text_field( wp_unslash( $_GET['access_token'] ) ) : '';
				$name         = isset( $_GET['name'] ) ? sanitize_text_field( wp_unslash( $_GET['name'] ) ) : 'WhatsApp Linked';

				$this->render_auto_setup_confirmation( $instance_id, $access_token, $name );
				exit;
			}
		}

		$instance_id  = isset( $_GET['instance_id'] ) ? sanitize_text_field( wp_unslash( $_GET['instance_id'] ) ) : '';
		$access_token = isset( $_GET['access_token'] ) ? sanitize_text_field( wp_unslash( $_GET['access_token'] ) ) : '';
		$name         = isset( $_GET['name'] ) ? sanitize_text_field( wp_unslash( $_GET['name'] ) ) : 'WhatsApp Linked';

		if ( ! empty( $instance_id ) && ! empty( $access_token ) ) {
			global $wpdb;
			$table  = $wpdb->prefix . 'wawp_instance_data';
			$exists = (int) WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT id FROM %i WHERE instance_id = %s', $table, $instance_id ), "wawp_inst_exists_{$instance_id}", 'wawp_instances', 3600 )[0]['id'] ?? 0;

			if ( ! $exists ) {
				WAWP()->db->insert(
					'instance_data',
					array(
						'name'         => $name,
						'instance_id'  => $instance_id,
						'access_token' => $access_token,
						'status'       => 'checking',
						'message'      => esc_html__( 'Verifying connection...', 'automation-web-platform' ),
					)
				);
				$this->check_and_update_instance_status( $instance_id, $access_token );
			} else {
				WAWP()->db->update_row(
					'instance_data',
					array(
						'name'         => $name,
						'access_token' => $access_token,
					),
					array( 'instance_id' => $instance_id )
				);
			}
			wp_cache_delete( 'wawp_all_instances', 'wawp_instances' );
			delete_transient( 'wawp_online_instances' );
			if ( class_exists( 'WAWP' ) && method_exists( WAWP(), 'clear_dashboard_cache_on_option_update' ) ) {
				WAWP()->clear_dashboard_cache_on_option_update( 'wawp_force' );
			}

			$this->update_wawp_setting( WAWP_Settings_Registry::ACCESS_TOKEN, $access_token );
			$senders_opts       = (array) $this->get_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED, array() );
			$senders_opts['wa'] = 1;
			$this->update_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED, $senders_opts );
		}

		$section      = isset( $_GET['wawp_section'] ) ? sanitize_key( wp_unslash( $_GET['wawp_section'] ) ) : 'whatsapp-web-sender';
		$step         = isset( $_GET['step'] ) ? (int) $_GET['step'] : 0;
		$redirect_url = 'admin.php?page=wawp&wawp_section=' . $section;
		if ( $step ) {
			$redirect_url .= '&step=' . $step;
		}

		wp_safe_redirect( admin_url( $redirect_url ) );
		exit;
	}

	/**
	 * Render confirmation page for auto setup to prevent CSRF.
	 *
	 * @param string $instance_id  WhatsApp Instance ID.
	 * @param string $access_token Setup Access Token.
	 * @param string $name         WhatsApp Instance Name.
	 */
	private function render_auto_setup_confirmation( $instance_id, $access_token, $name ) {
		require_once ABSPATH . 'wp-admin/admin-header.php';
		?>
		<div class="wrap">
			<div style="max-width: 600px; margin: 50px auto; padding: 30px; background: #fff; border: 1px solid #ccd0d4; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); text-align: center; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif;">
				<div style="width: 70px; height: 70px; background: #e6f4ea; color: #137333; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px;">
					<svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>
				</div>
				<h2 style="font-size: 22px; font-weight: 700; color: #1d2327; margin: 0 0 10px;"><?php esc_html_e( 'Connect WhatsApp Instance', 'automation-web-platform' ); ?></h2>
				<p style="font-size: 14px; color: #646970; line-height: 1.5; margin: 0 0 25px;">
					<?php
					echo wp_kses(
						sprintf(
							// translators: %s: WhatsApp instance name.
							esc_html__( 'You are about to link the WhatsApp Web instance %s to your site. Click the button below to confirm and complete the setup.', 'automation-web-platform' ),
							'<strong>' . esc_html( $name ) . '</strong>'
						),
						array(
							'strong' => array(),
						)
					);
					?>
				</p>
				
				<form method="post" action="<?php echo esc_url( admin_url( 'admin.php?' . $_SERVER['QUERY_STRING'] ) ); ?>">
					<?php wp_nonce_field( 'wawp_confirm_setup_action', 'wawp_setup_nonce' ); ?>
					<input type="hidden" name="wawp_confirm_setup" value="1" />
					<div style="display: flex; justify-content: center; gap: 15px;">
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=wawp' ) ); ?>" class="button button-large" style="height: 44px; line-height: 42px; padding: 0 25px; font-size: 14px; font-weight: 600; border-radius: 6px;"><?php esc_html_e( 'Cancel', 'automation-web-platform' ); ?></a>
						<button type="submit" class="button button-primary button-large" style="height: 44px; line-height: 42px; padding: 0 25px; font-size: 14px; font-weight: 600; background: #004449; border-color: #004449; color: #fff; border-radius: 6px;"><?php esc_html_e( 'Confirm & Connect', 'automation-web-platform' ); ?></button>
					</div>
				</form>
			</div>
		</div>
		<?php
		include ABSPATH . 'wp-admin/admin-footer.php';
	}

	/**
	 * Add a WhatsApp instance.
	 *
	 * @param array $data Instance data.
	 * @return array Result.
	 */
	public function wawp_add_instance( $data = array() ) {
		if ( empty( $data ) ) {
			$this->check_permissions( 'wawp_whatsapp_sender_nonce', 'security' );
		}
		global $wpdb;
		$name = isset( $data['name'] ) ? $data['name'] : '';

		$instance_id = isset( $data['instance_id'] ) ? $data['instance_id'] : '';

		$access_token = isset( $data['access_token'] ) ? $data['access_token'] : '';

		if ( ! $name || ! $instance_id || ! $access_token ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'All fields are required.', 'automation-web-platform' ),
			);
		}

		$inserted = WAWP()->db->insert(
			'instance_data',
			array(
				'name'         => $name,
				'instance_id'  => $instance_id,
				'access_token' => $access_token,
				'status'       => 'checking',
				'message'      => esc_html__( 'Verifying connection...', 'automation-web-platform' ),
			)
		);

		if ( false === $inserted ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'Failed to save the instance to the database.', 'automation-web-platform' ),
			);
		}

		wp_cache_delete( 'wawp_all_instances', 'wawp_instances' );

		$this->check_and_update_instance_status( $instance_id, $access_token );

		$this->auto_assign_if_only_instance();

		return array(
			'success' => true,
			'message' => esc_html__( 'Instance added successfully. Status is being updated.', 'automation-web-platform' ),
		);
	}

	/**
	 * Delete a WhatsApp instance.
	 *
	 * @param int $id Instance DB ID.
	 * @return array Result.
	 */
	public function wawp_delete_instance( $id = 0 ) {
		if ( ! $id ) {
			$this->check_permissions( 'wawp_whatsapp_sender_nonce', 'security' );
		}
		global $wpdb;
		$id = $id;

		if ( $id <= 0 ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'Invalid instance ID.', 'automation-web-platform' ),
			);
		}

		$result = WAWP()->db->delete_row( 'instance_data', array( 'id' => $id ) );
		if ( false === $result ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'Failed to delete instance.', 'automation-web-platform' ),
			);
		}

		wp_cache_delete( 'wawp_all_instances', 'wawp_instances' );

		$this->update_login_redirect_based_on_instances();

		return array(
			'success' => true,
			'message' => esc_html__( 'Instance deleted successfully.', 'automation-web-platform' ),
		);
	}
	/**
	 * Edit a WhatsApp instance.
	 *
	 * @param int   $id   Instance DB ID.
	 * @param array $data Instance data.
	 * @return array Result.
	 */
	public function wawp_edit_instance( $id = 0, $data = array() ) {
		if ( ! $id && empty( $data ) ) {
			$this->check_permissions( 'wawp_whatsapp_sender_nonce', 'security' );
		}
		global $wpdb;
		$id = $id;

		$name = isset( $data['name'] ) ? $data['name'] : '';

		$instance_id = isset( $data['instance_id'] ) ? $data['instance_id'] : '';

		$access_token = isset( $data['access_token'] ) ? $data['access_token'] : '';

		if ( $id <= 0 || ! $name || ! $instance_id || ! $access_token ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'All fields are required.', 'automation-web-platform' ),
			);
		}

		$result = WAWP()->db->update_row(
			'instance_data',
			array(
				'name'         => $name,
				'instance_id'  => $instance_id,
				'access_token' => $access_token,
				'status'       => 'checking',
				'message'      => '',
			),
			array( 'id' => $id )
		);

		if ( false === $result ) {
			$error = $wpdb->last_error ? $wpdb->last_error : esc_html__( 'Database error occurred.', 'automation-web-platform' );

			return array(
				'success' => false,
				'message' => esc_html__( 'Failed to update instance: ', 'automation-web-platform' ) . $error,
			);
		}

		wp_cache_delete( 'wawp_all_instances', 'wawp_instances' );

		$this->check_and_update_instance_status( $instance_id, $access_token );
		$st  = $this->get_instance_status( $instance_id );
		$msg = $this->get_instance_message( $instance_id );
		return array(
			'success'     => true,
			'message'     => esc_html__( 'Instance updated successfully.', 'automation-web-platform' ),
			'status'      => $st,
			'message_api' => $msg,
		);
	}

	/**
	 * Update instance status.
	 *
	 * @param string $iid Instance ID.
	 * @param string $atk Access Token.
	 * @return array Result.
	 */
	public function wawp_update_status( $iid = '', $atk = '' ) {
		$instance_id = $iid;

		$access_token = $atk;

		if ( ! $instance_id || ! $access_token ) {
			return array(
				'success' => false,
				'message' => __( 'Instance ID & Access Token are required.', 'automation-web-platform' ),
			);
		}

		$this->check_and_update_instance_status( $instance_id, $access_token );
		$new_status  = $this->get_instance_status( $instance_id );
		$new_message = $this->get_instance_message( $instance_id );

		if ( is_null( $new_status ) ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'Failed to retrieve updated status.', 'automation-web-platform' ),
			);
		}
		return array(
			'success'     => true,
			'message'     => esc_html__( 'Status updated.', 'automation-web-platform' ),
			'status'      => $new_status,
			'message_api' => $new_message,
		);
	}

	/**
	 * Send a test WhatsApp message.
	 *
	 * @param string $iid   Instance ID.
	 * @param string $atk   Access Token.
	 * @param string $phone Phone number.
	 * @param string $msg   Message body.
	 * @return array Result.
	 */
	public function wawp_send_test_message( $iid = '', $atk = '', $phone = '', $msg = '' ) {
		$instance_id = $iid;

		$access_token = $atk;

		$phone_number = $phone;

		$message_raw = $msg ? $msg : esc_html__( 'Wawp Test Message', 'automation-web-platform' );

		if ( ! $instance_id || ! $phone_number ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'Required fields missing.', 'automation-web-platform' ),
			);
		}

		$user    = wp_get_current_user();
		$message = WAWP_Message_Parser::parse_message_placeholders( $message_raw, array(), 0, $user ? $user->ID : 0 );

		$send_args = array(
			'channel'      => 'whatsapp',
			'message'      => $message,
			'context'      => 'Admin Test Message',
			'user_id'      => $user ? $user->ID : 0,
			'instance_id'  => $instance_id,
			'access_token' => $access_token,
		);

		// Find gateway_id for this specific instance_id.
		global $wpdb;
		$table = $wpdb->prefix . 'wawp_gateways';
		$g_id  = WAWP()->db->get_var( $wpdb->prepare( "SELECT id FROM %i WHERE gateway_type = 'whatsapp_web' AND config LIKE %s", $table, '%' . $wpdb->esc_like( $instance_id ) . '%' ) );
		if ( $g_id ) {
			$send_args['gateway_id'] = $g_id;
		}

		$result = wawp_messenger()->send( $phone_number, $send_args );

		if ( $result ) {
			return array(
				'success' => true,
				'message' => esc_html__( 'Test message sent successfully!', 'automation-web-platform' ),
			);
		} else {
			return array(
				'success' => false,
				'message' => esc_html__( 'Failed to send test message. Check Activity Hub for details.', 'automation-web-platform' ),
			);
		}
	}

	/**
	 * Auto check all instances status.
	 *
	 * @return array Result.
	 */
	public function wawp_auto_check_all_instance_status() {
		$instances = $this->get_all_instances();
		$updated   = 0;
		if ( $instances ) {
			foreach ( $instances as $inst ) {
				if ( $this->check_and_update_instance_status( $inst->instance_id, $inst->access_token ) ) {
					++$updated;
				}
			}
		}

		return array(
			'success' => true,
			/* translators: %d: number of instances updated */
			'message' => sprintf( esc_html__( '%d instances updated.', 'automation-web-platform' ), $updated ),
		);
	}

	/**
	 * Check and update instance status.
	 *
	 * @param string $iid Instance ID.
	 * @param string $atk Access Token.
	 * @return bool True if updated.
	 */
	public function check_and_update_instance_status( $iid, $atk ) {
		if ( ! $iid || ! $atk ) {
			return false;
		}

		$response = self::call_api( 'GET', 'session/info', $iid, $atk );

		if ( is_wp_error( $response ) ) {
			return $this->set_instance_state( $iid, 'offline', $response->get_error_message() );
		}

		$data    = $response;
		$raw     = strtoupper( isset( $data['status'] ) ? $data['status'] : '' );
		$map     = array(
			'WORKING'      => 'online',
			'ONLINE'       => 'online',
			'PAUSED'       => 'paused',
			'OFFLINE'      => 'offline',
			'SCAN_QR_CODE' => 'scan_qr_code',
		);
		$status  = isset( $map[ $raw ] ) ? $map[ $raw ] : 'checking';
		$display = isset( $data['metadata']['display_name'] ) ? $data['metadata']['display_name'] : ( isset( $data['display_name'] ) ? $data['display_name'] : '' );

		/* translators: %s: Display name or number */
		$msg = ( 'online' === $status && $display ) ? sprintf( esc_html__( 'Connected as %s', 'automation-web-platform' ), $display ) : (string) $raw;

		return $this->set_instance_state( $iid, $status, $msg );
	}

	/**
	 * Get session info for an instance.
	 *
	 * @param string $iid Instance ID.
	 * @param string $atk Access Token.
	 * @return array Result.
	 */
	public function wawp_get_session_me( $iid = '', $atk = '' ) {
		$instance_id  = $iid;
		$access_token = $atk;

		if ( ! $instance_id || ! $access_token ) {
			return array(
				'success' => false,
				'message' => __( 'Instance ID & Access Token are required.', 'automation-web-platform' ),
			);
		}

		$response = self::call_api( 'GET', 'session/me', $instance_id, $access_token );

		if ( is_wp_error( $response ) ) {
			return array(
				'success' => false,
				'message' => $response->get_error_message(),
			);
		}

		return array(
			'success' => true,
			'message' => 'Session info',
			'data'    => $response,
		);
	}

	/**
	 * Set instance state in DB.
	 *
	 * @param string $iid     Instance ID.
	 * @param string $status  Status.
	 * @param string $message Message.
	 * @return bool True on success.
	 */
	private function set_instance_state( $iid, $status, $message ) {
		WAWP()->db->update_row(
			'instance_data',
			array(
				'status'  => $status,
				'message' => $message,
			),
			array( 'instance_id' => $iid )
		);
		wp_cache_delete( 'wawp_all_instances', 'wawp_instances' );
		delete_transient( 'wawp_all_instances' );
		delete_transient( 'wawp_online_instances' );
		$this->update_login_redirect_based_on_instances();

		return true;
	}

	/**
	 * Get online instances.
	 *
	 * @return array Online instances.
	 */
	public function get_online_instances() {
		return WAWP()->instance_manager->get_online_instances_cached();
	}

	/**
	 * Get all instances.
	 *
	 * @return array All instances.
	 */
	public function get_all_instances() {
		return WAWP()->instance_manager->get_all_instances();
	}

	/**
	 * Get instance status.
	 *
	 * @param string $instance_id Instance ID.
	 * @return string|null Status.
	 */
	public function get_instance_status( $instance_id ) {
		global $wpdb;
		$table = $wpdb->prefix . 'wawp_instance_data';
		return WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT status FROM %i WHERE instance_id = %s', $table, $instance_id ), "wawp_inst_status_{$instance_id}", 'wawp_instances', 300 )[0]['status'] ?? null;
	}

	/**
	 * Get instance message.
	 *
	 * @param string $instance_id Instance ID.
	 * @return string|null Message.
	 */
	public function get_instance_message( $instance_id ) {
		global $wpdb;
		$table = $wpdb->prefix . 'wawp_instance_data';
		return WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT message FROM %i WHERE instance_id = %s', $table, $instance_id ), "wawp_inst_msg_{$instance_id}", 'wawp_instances', 300 )[0]['message'] ?? null;
	}

	/**
	 * Auto assign a WhatsApp instance to all mappings if it is the only instance or the only active instance.
	 */
	public function auto_assign_if_only_instance() {
		$all_instances    = $this->get_all_instances();
		$online_instances = $this->get_online_instances();

		$target_instance = null;

		if ( count( $all_instances ) === 1 ) {
			$target_instance = $all_instances[0];
		} elseif ( count( $online_instances ) === 1 ) {
			$target_instance = $online_instances[0];
		}

		if ( ! $target_instance ) {
			return;
		}

		$target_arr = (array) $target_instance;
		$db_id      = (string) $target_arr['id'];

		// 1. OTP Login routing.
		$otp_settings = $this->get_wawp_setting( WAWP_Settings_Registry::OTP_SETTINGS, array() );
		if ( ! is_array( $otp_settings ) ) {
			$otp_settings = $this->from_db( $otp_settings );
		}
		$otp_settings['instance'] = $db_id;
		$this->update_wawp_setting( WAWP_Settings_Registry::OTP_SETTINGS, $otp_settings );

		// 2. Signup routing.
		$signup_settings = $this->get_wawp_setting( WAWP_Settings_Registry::REGISTRATION_FORM_SETTINGS, array() );
		if ( ! is_array( $signup_settings ) ) {
			$signup_settings = $this->from_db( $signup_settings );
		}
		$signup_settings['selected_instance'] = $db_id;
		$this->update_wawp_setting( WAWP_Settings_Registry::REGISTRATION_FORM_SETTINGS, $signup_settings );

		// 3. Checkout routing.
		$this->update_wawp_setting( WAWP_Settings_Registry::CHECKOUT_SELECTED_INSTANCE, $db_id );

		// 4. General routing.
		$this->update_wawp_setting( WAWP_Settings_Registry::GENERAL_INSTANCE, $db_id );

		// 5. User notifications.
		$this->update_wawp_setting( WAWP_Settings_Registry::NOTIF_SELECTED_INSTANCE_IDS, $db_id );

		// 6. Admin notifications.
		$this->update_wawp_setting( WAWP_Settings_Registry::NOTIF_ADMIN_SELECTED_INSTANCE_IDS, $db_id );

		// Clear cache.
		if ( class_exists( 'WAWP_Menu' ) ) {
			WAWP_Menu::clear_all_dashboard_transients();
		} else {
			wp_cache_delete( 'wawp_otp_settings_raw', 'wawp_otp' );
			$user_id = get_current_user_id();
			if ( $user_id ) {
				wp_cache_delete( 'wawp_dashboard_data_full_' . $user_id, 'wawp_database' );
				delete_transient( 'wawp_dashboard_data_full_' . $user_id );
			}
		}
	}

	/**
	 * Update login redirect based on available instances.
	 */
	public function update_login_redirect_based_on_instances() {
		$online = $this->get_online_instances();
		if ( empty( $online ) ) {
			return;
		}
		$settings         = $this->get_wawp_setting( WAWP_Settings_Registry::OTP_SETTINGS, array() );
		$current_instance = isset( $settings['instance'] ) ? $settings['instance'] : '';
		$found            = false;
		foreach ( $online as $inst ) {
			if ( $inst->instance_id === $current_instance ) {
				$found = true;
				break;
			}
		}

		if ( ! $found ) {
			$settings['instance'] = $online[0]->instance_id;
			$this->update_wawp_setting( WAWP_Settings_Registry::OTP_SETTINGS, $settings );
		}
	}

	/**
	 * Get singleton instance.
	 *
	 * @return WAWP_Senders
	 */
	public static function get_instance() {
		return WAWP()->senders;
	}

	/**
	 * Check if tracking IDs are enabled.
	 *
	 * @return bool True if enabled.
	 */
	public static function tracking_ids_enabled() {
		if ( null === self::$tracking_ids_on ) {
			self::$tracking_ids_on = (bool) WAWP::instance()->get_wawp_setting( self::OPT_TRACKING_IDS, self::DEF_TRACKING_IDS );
		}

		return self::$tracking_ids_on;
	}

	/**
	 * Generate tracking IDs for a message.
	 *
	 * @param int $len Length of the IDs.
	 * @return string Tracking IDs string.
	 */
	public static function make_tracking_ids( $len = 8 ) {
		if ( ! self::tracking_ids_enabled() ) {
			return '';
		}
		$unique = wp_generate_password( $len, false, false );
		$msg_id = wp_generate_password( $len, false, false );

		return "\n\nUnique ID: {$unique}\nMessage ID: {$msg_id}";
	}

	/**
	 * Formats a phone number using the shared helper.
	 *
	 * @param string $raw Raw phone number.
	 * @return array Formatted phone.
	 */
	private static function format_phone_pair( $raw ) {
		return self::format_phone_number( $raw );
	}

	/**
	 * Checks if a phone is blocked using the shared helper.
	 *
	 * @param string $digits_only Digits only phone.
	 * @return bool True if blocked.
	 */
	private static function is_blocked( $digits_only ) {
		return self::is_phone_blocked( $digits_only );
	}

	/**
	 * Factory for Wawp API Calls using WordPress native functions.
	 *
	 * @param string $method       HTTP Method.
	 * @param string $path         API Path.
	 * @param string $instance_id  Instance ID.
	 * @param string $access_token Access Token.
	 * @param array  $body         Request body.
	 * @return array|WP_Error Response data.
	 */
	public static function call_api( $method, $path, $instance_id, $access_token, $body = array() ) {
		$base_url = 'https://api.wawp.net/v2/';
		$url      = $base_url . ltrim( $path, '/' );

		$query_args = array(
			'instance_id'  => $instance_id,
			'access_token' => $access_token,
			'bypass_check' => 'WP-NATIVE',
		);

		$url = add_query_arg( $query_args, $url );

		$args = array(
			'method'    => strtoupper( $method ),
			'timeout'   => 30,
			'headers'   => array(
				'Accept'       => 'application/json',
				'Content-Type' => 'application/json',
			),
			'sslverify' => true,
		);

		if ( in_array( strtoupper( $method ), array( 'POST', 'PUT', 'PATCH' ), true ) ) {
			$body['instance_id']  = $instance_id;
			$body['access_token'] = $access_token;
			$args['body']         = wp_json_encode( $body );
		}

		$response = wp_remote_request( $url, $args );

		if ( is_wp_error( $response ) ) {
			return $response;
		}

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

		if ( $code < 200 || $code >= 300 ) {
			$error_msg = isset( $data['message'] ) ? $data['message'] : ( isset( $data['error'] ) ? $data['error'] : 'API Error: ' . $code );
			return new WP_Error( 'api_error', $error_msg, $data );
		}

		return is_array( $data ) ? $data : array( 'raw' => $body );
	}

	/**
	 * Unified API Response Validator.
	 *
	 * @param array $response API response.
	 * @return bool True if success.
	 */
	public static function is_success( $response ) {
		return isset( $response['code'] ) && 'success' === $response['code'];
	}

	/**
	 * Send OTP via Wawp Auth Engine.
	 *
	 * @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 Result.
	 */
	public static function send_otp( $instance_id, $access_token, $recipient, $extra_params = array() ) {
		list( $digits, $chat_id ) = self::format_phone_pair( $recipient );
		if ( '' === $digits ) {
			return array(
				'status'  => 'error',
				'message' => 'Invalid phone number.',
			);
		}

		$payload = array( 'chatId' => $chat_id );

		// Pass the OTP language if provided (e.g. 'ar', 'en', 'fr', etc.).
		if ( ! empty( $extra_params['lang'] ) ) {
			$payload['lang'] = sanitize_text_field( $extra_params['lang'] );
		}

		// Pass the custom footer if enabled.
		if ( ! empty( $extra_params['footer_enabled'] ) && ! empty( $extra_params['footer'] ) ) {
			$payload['footer']         = sanitize_text_field( $extra_params['footer'] );
			$payload['footer_enabled'] = true;
		}

		$response = self::call_api( 'POST', 'auth/otp/send', $instance_id, $access_token, $payload );

		if ( is_wp_error( $response ) ) {
			return array(
				'status'  => 'error',
				'message' => $response->get_error_message(),
			);
		}

		if ( ! self::is_success( $response ) ) {
			return array(
				'status'  => 'error',
				'message' => isset( $response['message'] ) ? $response['message'] : esc_html__( 'Failed to send WhatsApp message.', 'automation-web-platform' ),
			);
		}

		return array(
			'status'        => 'success',
			'message'       => isset( $response['message'] ) ? $response['message'] : 'OTP Sent.',
			'full_response' => $response,
			'_code'         => 200,
		);
	}

	/**
	 * Send Auth List via Wawp Auth Engine.
	 *
	 * @param string $instance_id  Instance ID.
	 * @param string $access_token Access Token.
	 * @param string $recipient    Recipient phone.
	 * @param array  $list_data    List data.
	 * @return array Result.
	 */
	public static function send_auth_list( $instance_id, $access_token, $recipient, $list_data ) {
		list( $digits, $chat_id ) = self::format_phone_pair( $recipient );
		if ( '' === $digits ) {
			return array(
				'status'  => 'error',
				'message' => 'Invalid phone number.',
			);
		}

		$payload = array(
			'chatId'      => $chat_id,
			'title'       => isset( $list_data['title'] ) ? $list_data['title'] : 'Authentication Request',
			'description' => isset( $list_data['description'] ) ? $list_data['description'] : 'Please confirm your login attempt.',
			'footer'      => isset( $list_data['footer'] ) ? $list_data['footer'] : 'Wawp',
			'button'      => isset( $list_data['button'] ) ? $list_data['button'] : 'Verify Now',
			'item1'       => ( is_array( $list_data['item1'] ) ? ( isset( $list_data['item1']['title'] ) ? $list_data['item1']['title'] : '' ) : ( isset( $list_data['item1'] ) ? $list_data['item1'] : 'Approve Login' ) ),
			'item2'       => ( is_array( $list_data['item2'] ) ? ( isset( $list_data['item2']['title'] ) ? $list_data['item2']['title'] : '' ) : ( isset( $list_data['item2'] ) ? $list_data['item2'] : 'Deny Login' ) ),
		);

		$response = self::call_api( 'POST', 'auth/list/send', $instance_id, $access_token, $payload );

		if ( is_wp_error( $response ) ) {
			return array(
				'status'  => 'error',
				'message' => $response->get_error_message(),
			);
		}

		if ( ! self::is_success( $response ) ) {
			return array(
				'status'  => 'error',
				'message' => isset( $response['message'] ) ? $response['message'] : esc_html__( 'Failed to send WhatsApp list.', 'automation-web-platform' ),
			);
		}

		return array(
			'status'        => 'success',
			'full_response' => $response,
		);
	}

	/**
	 * Verify List Auth Status
	 *
	 * @param string $instance_id  Instance ID.
	 * @param string $access_token Access Token.
	 * @param string $auth_id      Auth ID.
	 * @return array Result.
	 */
	public static function check_auth_status( $instance_id, $access_token, $auth_id ) {
		$response = self::call_api( 'POST', 'auth/list/verify', $instance_id, $access_token, array( 'auth_id' => $auth_id ) );

		if ( is_wp_error( $response ) ) {
			return array(
				'status'  => 'error',
				'message' => $response->get_error_message(),
			);
		}

		if ( ! self::is_success( $response ) ) {
			return array(
				'status'  => 'error',
				'message' => isset( $response['message'] ) ? $response['message'] : 'Verification failed.',
			);
		}

		return array(
			'status'        => 'success',
			'full_response' => $response,
		);
	}

	/**
	 * Verify OTP
	 *
	 * @param string $instance_id  Instance ID.
	 * @param string $access_token Access Token.
	 * @param string $auth_id      Auth ID.
	 * @param string $phone        Phone number.
	 * @param string $otp          OTP code.
	 * @return array Result.
	 */
	public static function verify_otp( $instance_id, $access_token, $auth_id, $phone, $otp ) {
		list( $digits, ) = self::format_phone_pair( $phone );
		if ( '' === $digits ) {
			return array(
				'status'  => 'error',
				'message' => 'Invalid phone number.',
			);
		}

		$payload = array(
			'phone'   => $digits,
			'code'    => $otp,
			'auth_id' => $auth_id,
		);

		$response = self::call_api( 'POST', 'auth/otp/verify', $instance_id, $access_token, $payload );

		if ( is_wp_error( $response ) ) {
			return array(
				'status'  => 'error',
				'message' => $response->get_error_message(),
			);
		}

		if ( ! self::is_success( $response ) ) {
			return array(
				'status'  => 'error',
				'message' => isset( $response['message'] ) ? $response['message'] : esc_html__( 'API Error: Failed to send.', 'automation-web-platform' ),
			);
		}

		return array(
			'status'        => 'success',
			'full_response' => $response,
			'_code'         => 200,
		);
	}

	/**
	 * Main Message Sender.
	 *
	 * @param string $instance_id  Instance ID.
	 * @param string $access_token Access Token.
	 * @param string $recipient    Recipient phone.
	 * @param string $message      Message body.
	 * @param string $media_url    Optional media URL.
	 * @return array Result.
	 */
	public static function send_message( $instance_id, $access_token, $recipient, $message, $media_url = '' ) {
		if ( is_array( $media_url ) ) {
			$media_url = ! empty( $media_url ) ? reset( $media_url ) : '';
		}
		$media_url = trim( (string) $media_url );
		if ( '[]' === $media_url || 'null' === strtolower( $media_url ) ) {
			$media_url = '';
		}

		list( $digits, $chat_id ) = self::format_phone_pair( $recipient );
		if ( '' === $digits || '' === $chat_id ) {
			return array(
				'status'  => 'error',
				'message' => 'Invalid phone number.',
			);
		}

		if ( self::is_blocked( $digits ) ) {
			return array(
				'status'  => 'error',
				'message' => 'This number is blocked by the system.',
			);
		}

		// Prepare Content.
		$full_message = $message . self::make_tracking_ids();

		// Send Content.
		if ( ! empty( $media_url ) ) {
			$filename = basename( wp_parse_url( $media_url, PHP_URL_PATH ) );
			$ext      = strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) );
			$type     = ( 'pdf' === $ext ) ? 'pdf' : ( ( 'mp4' === $ext ) ? 'video' : 'image' );

			$mimetypes     = array(
				'pdf'   => 'application/pdf',
				'video' => 'video/mp4',
				'image' => 'image/jpeg',
			);
			$mimetype      = isset( $mimetypes[ $type ] ) ? $mimetypes[ $type ] : 'image/jpeg';
			$safe_filename = 'media_' . time() . '.' . $ext;

			// Encode non-ASCII chars in the URL path for the engine to fetch.
			$parsed_url = wp_parse_url( $media_url );
			$final_url  = $media_url;
			if ( isset( $parsed_url['path'] ) ) {
				$encoded_path = implode( '/', array_map( 'rawurlencode', explode( '/', $parsed_url['path'] ) ) );
				$final_url    = ( isset( $parsed_url['scheme'] ) ? $parsed_url['scheme'] . '://' : '' )
					. ( isset( $parsed_url['host'] ) ? $parsed_url['host'] : '' )
					. $encoded_path
					. ( isset( $parsed_url['query'] ) ? '?' . $parsed_url['query'] : '' );
			}
			$file_field = array(
				'url'      => $final_url,
				'filename' => $safe_filename,
				'mimetype' => $mimetype,
			);

			$payload  = array(
				'chatId'  => $chat_id,
				'file'    => $file_field,
				'caption' => $full_message,
			);
			$endpoint = "send/{$type}";
			$response = self::call_api( 'POST', $endpoint, $instance_id, $access_token, $payload );
		} else {
			$payload  = array(
				'chatId'  => $chat_id,
				'message' => $full_message,
			);
			$response = self::call_api( 'POST', 'send/text', $instance_id, $access_token, $payload );
		}

		if ( is_wp_error( $response ) ) {
			return array(
				'status'  => 'error',
				'message' => $response->get_error_message(),
			);
		}

		return array(
			'status'        => 'success',
			'message'       => isset( $response['message'] ) ? $response['message'] : 'Sent.',
			'full_response' => $response,
			'_code'         => 200,
		);
	}
}
// End of file.
