<?php
/**
 * Abandoned Cart Backend Trait.
 *
 * @package automation-web-platform
 */

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


/**
 * Trait WAWP_Abandoned_Cart_Backend.
 * Handles all backend/admin-facing logic for Abandoned Carts.
 */
trait WAWP_Abandoned_Cart_Backend {

	/**
	 * Get cart sessions for admin dashboard.
	 *
	 * @param array $params Request parameters.
	 * @return array Session data.
	 */
	public function get_sessions_return( $params = array() ) {
		global $wpdb;
		$table = esc_sql( $wpdb->prefix . 'wawp_abandoned_carts' );

		// Note: merge_duplicate_sessions_by_rule() was removed from here - it's an O(n²)
		// operation that causes timeouts on large datasets. Run it via Smart Clear instead.

		$status_param     = isset( $params['status'] ) ? sanitize_text_field( $params['status'] ) : 'all';
		$statuses         = array_map( 'sanitize_key', explode( ',', $status_param ) );
		$is_duplicate_ips = in_array( 'duplicate_ips', $statuses, true );

		$search          = isset( $params['search'] ) ? sanitize_text_field( $params['search'] ) : '';
		$paged           = isset( $params['paged'] ) ? absint( $params['paged'] ) : 1;
		$per_page        = 50;
		$offset          = ( $paged - 1 ) * $per_page;
		$hide_incomplete = $this->get_wawp_setting( WAWP_Settings_Registry::AC_HIDE_INCOMPLETE_ROWS, '0' );

		$where_conditions = array();
		$where_params     = array();

		if ( ! in_array( 'all', $statuses, true ) && ! in_array( 'duplicate_ips', $statuses, true ) ) {
			$db_statuses        = array_map(
				function ( $s ) {
					return str_replace( '_', ' ', $s );
				},
				$statuses
			);
			$placeholders       = implode( ',', array_fill( 0, count( $db_statuses ), '%s' ) );
			$where_conditions[] = 'status IN (' . $placeholders . ')';
			foreach ( $db_statuses as $ds ) {
				$where_params[] = $ds;
			}
		}

		if ( '1' === $hide_incomplete ) {
			$where_conditions[] = "NOT ((browser IS NULL OR browser = '') AND (os IS NULL OR os = '') AND (device IS NULL OR device = '') AND (page_history IS NULL OR page_history = '' OR page_history = '[]'))";
		}

		// Optimize admin ID lookup to avoid heavy get_users call.
		$admin_ids_cache_key = 'wawp_admin_ids';
		$admin_ids           = wp_cache_get( $admin_ids_cache_key, 'wawp_database' );
		if ( false === $admin_ids ) {
			$admin_ids = get_transient( $admin_ids_cache_key );
			if ( false === $admin_ids ) {
				$admin_ids = get_users(
					array(
						'role'   => 'administrator',
						'fields' => 'ID',
					)
				);
				set_transient( $admin_ids_cache_key, $admin_ids, DAY_IN_SECONDS );
			}
			wp_cache_set( $admin_ids_cache_key, $admin_ids, 'wawp_database', DAY_IN_SECONDS );
		}
		$admin_ids = array_map( 'intval', (array) $admin_ids );

		if ( ! empty( $admin_ids ) ) {
			$admin_placeholders = implode( ',', array_fill( 0, count( $admin_ids ), '%d' ) );
			$where_conditions[] = '(user_id IS NULL OR user_id NOT IN (' . $admin_placeholders . '))';
			foreach ( $admin_ids as $aid ) {
				$where_params[] = (int) $aid;
			}
		}

		if ( ! empty( $search ) ) {
			$search_like        = '%' . $wpdb->esc_like( $search ) . '%';
			$where_conditions[] = '(contact_details LIKE %s OR location LIKE %s OR status LIKE %s)';
			$where_params[]     = $search_like;
			$where_params[]     = $search_like;
			$where_params[]     = $search_like;
		}

		$where_clause = '';
		if ( ! empty( $where_conditions ) ) {
			$where_clause = ' WHERE ' . implode( ' AND ', $where_conditions );
		}

		// Stats Logic with Double-Layer Caching.
		$cache_key = 'wawp_ac_dashboard_stats';
		$stats     = wp_cache_get( $cache_key, 'wawp_ac' );
		if ( false === $stats ) {
			$stats = get_transient( $cache_key );
			if ( false === $stats ) {
				$stats_row = WAWP()->db->get_results_cached(
					$wpdb->prepare(
						"SELECT 
							COUNT(id) as total_visits, 
							SUM(CASE WHEN cart_contents IS NOT NULL AND cart_contents != '' AND cart_contents != 'a:0:{}' THEN cart_total ELSE 0 END) as potential_revenue, 
							COUNT(CASE WHEN cart_contents IS NOT NULL AND cart_contents != '' AND cart_contents != 'a:0:{}' THEN 1 END) as active_carts, 
							COUNT(CASE WHEN contact_details IS NOT NULL AND contact_details != '' AND contact_details != 'a:0:{}' THEN 1 END) as checkout_started, 
							COUNT(CASE WHEN status = 'purchased' OR (order_id IS NOT NULL AND order_id != '') THEN 1 END) as orders_recovered 
						FROM %i WHERE NOT ((browser IS NULL OR browser = '') AND (os IS NULL OR os = '') AND (device IS NULL OR device = '') AND (page_history IS NULL OR page_history = '' OR page_history = '[]'))",
						$table
					),
					'wawp_ac_stats_row',
					'wawp_ac',
					0 // No cache for now to ensure update.
				);
				$stats_row = ! empty( $stats_row ) ? (object) $stats_row[0] : null;

				if ( $stats_row ) {
					$total_visits      = (int) $stats_row->total_visits;
					$potential_revenue = (float) $stats_row->potential_revenue;
					$active_carts      = (int) $stats_row->active_carts;
					$checkout_started  = (int) $stats_row->checkout_started;
					$orders_recovered  = (int) $stats_row->orders_recovered;

					// Calculate actual recovered revenue from order totals.
					$actual_recovered_revenue = 0;
					$purchased_sessions       = WAWP()->db->get_results_cached(
						$wpdb->prepare(
							"SELECT order_id FROM %i WHERE (status = 'purchased' OR (order_id IS NOT NULL AND order_id != '')) AND NOT ((browser IS NULL OR browser = '') AND (os IS NULL OR os = '') AND (device IS NULL OR device = '') AND (page_history IS NULL OR page_history = '' OR page_history = '[]'))",
							$table
						),
						'wawp_ac_purchased_orders_list',
						'wawp_ac',
						0
					);

					if ( ! empty( $purchased_sessions ) ) {
						$all_purchased_oids = array();
						foreach ( $purchased_sessions as $ps ) {
							if ( ! empty( $ps['order_id'] ) ) {
								$all_purchased_oids = array_merge( $all_purchased_oids, explode( ',', $ps['order_id'] ) );
							}
						}
						$all_purchased_oids = array_unique( array_filter( array_map( 'intval', $all_purchased_oids ) ) );
						if ( ! empty( $all_purchased_oids ) ) {
							$order_totals_map         = $this->get_order_totals_map( $all_purchased_oids );
							$actual_recovered_revenue = array_sum( $order_totals_map );
						}
					}

					$recovered_revenue = $actual_recovered_revenue;

					$leads_data = WAWP()->db->get_results_cached(
						$wpdb->prepare(
							'SELECT contact_details FROM %i WHERE NOT ((browser IS NULL OR browser = "") AND (os IS NULL OR os = "") AND (device IS NULL OR device = "") AND (page_history IS NULL OR page_history = "" OR page_history = "[]")) AND contact_details LIKE %s',
							$table,
							'%billing_phone%'
						),
						'wawp_ac_leads_data',
						'wawp_ac',
						HOUR_IN_SECONDS
					);

					$unique_phones = array();
					if ( ! empty( $leads_data ) ) {
						foreach ( $leads_data as $cd_raw ) {
							$cd = maybe_unserialize( $cd_raw );
							if ( is_array( $cd ) && ! empty( $cd['billing_phone'] ) ) {
								$clean_phone = $this->get_digits_only( $cd['billing_phone'] );
								if ( $clean_phone ) {
									$unique_phones[ $clean_phone ] = true;
								}
							}
						}
					}
					$leads_captured = count( $unique_phones );

					$stats = array(
						'potential_revenue_raw' => $potential_revenue,
						'potential_revenue'     => wp_strip_all_tags( html_entity_decode( function_exists( 'wc_price' ) ? wc_price( $potential_revenue ) : $potential_revenue ) ),
						'active_carts'          => $active_carts,
						'pct_carts'             => $total_visits > 0 ? round( ( $active_carts / $total_visits ) * 100 ) : 0,
						'checkout_started'      => $checkout_started,
						'pct_checkout'          => $active_carts > 0 ? round( ( $checkout_started / $active_carts ) * 100 ) : 0,
						'leads_captured'        => $leads_captured,
						'pct_leads'             => $total_visits > 0 ? round( ( $leads_captured / $total_visits ) * 100 ) : 0,
						'orders_recovered'      => $orders_recovered,
						'pct_orders'            => $total_visits > 0 ? round( ( $orders_recovered / $total_visits ) * 100 ) : 0,
						'recovered_revenue_raw' => $recovered_revenue,
						'recovered_revenue'     => wp_strip_all_tags( html_entity_decode( function_exists( 'wc_price' ) ? wc_price( $recovered_revenue ) : $recovered_revenue ) ),
					);
					set_transient( $cache_key, $stats, HOUR_IN_SECONDS );
				}
				wp_cache_set( $cache_key, $stats, 'wawp_ac', HOUR_IN_SECONDS );
			}
		}

		$rows = array();
		if ( $is_duplicate_ips ) {
			$dup_rows = WAWP()->db->get_results_cached(
				$wpdb->prepare(
					"SELECT SUBSTRING_INDEX(location, '|', 1) AS ip_address, COUNT(*) AS session_count, MIN(created_at) AS first_seen, MAX(created_at) AS last_seen, GROUP_CONCAT(id ORDER BY id ASC SEPARATOR ',') AS all_ids, BIT_OR(CASE WHEN NOT ((browser IS NULL OR browser = '') AND (os IS NULL OR os = '') AND (device IS NULL OR device = '') AND (page_history IS NULL OR page_history = '' OR page_history = '[]')) THEN 1 ELSE 0 END) AS has_complete_record FROM %i WHERE location IS NOT NULL AND location != '' GROUP BY SUBSTRING_INDEX(location, '|', 1) HAVING COUNT(*) > 1 ORDER BY last_seen DESC LIMIT %d OFFSET %d",
					$table,
					$per_page,
					$offset
				),
				"wawp_ac_dup_rows_{$paged}",
				'wawp_ac',
				600
			);

			foreach ( $dup_rows as $dr ) {
				$rows[] = array(
					'is_duplicate_row' => true,
					'ip_address'       => $dr['ip_address'],
					'session_count'    => $dr['session_count'],
					'first_seen'       => $dr['first_seen'],
					'last_seen'        => $dr['last_seen'],
					'all_ids'          => $dr['all_ids'],
					'has_complete'     => (bool) $dr['has_complete_record'],
				);
			}

			$total_items = (int) WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT COUNT(*) FROM (SELECT 1 FROM %i WHERE location IS NOT NULL AND location != "" GROUP BY SUBSTRING_INDEX(location, "|", 1) HAVING COUNT(*) > 1) AS dups', $table ), 'wawp_ac_dup_total', 'wawp_ac', 3600 )[0]['COUNT(*)'] ?? 0;
		} else {
			$status_val = '';
			$search_val = ! empty( $params['search'] ) ? '%' . $wpdb->esc_like( $params['search'] ) . '%' : '';
			$df_val     = ! empty( $params['date_from'] ) ? $params['date_from'] . ' 00:00:00' : '';
			$dt_val     = ! empty( $params['date_to'] ) ? $params['date_to'] . ' 23:59:59' : '';

			if ( '1' === $hide_incomplete ) {
				$db_rows = WAWP()->db->get_results_cached(
					$wpdb->prepare(
						"SELECT * FROM %i WHERE (1=1) AND NOT ( (contact_details IS NULL OR contact_details = '' OR contact_details = 'a:0:{}') AND (cart_total = 0.00 OR cart_total IS NULL) AND (browser IS NULL OR browser = '' OR os IS NULL OR os = '' OR device IS NULL OR device = '' OR page_history IS NULL OR page_history = '' OR page_history = '[]') ) AND (%s = '' OR status = %s) AND (%s = '' OR (location LIKE %s OR contact_details LIKE %s OR browser LIKE %s OR os LIKE %s OR device LIKE %s)) AND (%s = '' OR created_at >= %s) AND (%s = '' OR created_at <= %s) ORDER BY id DESC LIMIT 2000",
						$table,
						$status_val,
						$status_val,
						$search_val,
						$search_val,
						$search_val,
						$search_val,
						$search_val,
						$search_val,
						$df_val,
						$df_val,
						$dt_val,
						$dt_val
					),
					'wawp_ac_db_rows_list',
					'wawp_ac',
					300
				);
			} else {
				$db_rows = WAWP()->db->get_results_cached(
					$wpdb->prepare(
						"SELECT * FROM %i WHERE (1=1) AND (%s = '' OR status = %s) AND (%s = '' OR (location LIKE %s OR contact_details LIKE %s OR browser LIKE %s OR os LIKE %s OR device LIKE %s)) AND (%s = '' OR created_at >= %s) AND (%s = '' OR created_at <= %s) ORDER BY id DESC LIMIT 2000",
						$table,
						$status_val,
						$status_val,
						$search_val,
						$search_val,
						$search_val,
						$search_val,
						$search_val,
						$search_val,
						$df_val,
						$df_val,
						$dt_val,
						$dt_val
					),
					'wawp_ac_db_rows_list',
					'wawp_ac',
					300
				);
			}
			$db_rows = array_map(
				function ( $r ) {
					return (object) $r;
				},
				$db_rows
			);

			$groups = array();
			foreach ( $db_rows as $r ) {
				$ip  = explode( '|', $r->location ?? '' )[0];
				$key = $ip;
				if ( empty( $ip ) || 'unknown' === $ip ) {
					$key = 'rnd_' . $r->id;
				}
				$groups[ $key ][] = $r;
			}

			// Pre-fetch all order totals to avoid N+1 queries in the loop.
			$all_oids_to_fetch = array();
			foreach ( $db_rows as $row ) {
				if ( ! empty( $row->order_id ) ) {
					$all_oids_to_fetch = array_merge( $all_oids_to_fetch, explode( ',', $row->order_id ) );
				}
			}
			$all_oids_to_fetch = array_unique( array_filter( array_map( 'intval', $all_oids_to_fetch ) ) );
			$order_totals_map  = array();
			if ( ! empty( $all_oids_to_fetch ) ) {
				// Use official WooCommerce function to get orders securely and bypass strict SQL linting.
				$orders = function_exists( 'wc_get_orders' ) ? wc_get_orders( array( 'include' => $all_oids_to_fetch ) ) : array();
				foreach ( $orders as $order ) {
					$order_totals_map[ (int) $order->get_id() ] = (float) $order->get_total();
				}
			}

			$merged_data = array();
			foreach ( $groups as $key => $group_rows ) {
				// Sort group by ID ascending to process chronologically.
				usort(
					$group_rows,
					function ( $a, $b ) {
						return $a->id <=> $b->id;
					}
				);

				$master         = end( $group_rows ); // Default to newest.
				$merged_history = array();
				$merged_contact = array();
				$merged_cart    = array();
				$max_total      = 0;
				$best_status    = 'new';
				$order_id       = null;
				$first_created  = $group_rows[0]->created_at;
				$last_updated   = $master->updated_at;

				$status_priority = array(
					'purchased'          => 7,
					'potential customer' => 6,
					'admin'              => 5,
					'shopping'           => 4,
					'online'             => 3,
					'new visitor'        => 2,
					'new'                => 1,
				);

				$all_order_ids = array();
				foreach ( $group_rows as $row ) {
					// Merge History.
					if ( ! empty( $row->page_history ) ) {
						$h = json_decode( $row->page_history, true );
						if ( ! is_array( $h ) ) {
							$h = json_decode( stripslashes( $row->page_history ), true );
						}
						if ( is_array( $h ) ) {
							$merged_history = array_merge( $merged_history, $h );
						}
					}
					// Merge Contact (only overwrite if the new value is not empty).
					$cd = maybe_unserialize( $row->contact_details );
					if ( is_array( $cd ) ) {
						foreach ( $cd as $key => $val ) {
							if ( ! empty( $val ) ) {
								$merged_contact[ $key ] = $val;
							}
						}
					}
					// Merge Cart.
					$cc = maybe_unserialize( $row->cart_contents );
					if ( is_array( $cc ) ) {
						$merged_cart = array_merge( $merged_cart, $cc );
					}
					// Totals & Status.
					if ( (float) $row->cart_total > $max_total ) {
						$max_total = (float) $row->cart_total;
					}
					$s = strtolower( $row->status );
					if ( ! empty( $row->user_id ) && in_array( (int) $row->user_id, $admin_ids, true ) ) {
						$s = 'admin';
					} elseif ( 'new' === $s ) {
						$ip = explode( '|', $row->location ?? '' )[0];
						if ( ! empty( $row->browser ) && ! empty( $row->os ) && ! empty( $row->device ) && ! empty( $ip ) && ! empty( $row->page_history ) && '[]' !== $row->page_history ) {
							$s = 'new visitor';
						}
					}

					if ( ( $status_priority[ $s ] ?? 0 ) > ( $status_priority[ $best_status ] ?? 0 ) ) {
						$best_status = $s;
					}
					if ( ! empty( $row->order_id ) ) {
						$row_order_ids = explode( ',', $row->order_id );
						$all_order_ids = array_merge( $all_order_ids, $row_order_ids );
					}
				}
				$order_id = implode( ',', array_unique( array_filter( $all_order_ids ) ) );

				// Deduplicate history by timestamp.
				$unique_history = array();
				foreach ( $merged_history as $ev ) {
					$h_key                    = ( $ev['timestamp'] ?? 0 ) . '|' . ( $ev['type'] ?? '' );
					$unique_history[ $h_key ] = $ev;
				}
				$merged_history = array_values( $unique_history );
				usort(
					$merged_history,
					function ( $a, $b ) {
						return (int) ( $a['timestamp'] ?? 0 ) <=> (int) ( $b['timestamp'] ?? 0 );
					}
				);

				// Calculate Journey Info.
				$source          = 'Direct';
				$first_timestamp = 0;
				$last_timestamp  = 0;
				if ( ! empty( $merged_history ) ) {
					$first_ev        = $merged_history[0];
					$first_timestamp = (int) ( $first_ev['timestamp'] ?? 0 );
					$last_ev         = end( $merged_history );
					$last_timestamp  = (int) ( $last_ev['timestamp'] ?? 0 );
					if ( ! empty( $first_ev['data']['referrer'] ) ) {
						$ref_host = wp_parse_url( $first_ev['data']['referrer'], PHP_URL_HOST );
						if ( $ref_host ) {
							$source = preg_replace( '/^www\./', '', strtolower( $ref_host ) );
						}
					}
				}
				if ( 0 === $first_timestamp ) {
					$first_timestamp = strtotime( $first_created );
					$last_timestamp  = strtotime( $last_updated );
				}

				$duration   = $last_timestamp - $first_timestamp;
				$total_time = '0s';
				if ( $duration > 0 ) {
					$d     = floor( $duration / 86400 );
					$h     = floor( ( $duration % 86400 ) / 3600 );
					$m     = floor( ( $duration % 3600 ) / 60 );
					$s     = $duration % 60;
					$parts = array();
					if ( $d > 0 ) {
						$parts[] = "{$d}d";
					}
					if ( $h > 0 ) {
						$parts[] = "{$h}h";
					}
					if ( $m > 0 ) {
						$parts[] = "{$m}m";
					}
					if ( $s > 0 ) {
						$parts[] = "{$s}s";
					}
					$total_time = implode( ' ', $parts );
				}

				// Current Page.
				$current_page = 'Unknown';
				foreach ( array_reverse( $merged_history ) as $ev ) {
					if ( ( $ev['type'] ?? '' ) === 'page' && ! empty( $ev['data']['url'] ) ) {
						$current_page = $ev['data']['title'] ?? wp_parse_url( $ev['data']['url'], PHP_URL_PATH );
						break;
					}
				}

				// Cart Items Data.
				$cart_items_data = array();
				if ( is_array( $merged_cart ) ) {
					foreach ( $merged_cart as $item ) {
						$pid     = $item['product_id'] ?? 0;
						$vid     = $item['variation_id'] ?? 0;
						$product = function_exists( 'wc_get_product' ) ? wc_get_product( $vid ? $vid : $pid ) : null;
						if ( $product ) {
							$image_id          = $product->get_image_id();
							$cart_items_data[] = array(
								'name'      => $item['name'] ?? $product->get_name(),
								'qty'       => $item['quantity'] ?? 1,
								'price'     => wp_strip_all_tags( html_entity_decode( function_exists( 'wc_price' ) ? wc_price( $item['price'] ?? $product->get_price() ) : ( $item['price'] ?? $product->get_price() ) ) ),
								'image_src' => $image_id ? wp_get_attachment_image_url( $image_id, 'thumbnail' ) : ( function_exists( 'wc_placeholder_img_src' ) ? wc_placeholder_img_src() : '' ),
							);
						}
					}
				}
				$has_contact = ! empty( $merged_contact['billing_email'] ) || ! empty( $merged_contact['billing_phone'] );
				$has_cart    = (float) $max_total > 0.00;

				$final_status = 'new';
				if ( ! empty( $master->user_id ) && in_array( (int) $master->user_id, $admin_ids, true ) ) {
					$final_status = 'admin';
				} elseif ( 'purchased' === $best_status || ! empty( $order_id ) ) {
					$final_status = 'purchased';
				} elseif ( $has_cart && $has_contact ) {
					$final_status = ( ( time() - $last_timestamp ) < 300 ) ? 'shopping' : 'abandoned cart';
				} elseif ( $has_cart && ! $has_contact ) {
					$final_status = 'guest cart';
				} elseif ( ! $has_cart && $has_contact ) {
					$final_status = 'potential customer';
				} else {
					$is_returning = count( $group_rows ) > 1;
					$ip           = explode( '|', $master->location ?? '' )[0];
					if ( ! empty( $master->browser ) && ! empty( $master->os ) && ! empty( $master->device ) && ! empty( $ip ) && ! empty( $merged_history ) ) {
						$final_status = $is_returning ? 'returning customer' : 'new visitor';
					} else {
						$final_status = $is_returning ? 'returning customer' : $best_status;
					}
				}

				// Calculate aggregate stats for multiple purchases.
				$purchased_count     = 0;
				$purchased_total_raw = 0;
				if ( ! empty( $order_id ) ) {
					$ids             = array_filter( array_map( 'trim', explode( ',', $order_id ) ) );
					$purchased_count = count( $ids );
					foreach ( $ids as $oid ) {
						$oid_int = (int) $oid;
						if ( isset( $order_totals_map[ $oid_int ] ) ) {
							$purchased_total_raw += $order_totals_map[ $oid_int ];
						}
					}
				}
				$purchased_total_formatted = wp_strip_all_tags( html_entity_decode( function_exists( 'wc_price' ) ? wc_price( $purchased_total_raw ) : $purchased_total_raw ) );

				// Perform on-the-fly Carrier Lookup if phone is set but carrier is empty.
				$phone_val   = $merged_contact['billing_phone'] ?? '';
				$carrier_val = $merged_contact['billing_carrier'] ?? '';
				if ( ! empty( $phone_val ) && empty( $carrier_val ) ) {
					$carrier_val = self::lookup_phone_carrier( $phone_val );
					if ( $carrier_val ) {
						$merged_contact['billing_carrier'] = $carrier_val;

						$master_arr = (array) $master;
						$master_id  = $master_arr['id'] ?? 0;
						$master_cd  = isset( $master_arr['contact_details'] ) ? maybe_unserialize( $master_arr['contact_details'] ) : array();
						if ( ! is_array( $master_cd ) ) {
							$master_cd = array();
						}
						$master_cd['billing_carrier'] = $carrier_val;

						WAWP()->db->update_row(
							'abandoned_carts',
							array( 'contact_details' => maybe_serialize( $master_cd ) ),
							array( 'id' => $master_id )
						);

						wp_cache_delete( 'wac_session_full_' . md5( (string) ( $master_arr['session_id'] ?? '' ) ), 'wawp_abandoned_carts' );
						wp_cache_delete( 'wac_session_' . md5( (string) ( $master_arr['session_id'] ?? '' ) ), 'wawp_abandoned_carts' );
						wp_cache_delete( 'wac_session_contact_' . md5( (string) ( $master_arr['session_id'] ?? '' ) ), 'wawp_abandoned_carts' );
						wp_cache_flush_group( 'wawp_ac' );
					}
				}

				// Format Row.
				$merged_data[] = array(
					'id'               => $master->id,
					'user_id'          => $master->user_id,
					'role'             => $master->user_id > 0 ? 'user' : 'guest',
					'display_name'     => ( trim( ( $merged_contact['billing_first_name'] ?? '' ) . ' ' . ( $merged_contact['billing_last_name'] ?? '' ) ) ) ? trim( ( $merged_contact['billing_first_name'] ?? '' ) . ' ' . ( $merged_contact['billing_last_name'] ?? '' ) ) : 'Unknown',
					'ip'               => $ip,
					'country_code'     => strtolower( ( ! empty( explode( '|', $master->location ?? '' )[1] ) ) ? explode( '|', $master->location ?? '' )[1] : ( $merged_contact['billing_country'] ?? '' ) ),
					'country_name'     => '',
					'device'           => $master->device,
					'os'               => $master->os,
					'browser'          => $master->browser,
					'email'            => $merged_contact['billing_email'] ?? '',
					'phone'            => $merged_contact['billing_phone'] ?? '',
					'carrier'          => $merged_contact['billing_carrier'] ?? '',
					'address'          => array(
						'address_1' => $merged_contact['billing_address_1'] ?? '',
						'city'      => $merged_contact['billing_city'] ?? '',
						'state'     => $merged_contact['billing_state'] ?? '',
						'postcode'  => $merged_contact['billing_postcode'] ?? '',
					),
					'cart_items_count' => count( $cart_items_data ),
					'cart_summary'     => count( $cart_items_data ) . ' items',
					'cart_total_raw'   => $max_total,
					'cart_total'       => wp_strip_all_tags( html_entity_decode( function_exists( 'wc_price' ) ? wc_price( $max_total ) : $max_total ) ),
					'status'           => $final_status,
					'order_id'         => $order_id,
					'orders_count'     => $purchased_count,
					'total_amount'     => (float) $purchased_total_raw,
					'purchased_total'  => $purchased_total_formatted,
					'source'           => $source,
					'current_page'     => $current_page,
					'created_at'       => $first_created,
					'updated_at'       => $last_updated,
					'total_time'       => $total_time,
					'is_online'        => ( ( time() - $last_timestamp ) < 300 ),
					'page_history'     => $merged_history,
					'cart_contents'    => $cart_items_data,
				);
			}

			// Sort merged data by updated_at DESC.
			usort(
				$merged_data,
				function ( $a, $b ) {
					return strtotime( $b['updated_at'] ) <=> strtotime( $a['updated_at'] );
				}
			);
			if ( ! in_array( 'all', $statuses, true ) && ! empty( $statuses ) ) {
				$target_statuses = array_map(
					function ( $s ) {
						return strtolower( str_replace( '_', ' ', $s ) );
					},
					$statuses
				);
				$merged_data     = array_values(
					array_filter(
						$merged_data,
						function ( $item ) use ( $target_statuses ) {
							return in_array( strtolower( $item['status'] ), $target_statuses, true );
						}
					)
				);
			}

			$has_contact = isset( $params['has_contact'] ) && ( '1' === $params['has_contact'] || 'true' === $params['has_contact'] || true === $params['has_contact'] );
			if ( $has_contact ) {
				$merged_data = array_values(
					array_filter(
						$merged_data,
						function ( $item ) {
							return ! empty( $item['phone'] ) || ! empty( $item['email'] );
						}
					)
				);
			}

			$total_items = count( $merged_data );
			$rows        = array_slice( $merged_data, $offset, $per_page );
		}

		return array(
			'stats'           => $stats,
			'rows'            => $rows,
			'total_items'     => $total_items,
			'per_page'        => $per_page,
			'hide_incomplete' => ( '1' === $hide_incomplete ),
			'i18n'            => array(
				'sessionsUserJourney'        => __( 'Sessions & User Journey', 'automation-web-platform' ),
				'trackUserJourney'           => __( 'Track user journey, abandoned carts, and more.', 'automation-web-platform' ),
				'cartSettings'               => __( 'Cart Settings', 'automation-web-platform' ),
				'sessionsSnapshot'           => __( 'Sessions & User Journey — Snapshot', 'automation-web-platform' ),
				'funnelView'                 => __( 'Funnel view of visitor sessions and recovery performance.', 'automation-web-platform' ),
				'potentialRevenue'           => __( 'Potential Revenue', 'automation-web-platform' ),
				'totalValueCarts'            => __( 'Total value of carts.', 'automation-web-platform' ),
				'total'                      => __( 'Total', 'automation-web-platform' ),
				'profit'                     => __( 'Profit', 'automation-web-platform' ),
				'totalOrderLtv'              => __( 'Total order lifetime value.', 'automation-web-platform' ),
				'roi'                        => __( 'ROI', 'automation-web-platform' ),
				'activeCarts'                => __( 'Active Carts', 'automation-web-platform' ),
				'visitorsWithItems'          => __( 'Visitors with items.', 'automation-web-platform' ),
				'recovered'                  => __( 'Recovered', 'automation-web-platform' ),
				'totalCountPurchased'        => __( 'Total count of PURCHASED.', 'automation-web-platform' ),
				'all'                        => __( 'All', 'automation-web-platform' ),
				'hasPhoneOrEmail'            => __( 'Has Phone or Email', 'automation-web-platform' ),
				'showOnlyContactCaptured'    => __( 'Show only sessions that have at least a phone number or email address captured', 'automation-web-platform' ),
				'liveSearch'                 => __( 'Live search within records...', 'automation-web-platform' ),
				/* translators: %d: number of sessions found */
				'sessionsFound'              => __( '%d sessions found', 'automation-web-platform' ),
				'abandonedCartSessionsTitle' => __( 'Abandoned Cart Sessions', 'automation-web-platform' ),
				'detailedLog'                => __( 'Detailed log of all visitor interactions and checkout progress.', 'automation-web-platform' ),
				'showIncomplete'             => __( 'Show Incomplete', 'automation-web-platform' ),
				'hideIncomplete'             => __( 'Hide Incomplete', 'automation-web-platform' ),
				'smartClear'                 => __( 'Smart Clear', 'automation-web-platform' ),
				/* translators: %d: number of selected records */
				'clearSelected'              => __( 'Clear Selected (%d)', 'automation-web-platform' ),
				'clearAll'                   => __( 'Clear All', 'automation-web-platform' ),
				'visitorUser'                => __( 'Visitor/User', 'automation-web-platform' ),
				'contactInfo'                => __( 'Contact Info', 'automation-web-platform' ),
				'cartSummary'                => __( 'Cart Summary', 'automation-web-platform' ),
				'status'                     => __( 'Status', 'automation-web-platform' ),
				'journey'                    => __( 'Journey', 'automation-web-platform' ),
				'noRecordsFound'             => __( 'No records found.', 'automation-web-platform' ),
				'duplicateSessionMerged'     => __( 'Duplicate session from same IP/User within short interval. Merged into main record above.', 'automation-web-platform' ),
				'guest'                      => __( 'Guest', 'automation-web-platform' ),
				'viewItems'                  => __( 'View Items', 'automation-web-platform' ),
				'online'                     => __( 'Online', 'automation-web-platform' ),
				'leftSite'                   => __( 'Left Site', 'automation-web-platform' ),
				'viewHistory'                => __( 'View History', 'automation-web-platform' ),
				'viewDetails'                => __( 'VIEW DETAILS', 'automation-web-platform' ),
				'showLess'                   => __( 'Show Less', 'automation-web-platform' ),
				'items'                      => __( 'items', 'automation-web-platform' ),
				'prev'                       => __( 'Prev', 'automation-web-platform' ),
				/* translators: 1: current page number, 2: total page count */
				'pageOf'                     => __( 'Page %1$d of %2$d', 'automation-web-platform' ),
				'next'                       => __( 'Next', 'automation-web-platform' ),
				'sessionJourney'             => __( 'Session Journey', 'automation-web-platform' ),
				'chronologicalRecord'        => __( 'A chronological record of visitor activities, page views, and shopping behavior.', 'automation-web-platform' ),
				'cartContents'               => __( 'Cart Contents', 'automation-web-platform' ),
				'detailedListProducts'       => __( 'Detailed list of products left in the customer\'s cart during this session.', 'automation-web-platform' ),
				'noItemsFoundInCart'         => __( 'No items found in this cart.', 'automation-web-platform' ),
				'qty'                        => __( 'Qty:', 'automation-web-platform' ),
				'noHistoryRecords'           => __( 'No history records found for this session.', 'automation-web-platform' ),
				'statusTransitioned'         => __( 'Status Transitioned:', 'automation-web-platform' ),
				'viewedPage'                 => __( 'Viewed Page:', 'automation-web-platform' ),
				'untitledPage'               => __( 'Untitled Page', 'automation-web-platform' ),
				'addedToCart'                => __( 'Added to Cart:', 'automation-web-platform' ),
				'removedFromCart'            => __( 'Removed from Cart:', 'automation-web-platform' ),
				'beganCheckout'              => __( 'Began Checkout', 'automation-web-platform' ),
				'loggedIn'                   => __( 'Logged In:', 'automation-web-platform' ),
				'orderCreated'               => __( 'Order Created:', 'automation-web-platform' ),
				'contactSubmitted'           => __( 'Contact Submitted:', 'automation-web-platform' ),
				'signedUp'                   => __( 'Signed Up:', 'automation-web-platform' ),
				'fillingCheckoutFields'      => __( 'Filling Checkout Fields', 'automation-web-platform' ),
				'orderCompleted'             => __( 'Order Completed:', 'automation-web-platform' ),
				'cartRestored'               => __( 'Cart Restored', 'automation-web-platform' ),
				'fromRecoveryLink'           => __( 'from recovery link', 'automation-web-platform' ),
				'event'                      => __( 'Event:', 'automation-web-platform' ),
				'confirmDeleteAll'           => __( 'Delete ALL records? This cannot be undone.', 'automation-web-platform' ),
				'confirmSmartCleanup'        => __( 'Smart cleanup: removes incomplete records whose IP already has complete data, then deduplicates remaining incomplete-only IPs keeping the newest. Continue?', 'automation-web-platform' ),
				'confirmClearSelected'       => __( 'Clear selected records?', 'automation-web-platform' ),
				'connectionError'            => __( 'Connection error', 'automation-web-platform' ),
				'failedToFetch'              => __( 'Failed to fetch sessions', 'automation-web-platform' ),
				'visibilityToggled'          => __( 'Visibility toggled', 'automation-web-platform' ),
				'errorTogglingVisibility'    => __( 'Error toggling visibility', 'automation-web-platform' ),
				'errorPerformingAction'      => __( 'Error performing action', 'automation-web-platform' ),
				'itemsSingular'              => __( '1 item', 'automation-web-platform' ),
				/* translators: %d: number of items */
				'itemsPlural'                => __( '%d items', 'automation-web-platform' ),
				'statusNew'                  => __( 'New', 'automation-web-platform' ),
				'statusNewVisitor'           => __( 'New Visitor', 'automation-web-platform' ),
				'statusAdmin'                => __( 'Admin', 'automation-web-platform' ),
				'statusPotentialCustomer'    => __( 'Potential Customer', 'automation-web-platform' ),
				'statusGuestCart'            => __( 'Guest Cart', 'automation-web-platform' ),
				'statusShopping'             => __( 'Shopping', 'automation-web-platform' ),
				'statusAbandonedCart'        => __( 'Abandoned Cart', 'automation-web-platform' ),
				'statusPurchased'            => __( 'Purchased', 'automation-web-platform' ),
				'statusReturningCustomer'    => __( 'Returning Customer', 'automation-web-platform' ),
				'statusLeftSite'             => __( 'Left Site', 'automation-web-platform' ),
				'statusReturnedToSite'       => __( 'Returned to Site', 'automation-web-platform' ),
				'statusDuplicateIps'         => __( 'Duplicate IPs', 'automation-web-platform' ),
				'sixMore'                    => __( '+6 More', 'automation-web-platform' ),
				'selected'                   => __( 'Selected', 'automation-web-platform' ),
				/* translators: %d: number of more orders */
				'andMore'                    => __( 'and +%d more', 'automation-web-platform' ),
				'associatedOrders'           => __( 'ASSOCIATED ORDERS', 'automation-web-platform' ),
				'source'                     => __( 'Source:', 'automation-web-platform' ),
				'exitPage'                   => __( 'Exit Page:', 'automation-web-platform' ),
				'start'                      => __( 'Start:', 'automation-web-platform' ),
				'totalTime'                  => __( 'Total Time:', 'automation-web-platform' ),
			),
		);
	}

	/**
	 * Get React-specific settings data.
	 *
	 * @return array
	 */
	public function get_react_settings_data() {
		$settings = array(
			'enabled'                   => (int) $this->get_wawp_setting( WAWP_Settings_Registry::ABANDONED_CARTS_ENABLED, 0 ),
			'enable_popup'              => (int) $this->get_wawp_setting( WAWP_Settings_Registry::AC_ENABLE_POPUP, 1 ),
			'popup_title'               => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_TITLE, esc_html__( 'Add your WhatsApp Number', 'automation-web-platform' ) ),
			'popup_description'         => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_DESCRIPTION, esc_html__( 'To get a better experience with our website.', 'automation-web-platform' ) ),
			'popup_display'             => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_DISPLAY, 'both' ),
			'popup_where'               => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WHERE, 'all' ),
			'popup_exclude_pages'       => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_EXCLUDE_PAGES, array() ),
			'popup_trigger_cart'        => (int) $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_TRIGGER_CART, 1 ),
			'popup_trigger_exit'        => (int) $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_TRIGGER_EXIT, 1 ),
			'popup_close_hide_duration' => (int) $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_CLOSE_HIDE_DURATION, 300 ),
			'popup_initial_delay'       => (int) $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_INITIAL_DELAY, 0 ),
			'popup_autofill_frontend'   => (int) $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_AUTOFILL_FRONTEND, 1 ),
			'checkout_autofill'         => (int) $this->get_wawp_setting( WAWP_Settings_Registry::AC_ENABLE_CHECKOUT_AUTOFILL, 1 ),
			'enable_cart_restoration'   => (int) $this->get_wawp_setting( WAWP_Settings_Registry::AC_ENABLE_CART_RESTORATION, 1 ),
			'popup_frequency'           => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_FREQUENCY, 'once' ),
			'popup_frequency_limit'     => (int) $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_FREQUENCY_LIMIT, 1 ),
			'enable_data_cleaner'       => (int) $this->get_wawp_setting( WAWP_Settings_Registry::AC_ENABLE_DATA_CLEANER, 0 ),
			'hide_incomplete'           => '1' === $this->get_wawp_setting( WAWP_Settings_Registry::AC_HIDE_INCOMPLETE_ROWS, '0' ),

			'verification_method'       => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_VERIFICATION_METHOD, 'none' ),
			'whatsappAuthType'          => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_AUTH_TYPE, 'otp' ),
			'whatsappOtpLangType'       => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_OTP_LANG_TYPE, 'site' ),
			'whatsappOtpCustomLang'     => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_OTP_CUSTOM_LANG, 'ar' ),
			'whatsappOtpFooterEnabled'  => (int) $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_OTP_FOOT_EN, 0 ),
			'whatsappOtpFooter'         => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_OTP_FOOT, 'Authorized by Wawp Engine' ),
			'whatsappListTitle'         => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_LIST_TITLE, 'Secure Authentication' ),
			'whatsappListDesc'          => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_LIST_DESC, 'Verify your identity to continue' ),
			'whatsappListFooter'        => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_LIST_FOOTER, 'Authorized by Wawp Engine' ),
			'whatsappListButton'        => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_LIST_BUTTON, 'Choose Action' ),
			'whatsappListItem1'         => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_LIST_ITEM1, 'Approve Request' ),
			'whatsappListItem1Desc'     => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_LIST_ITEM1_DESC, 'This is my login attempt' ),
			'whatsappListItem2'         => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_LIST_ITEM2, 'Reject & Report' ),
			'whatsappListItem2Desc'     => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_LIST_ITEM2_DESC, 'I don\'t recognize this' ),

			'popup_btn_color'           => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_BTN_COLOR, '#004449' ),
			'popup_btn_text_color'      => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_BTN_TEXT_COLOR, '#ffffff' ),
			'popup_btn_hover_color'     => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_BTN_HOVER_COLOR, '#003337' ),
			'popup_card_color'          => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_CARD_COLOR, '#ffffff' ),
			'popup_card_hover_color'    => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_CARD_HOVER_COLOR, '#fcfcfc' ),
			'popup_title_color'         => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_TITLE_COLOR, '#333333' ),
			'popup_title_hover_color'   => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_TITLE_HOVER_COLOR, '#111111' ),
			'popup_desc_color'          => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_DESC_COLOR, '#666666' ),
			'popup_desc_hover_color'    => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_DESC_HOVER_COLOR, '#444444' ),
			'popup_image_url'           => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_IMAGE_URL, '' ),
			'popup_image_type'          => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_IMAGE_TYPE, 'inline' ),
			'popup_image_alignment'     => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_IMAGE_ALIGNMENT, 'center' ),
			'popup_custom_css'          => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_CUSTOM_CSS, '' ),
			'popup_color_theme'         => $this->get_wawp_setting( 'wawp_ac_popup_color_theme', 'teal' ),
			'popup_save_btn'            => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_SAVE_BTN, 'Save' ),
			'popup_success_title'       => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_SUCCESS_TITLE, 'Excellent!' ),
			'popup_success_desc'        => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_SUCCESS_DESC, 'You can now browse our website better.' ),
			'popup_continue_btn'        => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_CONTINUE_BTN, 'Continue browsing' ),
		);

		$pages_obj = get_pages(
			array(
				'post_type'   => 'page',
				'post_status' => 'publish',
			)
		);
		$pages     = array();
		foreach ( $pages_obj as $p ) {
			$pages[] = array(
				'id'   => $p->ID,
				'name' => $p->post_title,
			);
		}

		return array(
			'settings'      => $settings,
			'pages'         => $pages,
			'optionNames'   => array(
				'enabled'                   => WAWP_Settings_Registry::ABANDONED_CARTS_ENABLED,
				'enable_popup'              => WAWP_Settings_Registry::AC_ENABLE_POPUP,
				'popup_title'               => WAWP_Settings_Registry::AC_POPUP_TITLE,
				'popup_description'         => WAWP_Settings_Registry::AC_POPUP_DESCRIPTION,
				'popup_display'             => WAWP_Settings_Registry::AC_POPUP_DISPLAY,
				'popup_where'               => WAWP_Settings_Registry::AC_POPUP_WHERE,
				'popup_exclude_pages'       => WAWP_Settings_Registry::AC_POPUP_EXCLUDE_PAGES,
				'popup_trigger_cart'        => WAWP_Settings_Registry::AC_POPUP_TRIGGER_CART,
				'popup_trigger_exit'        => WAWP_Settings_Registry::AC_POPUP_TRIGGER_EXIT,
				'popup_close_hide_duration' => WAWP_Settings_Registry::AC_POPUP_CLOSE_HIDE_DURATION,
				'popup_initial_delay'       => WAWP_Settings_Registry::AC_POPUP_INITIAL_DELAY,
				'popup_autofill_frontend'   => WAWP_Settings_Registry::AC_POPUP_AUTOFILL_FRONTEND,
				'checkout_autofill'         => WAWP_Settings_Registry::AC_ENABLE_CHECKOUT_AUTOFILL,
				'enable_cart_restoration'   => WAWP_Settings_Registry::AC_ENABLE_CART_RESTORATION,
				'popup_frequency'           => WAWP_Settings_Registry::AC_POPUP_FREQUENCY,
				'popup_frequency_limit'     => WAWP_Settings_Registry::AC_POPUP_FREQUENCY_LIMIT,
				'enable_data_cleaner'       => WAWP_Settings_Registry::AC_ENABLE_DATA_CLEANER,
				'hide_incomplete'           => WAWP_Settings_Registry::AC_HIDE_INCOMPLETE_ROWS,

				'popup_btn_color'           => WAWP_Settings_Registry::AC_POPUP_BTN_COLOR,
				'popup_btn_text_color'      => WAWP_Settings_Registry::AC_POPUP_BTN_TEXT_COLOR,
				'popup_btn_hover_color'     => WAWP_Settings_Registry::AC_POPUP_BTN_HOVER_COLOR,
				'popup_card_color'          => WAWP_Settings_Registry::AC_POPUP_CARD_COLOR,
				'popup_card_hover_color'    => WAWP_Settings_Registry::AC_POPUP_CARD_HOVER_COLOR,
				'popup_title_color'         => WAWP_Settings_Registry::AC_POPUP_TITLE_COLOR,
				'popup_title_hover_color'   => WAWP_Settings_Registry::AC_POPUP_TITLE_HOVER_COLOR,
				'popup_desc_color'          => WAWP_Settings_Registry::AC_POPUP_DESC_COLOR,
				'popup_desc_hover_color'    => WAWP_Settings_Registry::AC_POPUP_DESC_HOVER_COLOR,
				'popup_image_url'           => WAWP_Settings_Registry::AC_POPUP_IMAGE_URL,
				'popup_image_type'          => WAWP_Settings_Registry::AC_POPUP_IMAGE_TYPE,
				'popup_image_alignment'     => WAWP_Settings_Registry::AC_POPUP_IMAGE_ALIGNMENT,
				'popup_custom_css'          => WAWP_Settings_Registry::AC_POPUP_CUSTOM_CSS,
				'popup_color_theme'         => 'wawp_ac_popup_color_theme',
				'popup_save_btn'            => WAWP_Settings_Registry::AC_POPUP_SAVE_BTN,
				'popup_success_title'       => WAWP_Settings_Registry::AC_POPUP_SUCCESS_TITLE,
				'popup_success_desc'        => WAWP_Settings_Registry::AC_POPUP_SUCCESS_DESC,
				'popup_continue_btn'        => WAWP_Settings_Registry::AC_POPUP_CONTINUE_BTN,
				'verification_method'       => WAWP_Settings_Registry::AC_POPUP_VERIFICATION_METHOD,
				'whatsappAuthType'          => WAWP_Settings_Registry::AC_POPUP_WA_AUTH_TYPE,
				'whatsappOtpLangType'       => WAWP_Settings_Registry::AC_POPUP_WA_OTP_LANG_TYPE,
				'whatsappOtpCustomLang'     => WAWP_Settings_Registry::AC_POPUP_WA_OTP_CUSTOM_LANG,
				'whatsappOtpFooterEnabled'  => WAWP_Settings_Registry::AC_POPUP_WA_OTP_FOOT_EN,
				'whatsappOtpFooter'         => WAWP_Settings_Registry::AC_POPUP_WA_OTP_FOOT,
				'whatsappListTitle'         => WAWP_Settings_Registry::AC_POPUP_WA_LIST_TITLE,
				'whatsappListDesc'          => WAWP_Settings_Registry::AC_POPUP_WA_LIST_DESC,
				'whatsappListFooter'        => WAWP_Settings_Registry::AC_POPUP_WA_LIST_FOOTER,
				'whatsappListButton'        => WAWP_Settings_Registry::AC_POPUP_WA_LIST_BUTTON,
				'whatsappListItem1'         => WAWP_Settings_Registry::AC_POPUP_WA_LIST_ITEM1,
				'whatsappListItem1Desc'     => WAWP_Settings_Registry::AC_POPUP_WA_LIST_ITEM1_DESC,
				'whatsappListItem2'         => WAWP_Settings_Registry::AC_POPUP_WA_LIST_ITEM2,
				'whatsappListItem2Desc'     => WAWP_Settings_Registry::AC_POPUP_WA_LIST_ITEM2_DESC,
			),
			'availability'  => array(
				'whatsapp' => array(
					'available' => WAWP_Connector()->is_whatsapp_active(),
					'reason'    => ! WAWP_Connector()->is_whatsapp_active() ? esc_html__( 'WhatsApp is not connected or active.', 'automation-web-platform' ) : '',
				),
				'firebase' => array(
					'available' => WAWP_Connector()->is_firebase_active(),
					'reason'    => ! WAWP_Connector()->is_firebase_active() ? esc_html__( 'Firebase is not configured or active.', 'automation-web-platform' ) : '',
				),
			),
			'strings'       => array(
				'ab_popup_row_a'                  => esc_html__( 'Popup is actively triggering', 'automation-web-platform' ),
				'ab_popup_row_i'                  => esc_html__( 'Popup is currently paused', 'automation-web-platform' ),
				'ab_popup_disabled'               => esc_html__( 'Enable popup to configure targeting', 'automation-web-platform' ),
				'ab_popup_both'                   => esc_html__( 'Targeting all site visitors', 'automation-web-platform' ),
				'ab_popup_guest'                  => esc_html__( 'Targeting non-registered visitors only', 'automation-web-platform' ),
				'ab_popup_all'                    => esc_html__( 'Visible across all frontend pages', 'automation-web-platform' ),
				'ab_popup_restricted'             => esc_html__( 'Restricted to specific page inclusions', 'automation-web-platform' ),
				'ab_trigger_cart_a'               => esc_html__( 'Triggers immediately on add-to-cart', 'automation-web-platform' ),
				'ab_trigger_cart_i'               => esc_html__( 'Cart triggers are disabled', 'automation-web-platform' ),
				'ab_trigger_exit_a'               => esc_html__( 'Triggers when user moves to leave tab', 'automation-web-platform' ),
				'ab_trigger_exit_i'               => esc_html__( 'Exit intent triggers are disabled', 'automation-web-platform' ),
				'ab_popup_once'                   => esc_html__( 'User sees popup once per lifetime (cookie)', 'automation-web-platform' ),
				'ab_popup_every'                  => esc_html__( 'Popup shows on every page load', 'automation-web-platform' ),
				'ab_autofill_a'                   => esc_html__( 'WhatsApp capture popup will be pre-filled', 'automation-web-platform' ),
				'ab_autofill_i'                   => esc_html__( 'Visitors must enter number manually', 'automation-web-platform' ),
				'ab_cleaner_row_a'                => esc_html__( 'Auto-cleaning cart logs weekly', 'automation-web-platform' ),
				'ab_cleaner_row_i'                => esc_html__( 'Data logs preserved indefinitely', 'automation-web-platform' ),

				'preferred_channel_label'         => esc_html__( 'Preferred Verification Channel', 'automation-web-platform' ),
				'standard_otp_label'              => esc_html__( 'Standard OTP', 'automation-web-platform' ),
				'standard_otp_desc'               => esc_html__( '6-digit code via Message', 'automation-web-platform' ),
				'interactive_list_label'          => esc_html__( 'Interactive List', 'automation-web-platform' ),
				'interactive_list_desc'           => esc_html__( 'One-tap Verify/Reject', 'automation-web-platform' ),
				'message_config_label'            => esc_html__( 'Message Configuration', 'automation-web-platform' ),
				'force_language_label'            => esc_html__( 'Force Language', 'automation-web-platform' ),
				'enable_custom_footer_label'      => esc_html__( 'Enable Custom Footer', 'automation-web-platform' ),
				'list_interface_design_label'     => esc_html__( 'List Interface Design', 'automation-web-platform' ),
				'list_title_field_label'          => esc_html__( 'List Title', 'automation-web-platform' ),
				'main_description_field_label'    => esc_html__( 'Main Description', 'automation-web-platform' ),
				'item1_success_action_label'      => esc_html__( 'Item 1 (Success Action)', 'automation-web-platform' ),
				'action_title_field_label'        => esc_html__( 'Action Title', 'automation-web-platform' ),
				'action_description_field_label'  => esc_html__( 'Action Description', 'automation-web-platform' ),
				'item2_reject_action_label'       => esc_html__( 'Item 2 (Reject Action)', 'automation-web-platform' ),
				'selection_button_field_label'    => esc_html__( 'Selection Button', 'automation-web-platform' ),
				'bottom_footer_field_label'       => esc_html__( 'Bottom Footer', 'automation-web-platform' ),
				'select_language_label'           => esc_html__( 'Select Language', 'automation-web-platform' ),
				'footer_content_label'            => esc_html__( 'Footer Content', 'automation-web-platform' ),

				// Page Header.
				'recovery_title'                  => esc_html__( 'Abandoned Cart Recovery', 'automation-web-platform' ),
				'recovery_desc'                   => esc_html__( 'Capture visitor numbers before they leave to recover lost revenue.', 'automation-web-platform' ),

				// Tabs.
				'tab_general'                     => esc_html__( 'General Configuration', 'automation-web-platform' ),
				'tab_triggers'                    => esc_html__( 'Trigger Constraints', 'automation-web-platform' ),
				'tab_verification'                => esc_html__( 'Verification Settings', 'automation-web-platform' ),
				'tab_coupons'                     => esc_html__( 'Coupon Configuration', 'automation-web-platform' ),
				'tab_advanced'                    => esc_html__( 'Advanced Engine', 'automation-web-platform' ),

				// Save status.
				'saving'                          => esc_html__( 'Saving Changes...', 'automation-web-platform' ),
				'settings_saved_notice'           => esc_html__( 'All Changes Saved', 'automation-web-platform' ),
				'unsaved'                         => esc_html__( 'Unsaved Changes', 'automation-web-platform' ),
				'save_settings_btn'               => esc_html__( 'Save Changes', 'automation-web-platform' ),

				// General Tab.
				'popup_availability_title'        => esc_html__( 'Popup Availability', 'automation-web-platform' ),
				'popup_availability_desc'         => esc_html__( 'Global switch to enable or disable the recovery popup.', 'automation-web-platform' ),
				'content_design_title'            => esc_html__( 'Content Design', 'automation-web-platform' ),
				'content_design_desc'             => esc_html__( 'Craft the message that will convince users to stay.', 'automation-web-platform' ),
				'master_title_label'              => esc_html__( 'Master Title', 'automation-web-platform' ),
				'main_desc_label'                 => esc_html__( 'Main Description', 'automation-web-platform' ),
				'button_success_labels_title'     => esc_html__( 'Button & Success State Labels', 'automation-web-platform' ),
				'save_btn_text_label'             => esc_html__( 'Save Button Text', 'automation-web-platform' ),
				'continue_btn_text_label'         => esc_html__( 'Continue Button Text', 'automation-web-platform' ),
				'success_title_label'             => esc_html__( 'Success Title', 'automation-web-platform' ),
				'success_desc_label'              => esc_html__( 'Success Description', 'automation-web-platform' ),

				// Visual Customization.
				'visual_custom_title'             => esc_html__( 'Visual Customization', 'automation-web-platform' ),
				'visual_custom_desc'              => esc_html__( 'Customize the appearance of your popup to match your brand.', 'automation-web-platform' ),
				'popup_image_label'               => esc_html__( 'Popup Image', 'automation-web-platform' ),
				'popup_image_desc'                => esc_html__( 'Use a transparent PNG, SVG, or GIF. For banners, use a wide image (e.g. 550x150px).', 'automation-web-platform' ),
				'select_image_btn'                => esc_html__( 'Select Image', 'automation-web-platform' ),
				'change_image_btn'                => esc_html__( 'Change Image', 'automation-web-platform' ),
				'image_type_inline'               => esc_html__( 'Inline', 'automation-web-platform' ),
				'image_type_banner'               => esc_html__( 'Banner', 'automation-web-platform' ),
				'align_left'                      => esc_html__( 'Left', 'automation-web-platform' ),
				'align_center'                    => esc_html__( 'Center', 'automation-web-platform' ),
				'align_right'                     => esc_html__( 'Right', 'automation-web-platform' ),
				'custom_css_label'                => esc_html__( 'Custom CSS', 'automation-web-platform' ),
				'custom_styles_active'            => esc_html__( 'Custom Styles Active', 'automation-web-platform' ),
				'standard_design_active'          => esc_html__( 'Standard design is active', 'automation-web-platform' ),
				'custom_styles_applied'           => esc_html__( 'Your custom styles are being applied with high priority.', 'automation-web-platform' ),
				'custom_styles_injected'          => esc_html__( 'Your custom styles will be injected into the footer and applied with high priority to override default layouts.', 'automation-web-platform' ),
				'color_presets_label'             => esc_html__( 'Color Presets', 'automation-web-platform' ),
				'preset_teal'                     => esc_html__( 'Teal', 'automation-web-platform' ),
				'preset_midnight'                 => esc_html__( 'Midnight', 'automation-web-platform' ),
				'preset_ocean'                    => esc_html__( 'Ocean', 'automation-web-platform' ),
				'preset_sunset'                   => esc_html__( 'Sunset', 'automation-web-platform' ),
				'preset_minimal'                  => esc_html__( 'Minimal', 'automation-web-platform' ),
				'preset_warm'                     => esc_html__( 'Warm', 'automation-web-platform' ),
				'detailed_colors_label'           => esc_html__( 'Detailed Colors', 'automation-web-platform' ),
				'color_label_btn'                 => esc_html__( 'Button', 'automation-web-platform' ),
				'color_label_btn_hover'           => esc_html__( 'Button Hover', 'automation-web-platform' ),
				'color_label_card_bg'             => esc_html__( 'Card Background', 'automation-web-platform' ),
				'color_label_card_hover'          => esc_html__( 'Card Hover', 'automation-web-platform' ),
				'color_label_title'               => esc_html__( 'Title', 'automation-web-platform' ),
				'color_label_desc'                => esc_html__( 'Description', 'automation-web-platform' ),
				'color_group_action'              => esc_html__( 'Action', 'automation-web-platform' ),
				'color_group_card'                => esc_html__( 'Card', 'automation-web-platform' ),
				'color_group_text'                => esc_html__( 'Text', 'automation-web-platform' ),

				// Triggers Tab.
				'audience_targeting_title'        => esc_html__( 'Audience Targeting', 'automation-web-platform' ),
				'audience_targeting_desc'         => esc_html__( 'Segment users who should see the recovery mechanism.', 'automation-web-platform' ),
				'target_user_group_label'         => esc_html__( 'Target User Group', 'automation-web-platform' ),
				'opt_all_visitors'                => esc_html__( 'All Visitors (Guests & Logged In)', 'automation-web-platform' ),
				'opt_registered_only'             => esc_html__( 'Registered Users Only', 'automation-web-platform' ),
				'opt_guest_only'                  => esc_html__( 'Guest Visitors Only', 'automation-web-platform' ),
				'status_registered_only'          => esc_html__( 'Only registered users will see the popup', 'automation-web-platform' ),
				'device_targeting_label'          => esc_html__( 'Device Targeting', 'automation-web-platform' ),
				'opt_all_devices'                 => esc_html__( 'Show on All Devices', 'automation-web-platform' ),
				'opt_desktop_only'                => esc_html__( 'Desktop Only', 'automation-web-platform' ),
				'opt_mobile_only'                 => esc_html__( 'Mobile Only', 'automation-web-platform' ),
				'status_all_devices'              => esc_html__( 'Popup shows on all devices.', 'automation-web-platform' ),
				'status_desktop_only'             => esc_html__( 'Popup is limited to Desktop devices only.', 'automation-web-platform' ),
				'status_mobile_only'              => esc_html__( 'Popup is limited to Mobile devices only.', 'automation-web-platform' ),
				'page_accessibility_label'        => esc_html__( 'Page Accessibility', 'automation-web-platform' ),
				'opt_show_everywhere'             => esc_html__( 'Show Everywhere', 'automation-web-platform' ),
				'desc_global_display'             => esc_html__( 'Global display', 'automation-web-platform' ),
				'opt_exclude_pages'               => esc_html__( 'Exclude Pages', 'automation-web-platform' ),
				'desc_selective_display'          => esc_html__( 'Selective display', 'automation-web-platform' ),
				'exclude_pages_placeholder'       => esc_html__( 'Select pages to exclude...', 'automation-web-platform' ),
				'cart_activity_title'             => esc_html__( 'Cart Activity', 'automation-web-platform' ),
				'cart_activity_desc'              => esc_html__( 'Trigger on Add-to-Cart.', 'automation-web-platform' ),
				'exit_intent_title'               => esc_html__( 'Exit Intent', 'automation-web-platform' ),
				'exit_intent_desc'                => esc_html__( 'Trigger on cursor leave.', 'automation-web-platform' ),
				'timing_engine_title'             => esc_html__( 'Timing Engine', 'automation-web-platform' ),
				'timing_engine_desc'              => esc_html__( 'Manage how often and when the popup interrupts the user.', 'automation-web-platform' ),
				'post_close_hide_label'           => esc_html__( 'Post-Close Hide Period', 'automation-web-platform' ),
				'initial_delay_label'             => esc_html__( 'Initial Activation Delay', 'automation-web-platform' ),
				'duration_seconds_desc'           => esc_html__( 'Duration in seconds', 'automation-web-platform' ),
				'wait_seconds_desc'               => esc_html__( 'Wait time in seconds', 'automation-web-platform' ),
				'frequency_control_label'         => esc_html__( 'Frequency Control', 'automation-web-platform' ),
				'opt_freq_once'                   => esc_html__( 'Optimized (Once per visitor)', 'automation-web-platform' ),
				'opt_freq_every'                  => esc_html__( 'Aggressive (Every page load)', 'automation-web-platform' ),
				'opt_freq_limit'                  => esc_html__( 'Custom Limit (Session capped)', 'automation-web-platform' ),
				/* translators: %d: impression limit */
				'status_freq_limit'               => esc_html__( 'Limited to %d times per session', 'automation-web-platform' ),
				'impression_limit_label'          => esc_html__( 'Impression Limit', 'automation-web-platform' ),
				'max_views_desc'                  => esc_html__( 'Max views per session', 'automation-web-platform' ),
				'min_cart_value_label'            => esc_html__( 'Minimum Cart Value Required', 'automation-web-platform' ),
				'min_cart_value_desc'             => esc_html__( 'The popup will only show if the cart subtotal is greater than or equal to this amount. (Set 0 to disable)', 'automation-web-platform' ),

				// Verification Tab.
				'verification_settings_title'     => esc_html__( 'Cart Verification Settings', 'automation-web-platform' ),
				'verification_settings_desc'      => esc_html__( 'Secure recovery captures by enforcing mobile number verification before carts are recorded.', 'automation-web-platform' ),
				'opt_verification_none'           => esc_html__( 'None', 'automation-web-platform' ),
				'desc_verification_none'          => esc_html__( 'Direct telephone capture without verification.', 'automation-web-platform' ),
				'opt_verification_whatsapp'       => esc_html__( 'WhatsApp OTP / List', 'automation-web-platform' ),
				'desc_verification_whatsapp'      => esc_html__( 'High-speed WhatsApp OTP & Interactive list verification.', 'automation-web-platform' ),
				'opt_verification_firebase'       => esc_html__( 'Firebase SMS OTP', 'automation-web-platform' ),
				'desc_verification_firebase'      => esc_html__( 'Use Google Firebase to send global SMS verification codes.', 'automation-web-platform' ),
				'whatsapp_channel_title'          => esc_html__( 'WhatsApp Verification Channel', 'automation-web-platform' ),
				'whatsapp_channel_desc'           => esc_html__( 'Configure preferred WhatsApp verification behavior, language overrides, and list styles.', 'automation-web-platform' ),
				'firebase_channel_title'          => esc_html__( 'Firebase SMS OTP Settings', 'automation-web-platform' ),
				'firebase_channel_desc'           => esc_html__( 'Configure Firebase API and web credentials under Core Firebase Settings.', 'automation-web-platform' ),
				'firebase_active_globally'        => esc_html__( 'Firebase SMS Verification is configured and active globally.', 'automation-web-platform' ),

				// Coupons Tab.
				'coupon_settings_title'           => esc_html__( 'Coupon Code Settings', 'automation-web-platform' ),
				'coupon_settings_desc'            => esc_html__( 'Auto-generate and attach a unique discount code to these reminders.', 'automation-web-platform' ),
				'create_coupon_btn'               => esc_html__( 'Create Coupon', 'automation-web-platform' ),
				'access_coupons_btn'              => esc_html__( 'Access Coupons', 'automation-web-platform' ),
				'enable_coupon_gen_label'         => esc_html__( 'Enable Coupon Generation', 'automation-web-platform' ),
				'enable_coupon_gen_desc'          => esc_html__( 'Enable this to generate unique coupon codes for notifications.', 'automation-web-platform' ),
				'status_coupon_gen_active'        => esc_html__( 'Active: Unique coupons will be generated for abandoned cart recovery.', 'automation-web-platform' ),
				'status_coupon_gen_inactive'      => esc_html__( 'Inactive: No coupons will be generated for abandoned cart recovery.', 'automation-web-platform' ),
				'coupon_value_label'              => esc_html__( 'Coupon Value', 'automation-web-platform' ),
				'coupon_amount_label'             => esc_html__( 'Amount', 'automation-web-platform' ),
				'discount_type_percent'           => esc_html__( 'Percentage (%)', 'automation-web-platform' ),
				/* translators: %s: currency symbol */
				'discount_type_fixed'             => esc_html__( 'Fixed Amount (%s)', 'automation-web-platform' ),
				/* translators: 1: currency symbol, 2: currency symbol, 3: calculated discount value */
				'coupon_example_desc'             => esc_html__( 'Example: A %1$s100 cart will drop to %2$s%3$s after discount. (Recommended: 10% or more for best recovery)', 'automation-web-platform' ),
				'coupon_prefix_label'             => esc_html__( 'Coupon Prefix', 'automation-web-platform' ),
				/* translators: %s: coupon prefix */
				'coupon_prefix_desc'              => esc_html__( 'The prefix attached to generated coupon codes (e.g. %s-XXXX). Default: REC.', 'automation-web-platform' ),
				'coupon_expires_label'            => esc_html__( 'Coupon Expires After', 'automation-web-platform' ),
				'unit_hours'                      => esc_html__( 'Hours', 'automation-web-platform' ),
				'unit_days'                       => esc_html__( 'Days', 'automation-web-platform' ),
				'unit_weeks'                      => esc_html__( 'Weeks', 'automation-web-platform' ),
				'coupon_expiry_desc'              => esc_html__( 'Unique expiry per customer based on receipt date. Recommended: 3–7 days.', 'automation-web-platform' ),
				'min_spend_label'                 => esc_html__( 'Minimum Spend', 'automation-web-platform' ),
				'min_spend_placeholder'           => esc_html__( 'No minimum limit', 'automation-web-platform' ),
				/* translators: 1: currency symbol, 2: minimum spend amount */
				'status_min_spend_active'         => esc_html__( 'Active: Only orders above %1$s%2$s will receive this coupon.', 'automation-web-platform' ),
				'status_min_spend_inactive'       => esc_html__( 'Inactive: No minimum spend required. (Better for low-value cart recovery)', 'automation-web-platform' ),
				'auto_apply_link_label'           => esc_html__( 'Auto-Apply via Link', 'automation-web-platform' ),
				'auto_apply_link_desc'            => esc_html__( 'Automatically apply generated coupon when restoring cart via link.', 'automation-web-platform' ),
				'email_restrict_label'            => esc_html__( 'Email Restriction', 'automation-web-platform' ),
				'email_restrict_desc'             => esc_html__( 'Restrict the generated coupon code exclusively to the customer\'s email.', 'automation-web-platform' ),
				'individual_use_label'            => esc_html__( 'Individual Use Only', 'automation-web-platform' ),
				'individual_use_desc'             => esc_html__( 'Coupon cannot be used with other coupons.', 'automation-web-platform' ),
				'free_shipping_label'             => esc_html__( 'Free Shipping', 'automation-web-platform' ),
				'free_shipping_desc'              => esc_html__( 'Check this if the coupon grants free shipping.', 'automation-web-platform' ),
				'exclude_sale_items_label'        => esc_html__( 'Exclude Sale Items', 'automation-web-platform' ),
				'exclude_sale_items_desc'         => esc_html__( 'Coupon will not apply to items already on sale.', 'automation-web-platform' ),
				'max_discount_cap_label'          => esc_html__( 'Maximum Discount Cap', 'automation-web-platform' ),
				'max_discount_placeholder'        => esc_html__( 'No limit', 'automation-web-platform' ),
				/* translators: 1: currency symbol, 2: maximum discount amount */
				'status_max_discount_active'      => esc_html__( 'Active: Coupon discount will be capped at %1$s%2$s per order.', 'automation-web-platform' ),
				'status_max_discount_inactive'    => esc_html__( 'Inactive: No maximum discount limit.', 'automation-web-platform' ),
				'product_restrict_label'          => esc_html__( 'Product Restrictions (IDs)', 'automation-web-platform' ),
				/* translators: %s: product IDs */
				'status_product_restrict_active'  => esc_html__( 'Active: Coupon restricted to products with IDs: %s.', 'automation-web-platform' ),
				'status_product_restrict_i'       => esc_html__( 'Inactive: Applicable to all products.', 'automation-web-platform' ),
				'category_restrict_label'         => esc_html__( 'Category Restrictions (IDs)', 'automation-web-platform' ),
				/* translators: %s: category IDs */
				'status_category_restrict_active' => esc_html__( 'Active: Coupon restricted to categories with IDs: %s.', 'automation-web-platform' ),
				'status_category_restrict_i'      => esc_html__( 'Inactive: Applicable to all product categories.', 'automation-web-platform' ),
				'coupon_placeholders_title'       => esc_html__( 'Coupon Code Placeholders', 'automation-web-platform' ),
				'coupon_placeholders_desc'        => esc_html__( 'Use placeholders in your templates to trigger dynamic discounts.', 'automation-web-platform' ),
				'coupon_placeholders_body'        => esc_html__( 'Use the placeholder below inside your Email templates or WhatsApp messages. When a customer receives this message, it will be automatically replaced with their unique auto-generated coupon code.', 'automation-web-platform' ),
				'dynamic_coupon_code_label'       => esc_html__( 'Dynamic Coupon Code', 'automation-web-platform' ),
				'copy_placeholder_btn'            => esc_html__( 'Copy Placeholder', 'automation-web-platform' ),
				'how_it_works_label'              => esc_html__( 'How it works:', 'automation-web-platform' ),
				'coupon_how_it_works_desc'        => esc_html__( 'This dynamic placeholder automatically generates a unique WooCommerce coupon code for each abandoned cart reminder (e.g., REC-123-ABCDEF) based on the criteria configured above.', 'automation-web-platform' ),

				// Advanced Tab.
				'link_cart_restore_title'         => esc_html__( 'Link Cart Restoration', 'automation-web-platform' ),
				'link_cart_restore_desc'          => esc_html__( 'Allow customers to automatically restore their exact abandoned shopping cart when clicking a recovery link.', 'automation-web-platform' ),
				'status_cart_restore_active'      => esc_html__( 'Customers can restore their cart via recovery link', 'automation-web-platform' ),
				'status_cart_restore_inactive'    => esc_html__( 'Link recovery is disabled; cart will not auto-fill on visit', 'automation-web-platform' ),
				'checkout_autofill_title'         => esc_html__( 'Checkout Form Auto-Fill', 'automation-web-platform' ),
				'checkout_autofill_desc'          => esc_html__( 'Automatically restore previously captured contact and billing details in the WooCommerce checkout form.', 'automation-web-platform' ),
				'status_checkout_autofill_a'      => esc_html__( 'Customer data will auto-populate WooCommerce checkout fields', 'automation-web-platform' ),
				'status_checkout_autofill_i'      => esc_html__( 'Checkout fields will remain empty for returning visitors', 'automation-web-platform' ),
				'popup_autofill_title'            => esc_html__( 'Popup Form Auto-Fill', 'automation-web-platform' ),
				'popup_autofill_desc'             => esc_html__( 'Pre-fill the WhatsApp capture popup if the user\'s number is already known.', 'automation-web-platform' ),
				'data_hygiene_title'              => esc_html__( 'Automated Data Hygiene', 'automation-web-platform' ),
				'data_hygiene_desc'               => esc_html__( 'Automatically purge old abandoned cart records weekly to optimize database size.', 'automation-web-platform' ),
				'recovery_link_placeholders_t'    => esc_html__( 'Recovery Link Placeholders', 'automation-web-platform' ),
				'recovery_link_placeholders_d'    => esc_html__( 'Use placeholders in your templates to trigger instant cart restoration.', 'automation-web-platform' ),
				'recovery_link_placeholders_b'    => esc_html__( 'Use the placeholder below inside your Email templates or WhatsApp messages. When a customer clicks this link, their cart is completely restored and they are redirected to checkout.', 'automation-web-platform' ),
				'cart_recovery_link_label'        => esc_html__( 'Cart Recovery Link', 'automation-web-platform' ),
				'recovery_how_it_works_desc'      => esc_html__( 'This dynamic placeholder automatically generates a unique, secure, and encrypted link for each user session (e.g., https://yoursite.com/?wawp_restore_cart=1&wac_id=123).', 'automation-web-platform' ),

				// Toast & Alert actions.
				'toast_coupon_success'            => esc_html__( 'Coupon generated successfully!', 'automation-web-platform' ),
				'toast_coupon_failed'             => esc_html__( 'Failed to generate coupon', 'automation-web-platform' ),
				'toast_coupon_error'              => esc_html__( 'An error occurred during coupon generation', 'automation-web-platform' ),
				'toast_save_success'              => esc_html__( 'Settings saved successfully', 'automation-web-platform' ),
				'toast_save_failed'               => esc_html__( 'Failed to save settings', 'automation-web-platform' ),
				'toast_save_error'                => esc_html__( 'An error occurred during save', 'automation-web-platform' ),
				'toast_placeholder_copied'        => esc_html__( 'Placeholder copied to clipboard!', 'automation-web-platform' ),
			),
			'notifications' => $this->get_wawp_setting( WAWP_Settings_Registry::ABANDONED_CART_NOTIFICATIONS_SETTINGS ),
		);
	}

	/**
	 * Clear abandoned carts.
	 *
	 * @param array $params Request parameters.
	 * @return array Result data.
	 */
	public function clear_abandoned_carts( $params ) {
		global $wpdb;
		$table      = $wpdb->prefix . 'wawp_abandoned_carts';
		$clear_type = isset( $params['clear_type'] ) ? sanitize_text_field( $params['clear_type'] ) : '';

		if ( 'all' === $clear_type ) {
			WAWP()->db->truncate_row( 'abandoned_carts' );
			return array(
				'success' => true,
				'data'    => array( 'message' => esc_html__( 'All records cleared', 'automation-web-platform' ) ),
			);
		}

		if ( 'incomplete' === $clear_type ) {

			WAWP()->db->execute_query( $wpdb->prepare( "DELETE FROM %i WHERE (browser IS NULL OR browser = '') AND (os IS NULL OR os = '') AND (device IS NULL OR device = '') AND (page_history IS NULL OR page_history = '' OR page_history = '[]')", $table ) );
			wp_cache_flush_group( 'wawp_ac' );
			return array(
				'success' => true,
				'data'    => array( 'message' => esc_html__( 'Incomplete records cleared', 'automation-web-platform' ) ),
			);
		}

		if ( 'selected' === $clear_type && ! empty( $params['ids'] ) && is_array( $params['ids'] ) ) {
			$ids = array_map( 'intval', $params['ids'] );
			foreach ( $ids as $id ) {
				WAWP()->db->delete_row( 'abandoned_carts', array( 'id' => $id ) );
			}
			wp_cache_flush_group( 'wawp_ac' );
			return array(
				'success' => true,
				'data'    => array(
					'message' => sprintf(
							/* translators: %d: Number of records */
						esc_html__( '%d records cleared', 'automation-web-platform' ),
						count( $ids )
					),
				),
			);
		}

		return array(
			'success' => false,
			'data'    => array( 'message' => esc_html__( 'Invalid clear operation', 'automation-web-platform' ) ),
		);
	}

	/**
	 * Toggle visibility.
	 *
	 * @return array Result data.
	 */
	public function toggle_hide_incomplete() {
		$current = $this->get_wawp_setting( WAWP_Settings_Registry::AC_HIDE_INCOMPLETE_ROWS, '0' );
		$new_val = ( '1' === $current ) ? '0' : '1';
		$this->update_wawp_setting( WAWP_Settings_Registry::AC_HIDE_INCOMPLETE_ROWS, $new_val );
		wp_cache_delete( 'wawp_ac_db_rows_list', 'wawp_ac' );
		if ( function_exists( 'wp_cache_flush_group' ) ) {
			wp_cache_flush_group( 'wawp_ac' );
		}
		return array(
			'success' => true,
			'data'    => array( 'message' => 'Visibility toggled' ),
		);
	}

	/**
	 * AJAX Handlers.
	 */
	public function get_sessions_ajax() {
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'wawp_abandoned_cart_nonce' ) ) {
			$this->send_error( esc_html__( 'Security check failed.', 'automation-web-platform' ), 403 );
		}
		$this->check_permissions( 'wawp_abandoned_cart_nonce' );
		$this->send_success( '', $this->get_sessions_return( $_POST ) );
	}

	/**
	 * AJAX Handler for clearing abandoned carts.
	 */
	public function clear_abandoned_carts_ajax() {
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'wawp_abandoned_cart_nonce' ) ) {
			$this->send_error( esc_html__( 'Security check failed.', 'automation-web-platform' ), 403 );
		}
		$this->check_permissions( 'wawp_abandoned_cart_nonce' );
		$this->send_success( '', $this->clear_abandoned_carts( $_POST ) );
	}

	/**
	 * AJAX Handler for toggling incomplete rows visibility.
	 */
	public function toggle_hide_incomplete_ajax() {
		$this->check_permissions( 'wawp_abandoned_cart_nonce' );
		$this->send_success( '', $this->toggle_hide_incomplete() );
	}

	/**
	 * Merge duplicate sessions by rule.
	 */
	public function merge_duplicate_sessions_by_rule() {
		global $wpdb;
		$table = $wpdb->prefix . 'wawp_abandoned_carts';

		$cache_key = 'wawp_ac_merge_rows';
		$rows      = wp_cache_get( $cache_key, 'wawp_ac' );
		if ( false === $rows ) {
			$rows = WAWP()->db->get_results_cached( $wpdb->prepare( "SELECT * FROM %i WHERE contact_details IS NOT NULL AND contact_details <> '' AND location IS NOT NULL AND location <> ''", $table ), $cache_key, 'wawp_ac', 300 );
		}
		$rows = ! empty( $rows ) ? array_map(
			function ( $r ) {
				return (object) $r;
			},
			$rows
		) : array();
		if ( empty( $rows ) ) {
			return;
		}

		$records = array();
		foreach ( $rows as $row ) {
			$cd           = maybe_unserialize( $row->contact_details );
			$name         = '';
			$contact      = '';
			$billing_info = '';

			if ( is_array( $cd ) ) {
				$first        = isset( $cd['billing_first_name'] ) ? trim( strtolower( $cd['billing_first_name'] ) ) : '';
				$last         = isset( $cd['billing_last_name'] ) ? trim( strtolower( $cd['billing_last_name'] ) ) : '';
				$name         = $first . ' ' . $last;
				$email        = isset( $cd['billing_email'] ) ? trim( strtolower( $cd['billing_email'] ) ) : '';
				$phone        = isset( $cd['billing_phone'] ) ? $this->get_digits_only( $cd['billing_phone'] ) : '';
				$contact      = $email . ' ' . $phone;
				$address1     = isset( $cd['billing_address_1'] ) ? trim( strtolower( $cd['billing_address_1'] ) ) : '';
				$address2     = isset( $cd['billing_address_2'] ) ? trim( strtolower( $cd['billing_address_2'] ) ) : '';
				$city         = isset( $cd['billing_city'] ) ? trim( strtolower( $cd['billing_city'] ) ) : '';
				$state        = isset( $cd['billing_state'] ) ? trim( strtolower( $cd['billing_state'] ) ) : '';
				$postcode     = isset( $cd['billing_postcode'] ) ? trim( strtolower( $cd['billing_postcode'] ) ) : '';
				$country      = isset( $cd['billing_country'] ) ? trim( strtolower( $cd['billing_country'] ) ) : '';
				$billing_info = $address1 . ' ' . $address2 . ' ' . $city . ' ' . $state . ' ' . $postcode . ' ' . $country;
			}

			$location            = strtolower( trim( $row->location ) );
			$records[ $row->id ] = array(
				'id'           => $row->id,
				'name'         => $name,
				'contact'      => $contact,
				'billing_info' => $billing_info,
				'location'     => $location,
				'status'       => strtolower( $row->status ),
				'page_history' => $row->page_history,
				'order_id'     => $row->order_id,
				'row'          => $row,
			);
		}

		$groups     = array();
		$visited    = array();
		$record_ids = array_keys( $records );

		foreach ( $record_ids as $id ) {
			if ( in_array( $id, $visited, true ) ) {
				continue;
			}

			$group     = array( $id );
			$visited[] = $id;

			foreach ( $record_ids as $other_id ) {
				if ( $other_id === $id ) {
					continue;
				}
				if ( in_array( $other_id, $visited, true ) ) {
					continue;
				}

				$r1    = $records[ $id ];
				$r2    = $records[ $other_id ];
				$score = 0;

				if ( '' !== $r1['name'] && '' !== $r2['name'] && $r1['name'] === $r2['name'] ) {
					$score += 2;
				}
				if ( '' !== $r1['contact'] && '' !== $r2['contact'] && $r1['contact'] === $r2['contact'] ) {
					$score += 4;
				}
				if ( '' !== $r1['location'] && '' !== $r2['location'] && $r1['location'] === $r2['location'] ) {
					$score += 2;
				}
				if ( '' !== $r1['billing_info'] && '' !== $r2['billing_info'] && $r1['billing_info'] === $r2['billing_info'] ) {
					$score += 3;
				}

				if ( $score >= 4 ) {
					$group[]   = $other_id;
					$visited[] = $other_id;
				}
			}

			if ( count( $group ) > 1 ) {
				$groups[] = $group;
			}
		}

		foreach ( $groups as $group_ids ) {
			$group_records = array();
			foreach ( $group_ids as $gid ) {
				$group_records[] = $records[ $gid ];
			}

			usort(
				$group_records,
				function ( $a, $b ) {
					$s_map = array(
						'purchased'          => 5,
						'shopping'           => 4,
						'potential customer' => 3,
						'returning customer' => 2,
						'online'             => 1,
						'new'                => 0,
					);
					$v1    = $s_map[ $a['status'] ] ?? 0;
					$v2    = $s_map[ $b['status'] ] ?? 0;
					if ( $v1 !== $v2 ) {
						return $v2 <=> $v1;
					}
					return $b['id'] <=> $a['id'];
				}
			);

			$keep_record = array_shift( $group_records );
			$delete_ids  = array();
			foreach ( $group_records as $dr ) {
				$delete_ids[] = $dr['id'];
			}

			if ( ! empty( $delete_ids ) ) {
				foreach ( $delete_ids as $id ) {
					WAWP()->db->delete_row( 'abandoned_carts', array( 'id' => $id ) );
				}
				wp_cache_flush_group( 'wawp_ac' );
			}
		}
	}
}
