<?php
/**
 * Chat Widget Class.
 *
 * @package automation-web-platform
 */

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


/**
 * Class WAWP_Chat_Widget.
 */
class WAWP_Chat_Widget {
	use WAWP_Security_Trait;
	use WAWP_Settings_Handler;
	use WAWP_Phone_Helper_Trait;
	use WAWP_Logging_Trait;

	/**
	 * Option: Site visits.
	 *
	 * @var string
	 */
	private $option_site_visits;

	/**
	 * Option: Chat clicks.
	 *
	 * @var string
	 */
	private $option_chat_clicks;

	/**
	 * Option: Open WhatsApp clicks.
	 *
	 * @var string
	 */
	private $option_open_whatsapp;

	/**
	 * Option: Contact stats.
	 *
	 * @var string
	 */
	private $option_contact_stats;

	/**
	 * Option: Page stats.
	 *
	 * @var string
	 */
	private $option_page_stats;

	/**
	 * Option: Chat impressions.
	 *
	 * @var string
	 */
	private $option_chat_impressions;

	/**
	 * Option: Chat interactions.
	 *
	 * @var string
	 */
	private $option_chat_interactions;

	/**
	 * Option: Chat social clicks.
	 *
	 * @var string
	 */
	private $option_chat_social_clicks;

	/**
	 * Option: Chat device stats.
	 *
	 * @var string
	 */
	private $option_chat_device_stats;

	/**
	 * Option: Chat OS stats.
	 *
	 * @var string
	 */
	private $option_chat_os_stats;

	/**
	 * Option: Chat hour stats.
	 *
	 * @var string
	 */
	private $option_chat_hour_stats;

	/**
	 * Option: Chat day stats.
	 *
	 * @var string
	 */
	private $option_chat_day_stats;

	/**
	 * Option: Chat location stats.
	 *
	 * @var string
	 */
	private $option_chat_location_stats;

	/**
	 * Transient: Sessions.
	 *
	 * @var string
	 */
	private $transient_sessions;

	/**
	 * Session expiration in seconds.
	 *
	 * @var int
	 */
	private $session_expire_seconds = 300;

	/**
	 * Extended remix icons.
	 *
	 * @var array
	 */
	private $remix_icons_extended;

	/**
	 * WhatsApp chat icons.
	 *
	 * @var array
	 */
	private $chat_whatsapp_icons;

	/**
	 * Preset SVG icons.
	 *
	 * @var array
	 */
	private $preset_svgs;

	/**
	 * WAWP_Chat_Widget constructor.
	 */
	public function __construct() {
		$this->option_site_visits         = WAWP_Settings_Registry::CHAT_SITE_VISITS;
		$this->option_chat_clicks         = WAWP_Settings_Registry::CHAT_BUTTON_CLICKS;
		$this->option_open_whatsapp       = WAWP_Settings_Registry::CHAT_OPEN_WHATSAPP_CLICKS;
		$this->option_contact_stats       = WAWP_Settings_Registry::CHAT_CONTACT_STATS;
		$this->option_page_stats          = WAWP_Settings_Registry::CHAT_PAGE_STATS;
		$this->option_chat_impressions    = WAWP_Settings_Registry::CHAT_IMPRESSIONS;
		$this->option_chat_interactions   = WAWP_Settings_Registry::CHAT_INTERACTION_TIMES;
		$this->option_chat_social_clicks  = WAWP_Settings_Registry::CHAT_SOCIAL_CLICKS;
		$this->option_chat_device_stats   = WAWP_Settings_Registry::CHAT_DEVICE_STATS;
		$this->option_chat_os_stats       = WAWP_Settings_Registry::CHAT_OS_STATS;
		$this->option_chat_hour_stats     = WAWP_Settings_Registry::CHAT_HOUR_STATS;
		$this->option_chat_day_stats      = WAWP_Settings_Registry::CHAT_DAY_STATS;
		$this->option_chat_location_stats = WAWP_Settings_Registry::CHAT_LOCATION_STATS;
		$this->transient_sessions         = WAWP_Settings_Registry::CHAT_USER_SESSIONS;

		$this->remix_icons_extended = array(
			'ri-facebook-circle-fill' => array(
				'label' => 'Facebook',
				'color' => '#4267B2',
			),
			'ri-twitter-fill'         => array(
				'label' => 'Twitter (X)',
				'color' => '#1DA1F2',
			),
			'ri-instagram-fill'       => array(
				'label' => 'Instagram',
				'color' => '#C13584',
			),
			'ri-tiktok-fill'          => array(
				'label' => 'TikTok',
				'color' => '#010101',
			),
			'ri-linkedin-box-fill'    => array(
				'label' => 'LinkedIn',
				'color' => '#0A66C2',
			),
			'ri-youtube-fill'         => array(
				'label' => 'YouTube',
				'color' => '#FF0000',
			),
			'ri-telegram-fill'        => array(
				'label' => 'Telegram',
				'color' => '#229ED9',
			),
			'ri-github-fill'          => array(
				'label' => 'GitHub',
				'color' => '#171515',
			),
			'ri-mail-fill'            => array(
				'label' => 'Email',
				'color' => '#D44638',
			),
			'ri-phone-fill'           => array(
				'label' => 'Phone',
				'color' => '#4D4D4D',
			),
			'ri-global-fill'          => array(
				'label' => 'Website',
				'color' => '#555555',
			),
		);

		$this->chat_whatsapp_icons = array(
			'ri-whatsapp-line'           => 'WhatsApp (ri-whatsapp-line)',
			'ri-chat-2-line'             => 'Chat (ri-chat-2-line)',
			'ri-chat-3-line'             => 'Chat (ri-chat-3-line)',
			'ri-chat-4-line'             => 'Chat Dots (ri-chat-4-line)',
			'ri-discuss-line'            => 'Chat (ri-discuss-line)',
			'ri-chat-smile-2-line'       => 'Chat (ri-chat-smile-2-line)',
			'ri-send-plane-fill'         => 'Chat Dots (ri-send-plane-fill)',
			'ri-customer-service-2-line' => 'Chat Dots (ri-customer-service-2-line)',
			'ri-customer-service-line'   => 'Chat Dots (ri-customer-service-line)',
		);

		$this->preset_svgs = array(
			'whatsapp-line' => WAWP_UI_Helper::get_svg(
				'whatsapp-line',
				array(
					'width'  => 48,
					'height' => 48,
				)
			),
		);

		add_action( 'admin_init', array( $this, 'register_settings' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_scripts' ) );
		add_action( 'wp_footer', array( $this, 'render_whatsapp_button' ) );
		add_filter( 'wawp_frontend_global_vars', array( $this, 'add_frontend_global_vars' ) );
	}

	/**
	 * Get React settings data for the chat widget.
	 *
	 * @return array
	 */
	public function get_react_settings_data() {
		$defaults = WAWP_Settings_Registry::get_defaults();
		return array(
			'settings'    => array(
				'wawp_enable_button'        => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_ENABLE, $defaults[ WAWP_Settings_Registry::CHAT_ENABLE ] ),
				'wawp_whatsapp_numbers'     => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_NUMBERS, $defaults[ WAWP_Settings_Registry::CHAT_NUMBERS ] ),
				'wawp_whatsapp_messages'    => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_MESSAGES, $defaults[ WAWP_Settings_Registry::CHAT_MESSAGES ] ),
				'wawp_user_names'           => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_USER_NAMES, $defaults[ WAWP_Settings_Registry::CHAT_USER_NAMES ] ),
				'wawp_user_roles'           => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_USER_ROLES, $defaults[ WAWP_Settings_Registry::CHAT_USER_ROLES ] ),
				'wawp_user_avatars'         => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_USER_AVATARS, $defaults[ WAWP_Settings_Registry::CHAT_USER_AVATARS ] ),

				'wawp_whatsapp_header'      => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_HEADER, $defaults[ WAWP_Settings_Registry::CHAT_HEADER ] ),
				'wawp_welcome_message'      => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_WELCOME_MSG, $defaults[ WAWP_Settings_Registry::CHAT_WELCOME_MSG ] ),
				'wawp_reply_time_text'      => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_REPLY_TIME, $defaults[ WAWP_Settings_Registry::CHAT_REPLY_TIME ] ),
				'wawp_avatar_url'           => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_AVATAR_URL, $defaults[ WAWP_Settings_Registry::CHAT_AVATAR_URL ] ),
				'wawp_social_intro_text'    => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_SOCIAL_INTRO, $defaults[ WAWP_Settings_Registry::CHAT_SOCIAL_INTRO ] ),
				'wawp_social_icons'         => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_SOCIAL_ICONS, $defaults[ WAWP_Settings_Registry::CHAT_SOCIAL_ICONS ] ),
				'wawp_social_button_style'  => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_SOCIAL_STYLE, $defaults[ WAWP_Settings_Registry::CHAT_SOCIAL_STYLE ] ),
				'wawp_social_layout'        => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_SOCIAL_LAYOUT, $defaults[ WAWP_Settings_Registry::CHAT_SOCIAL_LAYOUT ] ),
				'wawp_whatsapp_icon_class'  => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_ICON_CLASS, $defaults[ WAWP_Settings_Registry::CHAT_ICON_CLASS ] ),
				'wawp_button_bg_color'      => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_BG_COLOR, $defaults[ WAWP_Settings_Registry::CHAT_BG_COLOR ] ),
				'wawp_icon_color'           => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_ICON_COLOR, $defaults[ WAWP_Settings_Registry::CHAT_ICON_COLOR ] ),
				'wawp_button_size'          => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_BTN_SIZE, $defaults[ WAWP_Settings_Registry::CHAT_BTN_SIZE ] ),
				'wawp_corner_radius'        => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_CORNER_RADIUS, $defaults[ WAWP_Settings_Registry::CHAT_CORNER_RADIUS ] ),
				'wawp_button_position'      => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_POSITION, $defaults[ WAWP_Settings_Registry::CHAT_POSITION ] ),
				'wawp_display_desktop'      => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_DISPLAY_DESKTOP, $defaults[ WAWP_Settings_Registry::CHAT_DISPLAY_DESKTOP ] ),
				'wawp_display_mobile'       => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_DISPLAY_MOBILE, $defaults[ WAWP_Settings_Registry::CHAT_DISPLAY_MOBILE ] ),
				'wawp_trigger_on_all_pages' => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_TRIGGER_ALL, $defaults[ WAWP_Settings_Registry::CHAT_TRIGGER_ALL ] ),
				'wawp_button_bottom_offset' => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_BOTTOM_OFFSET, $defaults[ WAWP_Settings_Registry::CHAT_BOTTOM_OFFSET ] ),
				'wawp_page_conditions'      => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_PAGE_CONDITIONS, $defaults[ WAWP_Settings_Registry::CHAT_PAGE_CONDITIONS ] ),
				'wawp_disable_powered_by'   => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_DISABLE_POWERED_BY, $defaults[ WAWP_Settings_Registry::CHAT_DISABLE_POWERED_BY ] ),
			),
			'optionNames' => array(
				'wawp_enable_button'        => WAWP_Settings_Registry::CHAT_ENABLE,
				'wawp_whatsapp_numbers'     => WAWP_Settings_Registry::CHAT_NUMBERS,
				'wawp_whatsapp_messages'    => WAWP_Settings_Registry::CHAT_MESSAGES,
				'wawp_user_names'           => WAWP_Settings_Registry::CHAT_USER_NAMES,
				'wawp_user_roles'           => WAWP_Settings_Registry::CHAT_USER_ROLES,
				'wawp_user_avatars'         => WAWP_Settings_Registry::CHAT_USER_AVATARS,

				'wawp_whatsapp_header'      => WAWP_Settings_Registry::CHAT_HEADER,
				'wawp_welcome_message'      => WAWP_Settings_Registry::CHAT_WELCOME_MSG,
				'wawp_reply_time_text'      => WAWP_Settings_Registry::CHAT_REPLY_TIME,
				'wawp_avatar_url'           => WAWP_Settings_Registry::CHAT_AVATAR_URL,
				'wawp_social_intro_text'    => WAWP_Settings_Registry::CHAT_SOCIAL_INTRO,
				'wawp_social_icons'         => WAWP_Settings_Registry::CHAT_SOCIAL_ICONS,
				'wawp_social_button_style'  => WAWP_Settings_Registry::CHAT_SOCIAL_STYLE,
				'wawp_social_layout'        => WAWP_Settings_Registry::CHAT_SOCIAL_LAYOUT,
				'wawp_whatsapp_icon_class'  => WAWP_Settings_Registry::CHAT_ICON_CLASS,
				'wawp_button_bg_color'      => WAWP_Settings_Registry::CHAT_BG_COLOR,
				'wawp_icon_color'           => WAWP_Settings_Registry::CHAT_ICON_COLOR,
				'wawp_button_size'          => WAWP_Settings_Registry::CHAT_BTN_SIZE,
				'wawp_corner_radius'        => WAWP_Settings_Registry::CHAT_CORNER_RADIUS,
				'wawp_button_position'      => WAWP_Settings_Registry::CHAT_POSITION,
				'wawp_display_desktop'      => WAWP_Settings_Registry::CHAT_DISPLAY_DESKTOP,
				'wawp_display_mobile'       => WAWP_Settings_Registry::CHAT_DISPLAY_MOBILE,
				'wawp_trigger_on_all_pages' => WAWP_Settings_Registry::CHAT_TRIGGER_ALL,
				'wawp_button_bottom_offset' => WAWP_Settings_Registry::CHAT_BOTTOM_OFFSET,
				'wawp_page_conditions'      => WAWP_Settings_Registry::CHAT_PAGE_CONDITIONS,
				'wawp_disable_powered_by'   => WAWP_Settings_Registry::CHAT_DISABLE_POWERED_BY,
			),
			'remix_icons' => $this->remix_icons_extended,
			'chat_icons'  => $this->chat_whatsapp_icons,
			'pages'       => $this->get_all_pages_simplified(),
			'stats'       => array(
				'total_views'    => (int) $this->get_wawp_setting( $this->option_chat_impressions, 0 ),
				'total_clicks'   => $this->get_chat_clicks(),
				'open_whatsapp'  => (int) $this->get_wawp_setting( $this->option_open_whatsapp, 0 ),
				'contact_stats'  => $this->get_wawp_setting( $this->option_contact_stats, array() ),
				'page_stats'     => $this->get_wawp_setting( $this->option_page_stats, array() ),
				'social_clicks'  => $this->get_wawp_setting( $this->option_chat_social_clicks, array() ),
				'device_stats'   => $this->get_wawp_setting( $this->option_chat_device_stats, array() ),
				'os_stats'       => $this->get_wawp_setting( $this->option_chat_os_stats, array() ),
				'hour_stats'     => $this->get_wawp_setting( $this->option_chat_hour_stats, array() ),
				'day_stats'      => $this->get_wawp_setting( $this->option_chat_day_stats, array() ),
				'location_stats' => $this->get_wawp_setting( $this->option_chat_location_stats, array() ),
			),
			'i18n'        => array(
				'chatWidget'                  => esc_html__( 'WhatsApp Chat Widget', 'automation-web-platform' ),
				'poweredBy'                   => esc_html__( 'Powered by', 'automation-web-platform' ),
				// Isolated strings for ChatWidget settings page.
				'chatWidgetDesc'              => esc_html__( 'Add direct WhatsApp chat, social media links, and more with interaction tracking.', 'automation-web-platform' ),
				'changesDeployed'             => esc_html__( 'Changes Deployed', 'automation-web-platform' ),
				'saving'                      => esc_html__( 'Saving...', 'automation-web-platform' ),
				'saveChanges'                 => esc_html__( 'Save Settings', 'automation-web-platform' ),
				'whatsappTab'                 => esc_html__( 'WhatsApp', 'automation-web-platform' ),
				'socialTab'                   => esc_html__( 'Social Links', 'automation-web-platform' ),
				'analyticsTab'                => esc_html__( 'Analytics', 'automation-web-platform' ),
				'appearanceTab'               => esc_html__( 'Appearance', 'automation-web-platform' ),
				'conditionsTab'               => esc_html__( 'Conditions', 'automation-web-platform' ),
				'whatsappWidgetStatus'        => esc_html__( 'WhatsApp Widget Status', 'automation-web-platform' ),
				'whatsappWidgetStatusDesc'    => esc_html__( 'General toggle to display or hide the chat widget across your site.', 'automation-web-platform' ),
				'whatsappWidgetActiveMsg'     => esc_html__( 'The WhatsApp floating button is currently active on your website.', 'automation-web-platform' ),
				'whatsappWidgetInactiveMsg'   => esc_html__( 'The WhatsApp floating button is currently hidden from your visitors.', 'automation-web-platform' ),
				'accountConfigTitle'          => esc_html__( 'Account Configuration', 'automation-web-platform' ),
				'accountConfigDesc'           => esc_html__( 'Configure your primary WhatsApp account details and display settings.', 'automation-web-platform' ),
				'widgetHeadline'              => esc_html__( 'Widget Headline', 'automation-web-platform' ),
				'replyTimeLabel'              => esc_html__( 'Reply Time Text', 'automation-web-platform' ),
				'replyTimePlaceholder'        => esc_html__( 'e.g. Typically replies in minutes', 'automation-web-platform' ),
				'welcomeMessageLabel'         => esc_html__( 'Welcome Message', 'automation-web-platform' ),
				'headerAvatar'                => esc_html__( 'Header Avatar', 'automation-web-platform' ),
				'headerAvatarDesc'            => esc_html__( 'This image appears at the top of the chat window. Recommended size 100x100px.', 'automation-web-platform' ),
				'changePhoto'                 => esc_html__( 'Change Photo', 'automation-web-platform' ),
				'supportAgentsTitle'          => esc_html__( 'Support Agents', 'automation-web-platform' ),
				'supportAgentsDesc'           => esc_html__( 'Manage multiple WhatsApp numbers and support roles.', 'automation-web-platform' ),
				'addNewAgent'                 => esc_html__( 'Add New Agent', 'automation-web-platform' ),
				'agentName'                   => esc_html__( 'Name', 'automation-web-platform' ),
				'whatsappNumber'              => esc_html__( 'WhatsApp Number', 'automation-web-platform' ),
				'roleTitle'                   => esc_html__( 'Role / Title', 'automation-web-platform' ),
				'rolePlaceholder'             => esc_html__( 'e.g. Sales', 'automation-web-platform' ),
				'prefilledMessage'            => esc_html__( 'Pre-filled Message', 'automation-web-platform' ),
				'prefilledMessagePlaceholder' => esc_html__( 'I have a question about...', 'automation-web-platform' ),
				'avatarLabel'                 => esc_html__( 'Avatar', 'automation-web-platform' ),
				'uploadButton'                => esc_html__( 'Upload', 'automation-web-platform' ),
				'removeAgent'                 => esc_html__( 'Remove Agent', 'automation-web-platform' ),
				'doneButton'                  => esc_html__( 'Done', 'automation-web-platform' ),
				'agentNamePrefix'             => esc_html__( 'Name:', 'automation-web-platform' ),
				'agentNumberPrefix'           => esc_html__( 'Number:', 'automation-web-platform' ),
				'agentRolePrefix'             => esc_html__( 'Role:', 'automation-web-platform' ),
				'editButton'                  => esc_html__( 'Edit', 'automation-web-platform' ),
				'noAgentsAdded'               => esc_html__( 'No agents added', 'automation-web-platform' ),
				'noAgentsAddedDesc'           => esc_html__( 'Add at least one WhatsApp number to show the widget.', 'automation-web-platform' ),
				'socialChannels'              => esc_html__( 'Social Channels', 'automation-web-platform' ),
				'socialChannelsDesc'          => esc_html__( 'Connect your other social platforms to provide more ways to reach you.', 'automation-web-platform' ),
				'addSocialLink'               => esc_html__( 'Add Social Link', 'automation-web-platform' ),
				'iconPlatform'                => esc_html__( 'Icon / Platform', 'automation-web-platform' ),
				'profileLinkUrl'              => esc_html__( 'Profile Link URL', 'automation-web-platform' ),
				'noSocialLinks'               => esc_html__( 'No social links added', 'automation-web-platform' ),
				'noSocialLinksDesc'           => esc_html__( 'Add links to your social profiles to show them in the widget.', 'automation-web-platform' ),
				'displayStyles'               => esc_html__( 'Display Styles', 'automation-web-platform' ),
				'displayStylesDesc'           => esc_html__( 'Choose how your social icons should appear in the widget.', 'automation-web-platform' ),
				'iconShapeStyle'              => esc_html__( 'Icon Shape & Style', 'automation-web-platform' ),
				'styleRoundWhite'             => esc_html__( 'Round White', 'automation-web-platform' ),
				'styleSquareWhite'            => esc_html__( 'Square White', 'automation-web-platform' ),
				'styleOutline'                => esc_html__( 'Outline', 'automation-web-platform' ),
				'styleBrandColors'            => esc_html__( 'Brand Colors', 'automation-web-platform' ),
				'socialLayout'                => esc_html__( 'Social Layout', 'automation-web-platform' ),
				'layoutVertical'              => esc_html__( 'Vertical (Above)', 'automation-web-platform' ),
				'layoutVerticalDesc'          => esc_html__( 'Text above icons', 'automation-web-platform' ),
				'layoutHorizontal'            => esc_html__( 'Horizontal (Inline)', 'automation-web-platform' ),
				'layoutHorizontalDesc'        => esc_html__( 'Text before icons', 'automation-web-platform' ),
				'socialIntroText'             => esc_html__( 'Social Intro Text', 'automation-web-platform' ),
				'engagementAnalytics'         => esc_html__( 'Engagement Analytics', 'automation-web-platform' ),
				'engagementAnalyticsDesc'     => esc_html__( 'Insights into how visitors are interacting with your chat widget.', 'automation-web-platform' ),
				'totalViews'                  => esc_html__( 'Total Views', 'automation-web-platform' ),
				'totalViewsDesc'              => esc_html__( 'Total widget impressions across your site.', 'automation-web-platform' ),
				'viewsBadge'                  => esc_html__( 'Views', 'automation-web-platform' ),
				'widgetOpens'                 => esc_html__( 'Widget Opens', 'automation-web-platform' ),
				'widgetOpensDesc'             => esc_html__( 'Number of times visitors clicked to see agents.', 'automation-web-platform' ),
				'clicksBadge'                 => esc_html__( 'Clicks', 'automation-web-platform' ),
				'whatsappChats'               => esc_html__( 'WhatsApp Chats', 'automation-web-platform' ),
				'whatsappChatsDesc'           => esc_html__( 'Direct redirections to the WhatsApp API.', 'automation-web-platform' ),
				'leadsBadge'                  => esc_html__( 'Leads', 'automation-web-platform' ),
				'socialEngagement'            => esc_html__( 'Social Engagement', 'automation-web-platform' ),
				'socialEngagementDesc'        => esc_html__( 'Total clicks on external social link icons.', 'automation-web-platform' ),
				'socialBadge'                 => esc_html__( 'Social', 'automation-web-platform' ),
				'interactionActivity'         => esc_html__( 'Interaction Activity', 'automation-web-platform' ),
				'interactionActivityDesc'     => esc_html__( 'Peak engagement times and days.', 'automation-web-platform' ),
				'activeDays'                  => esc_html__( 'Active Days', 'automation-web-platform' ),
				'hourlyTrends'                => esc_html__( 'Hourly Trends', 'automation-web-platform' ),
				'topPerformingPages'          => esc_html__( 'Top Performing Pages', 'automation-web-platform' ),
				'clicksLabel'                 => esc_html__( 'Clicks', 'automation-web-platform' ),
				'waOpenLabel'                 => esc_html__( 'WA Open', 'automation-web-platform' ),
				'noPageData'                  => esc_html__( 'No page-specific data yet', 'automation-web-platform' ),
				'topSupportAgents'            => esc_html__( 'Top Support Agents', 'automation-web-platform' ),
				'leadsLabel'                  => esc_html__( 'Leads', 'automation-web-platform' ),
				'noAgentActivity'             => esc_html__( 'No agent activity recorded yet', 'automation-web-platform' ),
				'deviceDistribution'          => esc_html__( 'Device Distribution', 'automation-web-platform' ),
				'deviceDistributionDesc'      => esc_html__( 'User traffic split by device type.', 'automation-web-platform' ),
				'desktopLabel'                => esc_html__( 'Desktop', 'automation-web-platform' ),
				'mobileLabel'                 => esc_html__( 'Mobile', 'automation-web-platform' ),
				'tabletLabel'                 => esc_html__( 'Tablet', 'automation-web-platform' ),
				'buttonAppearance'            => esc_html__( 'Button Appearance', 'automation-web-platform' ),
				'buttonAppearanceDesc'        => esc_html__( 'Customize the look and feel of your floating WhatsApp button.', 'automation-web-platform' ),
				'buttonIcon'                  => esc_html__( 'Button Icon', 'automation-web-platform' ),
				'buttonPosition'              => esc_html__( 'Button Position', 'automation-web-platform' ),
				'leftSide'                    => esc_html__( 'Left Side', 'automation-web-platform' ),
				'rightSide'                   => esc_html__( 'Right Side', 'automation-web-platform' ),
				'buttonSize'                  => esc_html__( 'Button Size', 'automation-web-platform' ),
				'cornerRadius'                => esc_html__( 'Corner Radius', 'automation-web-platform' ),
				'verticalOffset'              => esc_html__( 'Vertical Offset', 'automation-web-platform' ),
				'backgroundColor'             => esc_html__( 'Background Color', 'automation-web-platform' ),
				'iconColor'                   => esc_html__( 'Icon Color', 'automation-web-platform' ),
				'showOnDesktop'               => esc_html__( 'Show on Desktop', 'automation-web-platform' ),
				'showOnDesktopDesc'           => esc_html__( 'Show widget for computer visitors', 'automation-web-platform' ),
				'showOnMobile'                => esc_html__( 'Show on Mobile', 'automation-web-platform' ),
				'showOnMobileDesc'            => esc_html__( 'Show widget for mobile visitors', 'automation-web-platform' ),
				'hideBranding'                => __( 'Hide "Powered by" Branding', 'automation-web-platform' ),
				'hideBrandingDesc'            => esc_html__( 'Remove the WAWP branding from the chat widget footer.', 'automation-web-platform' ),
				'paidPlan'                    => esc_html__( 'Paid Plan', 'automation-web-platform' ),
				'visibilityRules'             => esc_html__( 'Visibility Rules', 'automation-web-platform' ),
				'visibilityRulesDesc'         => esc_html__( 'Control exactly which pages your chat button appears on.', 'automation-web-platform' ),
				'activeAllPagesMsg'           => esc_html__( 'The widget is currently active on all public pages.', 'automation-web-platform' ),
				'hiddenRestrictedPagesMsg'    => esc_html__( 'Hidden on {count} restricted page(s).', 'automation-web-platform' ),
				'exclusionList'               => esc_html__( 'Exclusion List', 'automation-web-platform' ),
				'exclusionListPlaceholder'    => esc_html__( 'Search and select pages to hide widget on...', 'automation-web-platform' ),
				'exclusionWarning'            => esc_html__( "Visitors won't see the chat widget on the selected pages above.", 'automation-web-platform' ),
				'letsChat'                    => esc_html__( "Let's chat", 'automation-web-platform' ),
				'welcomeMessage'              => esc_html__( 'How may we help you?', 'automation-web-platform' ),
				'replyTimeText'               => esc_html__( 'Typically replies within minutes', 'automation-web-platform' ),
				'supportAgent'                => esc_html__( 'Support Agent', 'automation-web-platform' ),
				'online'                      => esc_html__( 'Online', 'automation-web-platform' ),
				'addNumberToPreview'          => esc_html__( 'Add a number to preview', 'automation-web-platform' ),
				'reachUsOn'                   => esc_html__( 'Reach us on:', 'automation-web-platform' ),
			),
		);
	}

	/**
	 * Get all pages in a simplified format for the React dropdown.
	 *
	 * @return array
	 */
	private function get_all_pages_simplified() {
		$pages     = get_pages(
			array(
				'post_status' => 'publish',
				'sort_column' => 'post_title',
			)
		);
		$formatted = array();
		if ( ! empty( $pages ) ) {
			foreach ( $pages as $page ) {
				$formatted[] = array(
					'ID'         => $page->ID,
					'post_title' => $page->post_title,
				);
			}
		}
		return $formatted;
	}

	/**
	 * AJAX Handler to increment chat button clicks.
	 */
	public function ajax_increment_chat_clicks() {
		check_ajax_referer( 'wawp_chat_nonce', 'nonce' );
		$res = $this->handle_increment_chat_clicks_return( array_map( 'sanitize_text_field', wp_unslash( $_POST ) ) );
		$this->send_success( '', $res );
	}

	/**
	 * Handle incrementing chat clicks.
	 *
	 * @param array $data Input data.
	 * @return array
	 */
	public function handle_increment_chat_clicks_return( $data ) {
		WAWP::instance()->stats_manager->increment_stat( $this->option_chat_clicks );
		$c = (int) $this->get_wawp_setting( $this->option_chat_clicks, 0 ) + 1;
		$this->record_page_stat_logic( 'chat_clicks', $data['page_id'] ?? 0 );
		return array(
			'success' => true,
			'clicks'  => $c,
		);
	}

	/**
	 * Get total chat button clicks.
	 *
	 * @return int
	 */
	private function get_chat_clicks() {
		return (int) $this->get_wawp_setting( $this->option_chat_clicks, 0 );
	}

	/**
	 * AJAX Handler for contact selection click.
	 */
	public function ajax_contact_click() {
		check_ajax_referer( 'wawp_chat_nonce', 'nonce' );
		$res = $this->handle_contact_click_return( array_map( 'sanitize_text_field', wp_unslash( $_POST ) ) );
		if ( $res['success'] ) {
			$this->send_success( $res['message'] );
		} else {
			$this->send_error( $res['message'] );
		}
	}

	/**
	 * Handle contact click recording.
	 *
	 * @param array $data Input data.
	 * @return array
	 */
	public function handle_contact_click_return( $data ) {
		$phone = self::get_digits_only( $data['phone'] ?? '' );
		if ( ! $phone ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'No phone', 'automation-web-platform' ),
			);
		}
		$stats = $this->get_wawp_setting( $this->option_contact_stats, array() );
		if ( ! isset( $stats[ $phone ] ) ) {
			$stats[ $phone ] = array(
				'name'          => sanitize_text_field( $data['name'] ?? 'Unknown' ),
				'chat_clicks'   => 0,
				'open_whatsapp' => 0,
			);
		}
		++$stats[ $phone ]['chat_clicks'];
		$this->update_wawp_setting( $this->option_contact_stats, $stats );
		$this->record_page_stat_logic( 'chat_clicks', $data['page_id'] ?? 0 );
		return array(
			'success' => true,
			'message' => esc_html__( 'Contact click recorded', 'automation-web-platform' ),
		);
	}

	/**
	 * AJAX Handler for opening WhatsApp click.
	 */
	public function ajax_open_whatsapp_click() {
		check_ajax_referer( 'wawp_chat_nonce', 'nonce' );
		$res = $this->handle_open_whatsapp_click_return( array_map( 'sanitize_text_field', wp_unslash( $_POST ) ) );
		if ( $res['success'] ) {
			$this->send_success( '', $res );
		} else {
			$this->send_error( $res['message'] );
		}
	}

	/**
	 * Handle recording WhatsApp open clicks.
	 *
	 * @param array $data Input data.
	 * @return array
	 */
	public function handle_open_whatsapp_click_return( $data ) {
		$phone = sanitize_text_field( $data['phone'] ?? '' );
		if ( ! $phone ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'No phone', 'automation-web-platform' ),
			);
		}
		$stats = $this->get_wawp_setting( $this->option_contact_stats, array() );
		if ( isset( $stats[ $phone ] ) ) {
			++$stats[ $phone ]['open_whatsapp'];
			$this->update_wawp_setting( $this->option_contact_stats, $stats );
		}

		WAWP::instance()->stats_manager->increment_stat( $this->option_open_whatsapp );
		$new_global = (int) $this->get_wawp_setting( $this->option_open_whatsapp, 0 ) + 1;
		$this->record_page_stat_logic( 'open_whatsapp', $data['page_id'] ?? 0 );
		$this->record_location();
		return array(
			'success'    => true,
			'total_open' => $new_global,
		);
	}

	/**
	 * AJAX Handler for tracking chat impression.
	 */
	public function ajax_track_chat_impression() {
		check_ajax_referer( 'wawp_chat_nonce', 'nonce' );
		$this->handle_track_chat_impression_return( array_map( 'sanitize_text_field', wp_unslash( $_POST ) ) );

		$this->send_success();
	}

	/**
	 * Handle chat impression tracking logic.
	 *
	 * @param array $data Input data.
	 * @return array
	 */
	public function handle_track_chat_impression_return( $data ) {
		$ip       = $this->get_client_ip();
		$rate_key = 'wawp_imp_rate_' . md5( $ip );
		if ( wp_cache_get( $rate_key, 'wawp_chat' ) || get_transient( $rate_key ) ) {
			return array(
				'success' => true,
				'skipped' => true,
			);
		}
		wp_cache_set( $rate_key, 1, 'wawp_chat', 1800 );
		set_transient( $rate_key, 1, 1800 );

		WAWP::instance()->stats_manager->increment_stat( $this->option_chat_impressions );
		$this->increment_stat_option( $this->option_chat_device_stats, sanitize_text_field( $data['device'] ?? 'Unknown' ) );
		$this->increment_stat_option( $this->option_chat_os_stats, sanitize_text_field( $data['os'] ?? 'Unknown' ) );
		$this->increment_stat_option( $this->option_chat_hour_stats, current_time( 'H' ) );
		$this->increment_stat_option( $this->option_chat_day_stats, current_time( 'l' ) );
		return array( 'success' => true );
	}

	/**
	 * AJAX Handler for tracking social icon click.
	 */
	public function ajax_track_social_click() {
		check_ajax_referer( 'wawp_chat_nonce', 'nonce' );
		$this->handle_track_social_click_return( array_map( 'sanitize_text_field', wp_unslash( $_POST ) ) );

		$this->send_success();
	}

	/**
	 * Handle social click tracking logic.
	 *
	 * @param array $data Input data.
	 * @return array
	 */
	public function handle_track_social_click_return( $data ) {
		$icon = sanitize_text_field( $data['icon'] ?? '' );
		if ( $icon ) {
			$this->increment_stat_option( $this->option_chat_social_clicks, $icon );
		}
		return array( 'success' => true );
	}

	/**
	 * AJAX Handler for clearing widget stats.
	 */
	public function ajax_clear_stats() {
		$this->check_permissions( 'wawp_nonce' );
		$res = $this->handle_clear_stats_return();
		$this->send_success( $res['message'] );
	}

	/**
	 * Handle clearing stats logic.
	 *
	 * @return array
	 */
	public function handle_clear_stats_return() {
		foreach ( array( $this->option_site_visits, $this->option_chat_clicks, $this->option_open_whatsapp, $this->option_chat_impressions ) as $o ) {
			update_option( $o, 0 );
		}
		foreach ( array( $this->option_contact_stats, $this->option_page_stats, $this->option_chat_interactions, $this->option_chat_social_clicks, $this->option_chat_device_stats, $this->option_chat_os_stats, $this->option_chat_hour_stats, $this->option_chat_day_stats, $this->option_chat_location_stats ) as $o ) {
			update_option( $o, array() );
		}
		delete_transient( $this->transient_sessions );
		return array(
			'success' => true,
			'message' => esc_html__( 'Stats cleared.', 'automation-web-platform' ),
		);
	}

	/**
	 * Increment a specific stat in an option array.
	 *
	 * @param string $name Option name.
	 * @param string $key  Stat key.
	 */
	private function increment_stat_option( $name, $key ) {
		WAWP::instance()->stats_manager->increment_array_stat( $name, $key );
	}

	/**
	 * Record user location based on IP.
	 */
	private function record_location() {
		$ip = $this->get_client_ip();
		if ( ! $ip ) {
			return;
		}

		$cache_key = 'wawp_chat_location_stat_' . md5( $ip );
		if ( wp_cache_get( $cache_key, 'wawp_chat' ) ) {
			return; // Only record once per IP per short interval.
		}

		WAWP::instance()->stats_manager->increment_array_stat( $this->option_chat_location_stats, $ip );
		wp_cache_set( $cache_key, true, 'wawp_chat', 3600 );
	}

	/**
	 * Record page-specific stat logic.
	 *
	 * @param string $field Stat field.
	 * @param int    $pid   Page ID.
	 */
	private function record_page_stat_logic( $field, $pid = 0 ) {
		if ( ! $pid ) {
			global $post;
			$pid = $post->ID ?? get_queried_object_id() ?? 0;
		}

		WAWP::instance()->stats_manager->increment_multi_array_stat( $this->option_page_stats, $pid, $field );
	}

	/**
	 * Enqueue frontend scripts and styles for the chat widget.
	 */
	public function enqueue_frontend_scripts() {
		wp_enqueue_style( 'wawp-chat-widget-style', WAWP_PLUGIN_URL . 'assets/css/style.css', array(), WAWP_PLUGIN_VERSION );
		wp_enqueue_script( 'wawp-qrcodejs', WAWP_PLUGIN_URL . 'assets/js/resources/qrcode.js', array( 'jquery' ), '1.0.1', true );
		wp_enqueue_script( 'wawp-chat-widget-script', WAWP_PLUGIN_URL . 'assets/js/script.js', array( 'jquery', 'wawp-qrcodejs' ), WAWP_PLUGIN_VERSION, true );
		wp_enqueue_style( 'wawp-remix-icon', WAWP_PLUGIN_URL . 'assets/css/resources/remixicon.css', array(), '4.6.0' );
	}

	/**
	 * Add global vars to central data hub.
	 *
	 * @param array $vars Global variables array.
	 * @return array
	 */
	public function add_frontend_global_vars( $vars ) {
		global $post;
		$pid                   = $post->ID ?? get_queried_object_id() ?? 0;
		$vars['wawp_ajax_obj'] = array(
			'ajax_url'    => admin_url( 'admin-ajax.php' ),
			'rest_url'    => esc_url_raw( rest_url( 'wawp/v1/chat-widget' ) ),
			'current_pid' => $pid,
			'nonce'       => wp_create_nonce( 'wp_rest' ),
		);
		return $vars;
	}

	/**
	 * Register settings for the chat widget.
	 */
	public function register_settings() {
		$settings = array(
			'wawp_whatsapp_numbers'    => array(
				'default'           => array(),
				'sanitize_callback' => array( $this, 'sanitize_array' ),
			),
			'wawp_whatsapp_messages'   => array(
				'default'           => array(),
				'sanitize_callback' => array( $this, 'sanitize_array' ),
			),
			'wawp_user_names'          => array(
				'default'           => array(),
				'sanitize_callback' => array( $this, 'sanitize_array' ),
			),
			'wawp_user_roles'          => array(
				'default'           => array(),
				'sanitize_callback' => array( $this, 'sanitize_array' ),
			),
			'wawp_user_avatars'        => array(
				'default'           => array(),
				'sanitize_callback' => array( $this, 'sanitize_array' ),
			),
			'wawp_social_button_style' => array(
				'default'           => 'round',
				'sanitize_callback' => 'sanitize_text_field',
			),
			'wawp_social_layout'       => array(
				'default'           => 'vertical',
				'sanitize_callback' => 'sanitize_text_field',
			),
			'wawp_social_intro_text'   => array(
				'default'           => esc_html__( 'Reach us on:', 'automation-web-platform' ),
				'sanitize_callback' => 'sanitize_text_field',
			),
			'wawp_social_icons'        => array(
				'default'           => array(),
				'sanitize_callback' => array( $this, 'sanitize_social_icons' ),
			),
			'wawp_reply_time_text'     => array(
				'default'           => esc_html__( 'Typically replies within minutes', 'automation-web-platform' ),
				'sanitize_callback' => 'sanitize_text_field',
			),
			'wawp_welcome_message'     => array(
				'default'           => esc_html__( 'How may we help you?', 'automation-web-platform' ),
				'sanitize_callback' => 'sanitize_text_field',
			),
			'wawp_whatsapp_header'     => array(
				'default'           => esc_html__( "Let's chat", 'automation-web-platform' ),
				'sanitize_callback' => 'sanitize_text_field',
			),
			'wawp_button_size'         => array(
				'default'           => '60',
				'sanitize_callback' => 'intval',
			),
			'wawp_corner_radius'       => array(
				'default'           => '50',
				'sanitize_callback' => 'intval',
			),
			'wawp_button_position'     => array(
				'default'           => 'right',
				'sanitize_callback' => 'sanitize_text_field',
			),
			'wawp_display_desktop'     => array(
				'default'           => 'yes',
				'sanitize_callback' => 'sanitize_text_field',
			),
			'wawp_display_mobile'      => array(
				'default'           => 'yes',
				'sanitize_callback' => 'sanitize_text_field',
			),
			'wawp_enable_button'       => array(
				'default'           => 'yes',
				'sanitize_callback' => 'sanitize_text_field',
			),
			'wawp_disable_powered_by'  => array(
				'default'           => 'no',
				'sanitize_callback' => 'sanitize_text_field',
			),

			'wawp_icon_url'            => array(
				'default'           => plugin_dir_url( __FILE__ ) . 'WhatsApp_icon.png',
				'sanitize_callback' => 'esc_url_raw',
			),
			'wawp_avatar_url'          => array(
				'default'           => plugin_dir_url( __FILE__ ) . 'WhatsApp_avatar.png',
				'sanitize_callback' => 'esc_url_raw',
			),
			'wawp_whatsapp_icon_class' => array(
				'default'           => 'ri-chat-3-line',
				'sanitize_callback' => 'sanitize_text_field',
			),
			'wawp_button_bg_color'     => array(
				'default'           => 'linear-gradient(135deg, #2ee168, #00c66b)',
				'sanitize_callback' => 'sanitize_text_field',
			),
			'wawp_icon_color'          => array(
				'default'           => '#fff',
				'sanitize_callback' => 'sanitize_text_field',
			),
		);
		foreach ( $settings as $k => $a ) {
			register_setting(
				'wawp_options_group',
				$k,
				array(
					'type'              => 'string',
					'sanitize_callback' => $a['sanitize_callback'],
					'default'           => $a['default'],
				)
			);
		}
		register_setting(
			'wawp_options_group',
			'wawp_trigger_on_all_pages',
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
				'default'           => 'yes',
			)
		);
		register_setting(
			'wawp_options_group',
			'wawp_page_conditions',
			array(
				'type'              => 'array',
				'sanitize_callback' => array( $this, 'sanitize_page_conditions_exact' ),
				'default'           => array(),
			)
		);
	}

	/**
	 * Sanitize an array of strings.
	 *
	 * @param array $input Input array.
	 * @return array
	 */
	public function sanitize_array( $input ) {
		return is_array( $input ) ? array_map( 'sanitize_text_field', $input ) : array();
	}

	/**
	 * Sanitize social icons settings.
	 *
	 * @param array $input Input array.
	 * @return array
	 */
	public function sanitize_social_icons( $input ) {
		if ( ! is_array( $input ) ) {
			return array();
		}
		$clean = array();
		foreach ( $input as $item ) {
			$link = isset( $item['link'] ) ? esc_url_raw( $item['link'] ) : '';
			$icon = isset( $item['icon'] ) ? sanitize_text_field( $item['icon'] ) : 'ri-global-fill';
			if ( ! isset( $this->remix_icons_extended[ $icon ] ) ) {
				$icon = 'ri-global-fill';
			}
			if ( 'ri-mail-fill' === $icon && $link && 0 !== stripos( $link, 'mailto:' ) ) {
				$link = 'mailto:' . $link;
			}
			if ( 'ri-phone-fill' === $icon && $link && 0 !== stripos( $link, 'tel:' ) ) {
				$link = 'tel:' . $link;
			}
			if ( $link ) {
				$clean[] = array(
					'link' => $link,
					'icon' => $icon,
				);
			}
		}

		return $clean;
	}

	/**
	 * Sanitize page conditions (array of IDs).
	 *
	 * @param array $input Input array.
	 * @return array
	 */
	public function sanitize_page_conditions_exact( $input ) {
		return is_array( $input ) ? array_filter( array_map( 'absint', $input ) ) : array();
	}

	/**
	 * Render the WhatsApp button on the frontend.
	 *
	 * @param bool $is_preview Whether it's a preview mode.
	 */
	public function render_whatsapp_button( $is_preview = false ) {
		static $rendered = false;
		if ( $rendered ) {
			return;
		}
		$rendered = true;
		if ( $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_ENABLE, 'yes' ) !== 'yes' ) {
			return;
		}
		$numbers = $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_NUMBERS, array() );
		if ( empty( $numbers ) ) {
			return;
		}
		if ( ! $is_preview && ! ( ( $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_DISPLAY_DESKTOP, 'yes' ) === 'yes' && ! wp_is_mobile() ) || ( $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_DISPLAY_MOBILE, 'yes' ) === 'yes' && wp_is_mobile() ) ) ) {
			return;
		}
		if ( 'no' === $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_TRIGGER_ALL, 'yes' ) ) {
			global $post;
			if ( in_array( $post->ID ?? 0, $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_PAGE_CONDITIONS, array() ), true ) ) {
				return;
			}
		}

		$names         = $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_USER_NAMES, array() );
		$roles         = $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_USER_ROLES, array() );
		$avatars       = $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_USER_AVATARS, array() );
		$header        = esc_html( $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_HEADER, esc_html__( "Let's chat", 'automation-web-platform' ) ) );
		$welcome       = esc_html( $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_WELCOME_MSG, esc_html__( 'How may we help you?', 'automation-web-platform' ) ) );
		$reply_time    = esc_html( $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_REPLY_TIME, esc_html__( 'Typically replies within minutes', 'automation-web-platform' ) ) );
		$btn_size      = (int) $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_BTN_SIZE, 60 );
		$pos           = $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_POSITION, is_rtl() ? 'left' : 'right' );
		$btn_bg        = $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_BG_COLOR, 'linear-gradient(135deg, #2ee168, #00c66b)' );
		$icon_url      = $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_ICON_URL, plugin_dir_url( __FILE__ ) . 'WhatsApp_icon.png' );
		$def_avatar    = $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_AVATAR_URL, plugin_dir_url( __FILE__ ) . 'WhatsApp_avatar.png' );
		$icon_color    = $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_ICON_COLOR, '#fff' );
		$bottom_offset = (int) $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_BOTTOM_OFFSET, 32 );
		$pos_css       = ( ( 'left' === $pos ) ? 'left:16px;' : 'right:16px;' ) . " bottom:{$bottom_offset}px;" . ( $is_preview ? ' z-index: 100;' : '' );
		?>
		<div id="wawp-chat-wrapper" style='<?php echo esc_attr( $pos_css ); ?>'>
			<div id="wawp-whatsapp-button" class="wawp-whatsapp-button" style='width:<?php echo esc_attr( $btn_size ); ?>px; height:<?php echo esc_attr( $btn_size ); ?>px; border-radius:<?php echo esc_attr( $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_CORNER_RADIUS, 50 ) ); ?>%; background:<?php echo esc_attr( $btn_bg ); ?>; display:flex;'>
				<?php
				$icon_choice = $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_ICON_CLASS, 'ri-chat-3-line' );
				$icon_size   = floor( $btn_size * 0.6 );
				if ( isset( $this->preset_svgs[ $icon_choice ] ) ) {
					echo '<div class="wawp-custom-svg" style=\'width:' . esc_attr( $icon_size ) . 'px; height:auto; color:' . esc_attr( $icon_color ) . ';\'>'
						. wp_kses_post( $this->preset_svgs[ $icon_choice ] )
						. '</div>';
				} elseif ( ! empty( $icon_choice ) ) {
					echo '<i class="' . esc_attr( $icon_choice ) . '" style=\'font-size:' . esc_attr( $icon_size ) . 'px; color:' . esc_attr( $icon_color ) . ';\'></i>';
				} else {
					echo '<img src="' . esc_url( $icon_url ) . '" alt="WhatsApp" style=\'width:100%; height:auto; border-radius:inherit;\'>';
				}
				?>
			</div>
			<div id="wawp-chat-window" class="wawp-chat-window" style='background:linear-gradient(135deg, #044 50%, #00c66b); <?php echo esc_attr( ( 'left' === $pos ) ? 'transform-origin:bottom left; left:0;' : 'transform-origin:bottom right; right:0;' ); ?>'>
				<div class="wawp-chat-header">
					<img src="<?php echo esc_url( $def_avatar ); ?>" alt="Avatar" class="wawp-header-avatar" />
					<div>
						<div class="wawp-widget-title"><?php echo esc_html( $header ); ?></div>
						<div class="wawp-widget-message"><?php echo esc_html( $welcome ); ?></div>
					</div>
					<i class="ri-close-line wawp-minimize-icon" id="wawp-minimize-icon" style='<?php echo esc_attr( is_rtl() ? 'left:12px;' : 'right:12px;' ); ?>'></i>
				</div>
				<div class="wawp-chat-data">
					<div class="wawp-reply-time-container">
						<div class="wawp-reply-time-bubble"><i class="ri-time-line"></i><?php echo esc_html( $reply_time ); ?></div>
					</div>
					<div class="wawp-chat-content" id="wawp-contact-list">
						<?php foreach ( $numbers as $i => $num ) : ?>
							<div class="wawp-contact-item">
								<div class="wawp-avatar-wrapper">
									<img src="<?php echo esc_url( $avatars[ $i ] ?? $def_avatar ); ?>" alt="Avatar"><span class="wawp-online-dot"></span>
								</div>
								<div class="wawp-contact-info">
									<span class="wawp-contact-name"><?php echo esc_html( $names[ $i ] ?? 'John Doe' ); ?></span>
									<span class="wawp-contact-role"><?php echo esc_html( $roles[ $i ] ?? 'Support' ); ?></span>
								</div>
								<div class="btns-group">
									<?php
									$link = 'https://api.whatsapp.com/send?phone=' . esc_attr( $num ) . '&text=' . rawurlencode( ( $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_MESSAGES, array() )[ $i ] ?? 'Hello!' ) . ' | ' . esc_html__( 'I am on this page: ', 'automation-web-platform' ) . get_permalink() );
									?>
									<a href="<?php echo esc_url( $link ); ?>" target="_blank"><i class="ri-whatsapp-line wawp-wa-chat-icon"></i></a>
									<i class="ri-qr-code-line wawp-qr-chat-icon" data-wawp-link="<?php echo esc_url( $link ); ?>"></i>
								</div>
							</div>
							<hr style="width: 100%;margin: 0;border: 0;border-top: 1px solid #ededed;">
						<?php endforeach; ?>
					</div>
					<div class="wawp-qr-card" id="wawp-qr-card">
						<div class="wawp-qr-header">
							<i class="ri-arrow-<?php echo esc_attr( is_rtl() ? 'right' : 'left' ); ?>-line wawp-qr-back" id="wawp-qr-back"></i><?php esc_html_e( 'Scan QR Code', 'automation-web-platform' ); ?>
						</div>
						<div id="wawp-dynamic-qr"></div>
						<a id="wawp-open-whatsapp" href="#" target="_blank" class="wawp-open-whatsapp">
							<i class="ri-whatsapp-line"></i> <?php esc_html_e( 'Open WhatsApp', 'automation-web-platform' ); ?>
						</a>
					</div>
				</div>
				<div class="wawp-chat-footer">

					<?php
					$social_icons = $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_SOCIAL_ICONS, array() );
					if ( ! empty( $social_icons ) ) :
						?>
						<div class="wawp-social-section wawp-social-container wawp-layout-<?php echo esc_attr( $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_SOCIAL_LAYOUT, 'vertical' ) ); ?>">
							<div class="wawp-social-intro"><?php echo esc_html( $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_SOCIAL_INTRO, 'Reach us on:' ) ); ?></div>
							<div class="wawp-social-icons wawp-style-<?php echo esc_attr( $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_SOCIAL_STYLE, 'round' ) ); ?>">
								<?php foreach ( $social_icons as $s ) : ?>
									<a href="<?php echo esc_url( $s['link'] ); ?>" target="_blank" class="wawp-social-icon" data-icon="<?php echo esc_attr( $s['icon'] ); ?>">
										<i class="<?php echo esc_attr( $s['icon'] ); ?>"></i>
									</a>
								<?php endforeach; ?>
							</div>
						</div>
					<?php endif; ?>
				</div>
				<?php if ( $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_DISABLE_POWERED_BY, 'no' ) !== 'yes' ) : ?>
			<div class="wawp-powered_by">
				<a href="https://wawp.net" target="_blank" rel="noopener">
					<span class="wawp-powered_by-label"><?php esc_html_e( 'Powered by', 'automation-web-platform' ); ?></span>
					<svg class="wawp-powered_by-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
						<path d="M7 0C7.55228 0 8 0.447715 8 1V3H16V1C16 0.447715 16.4477 0 17 0H19C19.5523 0 20 0.447715 20 1V3C22.2091 3 24 4.79086 24 7V17C24 19.2091 22.2091 21 20 21H17C17 21 14 24 12 24C10 24 7 21 7 21H4C1.79086 21 1.61067e-08 19.2091 0 17V7C0 4.79086 1.79086 3 4 3V1C4 0.447715 4.44772 0 5 0H7ZM4 5C2.89543 5 2 5.89543 2 7V17C2 18.1046 2.89543 19 4 19H20C21.1046 19 22 18.1046 22 17V7C22 5.89543 21.1046 5 20 5H4ZM9 9C9.55228 9 10 9.44772 10 10V14C10 14.5523 9.55228 15 9 15H7C6.44772 15 6 14.5523 6 14V10C6 9.44772 6.44772 9 7 9H9ZM17 9C17.5523 9 18 9.44772 18 10V14C18 14.5523 17.5523 15 17 15H15C14.4477 15 14 14.5523 14 14V10C14 9.44772 14.4477 9 15 9H17Z" fill="currentColor"/>
					</svg>
					<span class="wawp-powered_by-name">Wawp</span>
				</a>
			</div>
			<?php endif; ?>
			</div>
		</div>
		<?php
	}
}

new WAWP_Chat_Widget();
