<?php
/**
 * Cart Abandonment Tracker with Cron Jobs
 *
 * This class handles cart abandonment tracking using WordPress cron jobs
 * to detect when users abandon their carts even after closing the browser.
 *
 * @package SHOPEXPLORER\Ajax
 */

namespace SHOPEXPLORER\Ajax;

use SHOPEXPLORER\Database\DatabaseManager;

defined('ABSPATH') || die('Hey, what are you doing here? You silly human!');

/**
 * Cart Abandonment Tracker Class
 *
 * @since 1.0.0
 */
class SHOPEX_CartAbandonmentTracker {

	/**
	 * Constructor
	 */
	public function __construct() {
		// Add custom cron schedule
		add_filter('cron_schedules', [$this, 'add_custom_cron_schedules']);
		
		// Hook into cart events (Classic WooCommerce)
		add_action('woocommerce_add_to_cart', [$this, 'track_cart_activity'], 10, 6);
		add_action('woocommerce_cart_item_removed', [$this, 'track_cart_removal'], 10, 2);
		add_action('woocommerce_before_cart_item_quantity_zero', [$this, 'track_cart_removal'], 10, 2);
		add_action('woocommerce_cart_item_set_quantity', [$this, 'track_cart_quantity_change'], 10, 3);
		add_action('woocommerce_after_cart_item_quantity_update', [$this, 'track_cart_update'], 10, 4);
		add_action('woocommerce_cart_emptied', [$this, 'track_cart_emptied']);
		add_action('woocommerce_before_cart_emptied', [$this, 'track_cart_emptied']);
		
		// Hook into WooCommerce Blocks cart events (for modern themes)
		add_action('woocommerce_store_api_cart_update_item', [$this, 'track_blocks_cart_update'], 10, 2);
		add_action('woocommerce_store_api_cart_remove_item', [$this, 'track_blocks_cart_removal'], 10, 2);
		add_action('woocommerce_store_api_cart_add_item', [$this, 'track_blocks_cart_add'], 10, 2);
		
		// Hook into checkout events
		add_action('woocommerce_checkout_init', [$this, 'track_checkout_start']);
		add_action('woocommerce_checkout_process', [$this, 'track_checkout_process']);
		
		// Hook into page loads to capture cart state
		add_action('wp', [$this, 'maybe_track_cart_on_page_load']);
		
		// Schedule abandonment checks
		add_action('wp_loaded', [$this, 'schedule_abandonment_checks']);
		add_action('wpnts_check_cart_abandonment', [$this, 'process_cart_abandonment']);
		add_action('wpnts_cleanup_old_cart_sessions', [$this, 'cleanup_old_sessions']);
		
		// AJAX handlers for cart tracking
		add_action('wp_ajax_wpnts_track_cart_session', [$this, 'track_cart_session']);
		add_action('wp_ajax_nopriv_wpnts_track_cart_session', [$this, 'track_cart_session']);
		
		// Bridge handler for cart interactions (connects to enhanced checkout tracking)
		add_action('wp_ajax_wpnts_track_cart_interaction_bridge', [$this, 'track_cart_interaction_bridge']);
		add_action('wp_ajax_nopriv_wpnts_track_cart_interaction_bridge', [$this, 'track_cart_interaction_bridge']);
		
		// Debug handler
		add_action('wp_ajax_wpnts_debug_cart_data', [$this, 'debug_cart_data']);
		
		// Test cart tracking handler
		add_action('wp_ajax_wpnts_test_cart_tracking', [$this, 'test_cart_tracking']);
		
		// Manual cleanup handler (for testing)
		add_action('wp_ajax_wpnts_manual_cleanup', [$this, 'manual_cleanup']);
		
		// Clean up on order completion
		add_action('woocommerce_checkout_order_processed', [$this, 'clear_cart_session'], 10, 1);
		add_action('woocommerce_thankyou', [$this, 'clear_cart_session'], 10, 1);
	}

	/**
	 * Add custom cron schedules
	 */
	public function add_custom_cron_schedules($schedules) {
		$schedules['wpnts_five_minutes'] = [
			'interval' => 300, // 5 minutes in seconds
			'display' => __('Every 5 Minutes', 'shop-explorer')
		];
		return $schedules;
	}

	/**
	 * Schedule abandonment check cron jobs
	 */
	public function schedule_abandonment_checks() {
		// Schedule every 5 minutes to check for abandoned carts
		if (!wp_next_scheduled('wpnts_check_cart_abandonment')) {
			wp_schedule_event(time(), 'wpnts_five_minutes', 'wpnts_check_cart_abandonment');
		}
		
		// Schedule daily cleanup of old sessions
		if (!wp_next_scheduled('wpnts_cleanup_old_cart_sessions')) {
			wp_schedule_event(time(), 'daily', 'wpnts_cleanup_old_cart_sessions');
		}
	}

	/**
	 * Track when items are added to cart
	 */
	public function track_cart_activity($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
		
		$this->update_cart_session([
			'action' => 'add_to_cart',
			'product_id' => $product_id,
			'quantity' => $quantity,
			'variation_id' => $variation_id,
			'timestamp' => time()
		], null);
		
		// Immediately create/update incomplete order when cart changes
		$result = $this->create_incomplete_order_from_current_cart();
	}

	/**
	 * Track when items are removed from cart
	 */
	public function track_cart_removal($cart_item_key, $cart) {
		$cart_item = $cart->get_cart_item($cart_item_key);
		if ($cart_item) {
			
			$this->update_cart_session([
				'action' => 'remove_from_cart',
				'product_id' => $cart_item['product_id'],
				'quantity' => $cart_item['quantity'],
				'timestamp' => time()
			], null);
			
			// Update incomplete order record with current cart state (after removal)
			$result = $this->create_incomplete_order_from_current_cart();
		}
	}

	/**
	 * Track cart quantity changes
	 */
	public function track_cart_quantity_change($cart_item_key, $quantity, $old_quantity) {
		$this->update_cart_session([
			'action' => 'quantity_change',
			'cart_item_key' => $cart_item_key,
			'new_quantity' => $quantity,
			'old_quantity' => $old_quantity,
			'timestamp' => time()
		], null);
		
		// Update incomplete order with new quantities
		$this->create_incomplete_order_from_current_cart();
	}

	/**
	 * Track cart updates
	 */
	public function track_cart_update($cart_item_key, $quantity, $old_quantity, $cart) {
		$cart_item = $cart->get_cart_item($cart_item_key);
		if ($cart_item) {
			$this->update_cart_session([
				'action' => 'cart_update',
				'product_id' => $cart_item['product_id'],
				'quantity' => $quantity,
				'old_quantity' => $old_quantity,
				'timestamp' => time()
			], null);
			
			// Update incomplete order with new cart state
			$this->create_incomplete_order_from_current_cart();
		}
	}

	/**
	 * Track when cart is completely emptied
	 */
	public function track_cart_emptied() {
		
		$this->update_cart_session([
			'action' => 'cart_emptied',
			'timestamp' => time()
		], null);
		
		// Mark incomplete order as completed since cart is empty
		$session_key = $this->get_session_key();
		if ($session_key) {
			$this->mark_incomplete_order_completed_by_session($session_key, 'cart_emptied');
		}
	}

	/**
	 * Track WooCommerce Blocks cart additions
	 */
	public function track_blocks_cart_add($cart_item, $request) {
		
		$this->update_cart_session([
			'action' => 'blocks_add_to_cart',
			'product_id' => $cart_item['product_id'] ?? 0,
			'quantity' => $cart_item['quantity'] ?? 1,
			'timestamp' => time()
		], null);
		
		// Create/update incomplete order
		$result = $this->create_incomplete_order_from_current_cart();
	}

	/**
	 * Track WooCommerce Blocks cart removals
	 */
	public function track_blocks_cart_removal($cart_item_key, $cart) {
		
		// Get the cart item before it's removed (if possible)
		$cart_item = null;
		if (is_object($cart) && method_exists($cart, 'get_cart_item')) {
			$cart_item = $cart->get_cart_item($cart_item_key);
		}
		
		$this->update_cart_session([
			'action' => 'blocks_remove_from_cart',
			'cart_item_key' => $cart_item_key,
			'product_id' => $cart_item['product_id'] ?? 0,
			'quantity' => $cart_item['quantity'] ?? 0,
			'timestamp' => time()
		], null);
		
		// Update incomplete order with current cart state (after removal)
		$result = $this->create_incomplete_order_from_current_cart();
	
	}

	/**
	 * Track WooCommerce Blocks cart updates
	 */
	public function track_blocks_cart_update($cart_item, $request) {
		
		$this->update_cart_session([
			'action' => 'blocks_cart_update',
			'product_id' => $cart_item['product_id'] ?? 0,
			'quantity' => $cart_item['quantity'] ?? 1,
			'timestamp' => time()
		], null);
		
		// Update incomplete order with new cart state
		$result = $this->create_incomplete_order_from_current_cart();
	}

	/**
	 * Create or update incomplete order from current cart state
	 */
	private function create_incomplete_order_from_current_cart() {
		$session_key = $this->get_session_key();
		if (!$session_key) {
			return;
		}
		
		$cart_data = $this->get_current_cart_data();
		$user_data = $this->get_current_user_data();
		
		// If cart is empty, mark existing incomplete order as completed (cart emptied)
		if (empty($cart_data['items'])) {
			$this->mark_incomplete_order_completed_by_session($session_key, 'cart_emptied');
			return;
		}
		
		// Extract product information from cart data
		$product_ids = [];
		$product_names = [];
		$product_links = [];
		$calculated_total = 0;
		
		foreach ($cart_data['items'] as $item) {
			// Make sure we have valid product IDs
			if (!empty($item['product_id']) && $item['product_id'] > 0) {
				$product_ids[] = intval($item['product_id']);
			}
			if (!empty($item['name'])) {
				$product_names[] = $item['name'];
			}
			if (!empty($item['permalink'])) {
				$product_links[] = $item['permalink'];
			}
			// Calculate total from actual cart items
			$calculated_total += floatval($item['total']);
		}
		
		// Use WooCommerce cart total (most reliable), fallback to calculated total
		$final_total = !empty($cart_data['total']) && $cart_data['total'] > 0 ? $cart_data['total'] : $calculated_total;
		
		// Create incomplete order data
		$incomplete_order_data = [
			'session_key' => $session_key,
			'user_id' => get_current_user_id(),
			'email' => $user_data['email'],
			'name' => $user_data['name'],
			'phone' => '',
			'address' => '',
			'product_ids' => json_encode($product_ids),
			'product_names' => json_encode($product_names),
			'product_links' => json_encode($product_links),
			'cart_data' => json_encode($cart_data),
			'total_amount' => $final_total,
			'cart_interactions' => json_encode([]),
			'is_abandonment' => false,
			'time_on_checkout' => 0,
			'ip' => isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : '',
			'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '',
		];
		
		$wpnts_db_instance = new DatabaseManager();
		$result = $wpnts_db_instance->save_incomplete_order($incomplete_order_data);
		
		
		return $result;
	}

	/**
	 * Mark incomplete order as completed by session key
	 */
	private function mark_incomplete_order_completed_by_session($session_key, $reason = 'cart_emptied') {
		global $wpdb;
		$incomplete_table = $wpdb->prefix . 'wpnts_incomplete_orders';
		
		$result = $wpdb->update(
			$incomplete_table,
			[
				'status' => 'completed',
				'updated_at' => current_time('mysql')
			],
			[
				'session_key' => $session_key,
				'status' => 'incomplete'
			],
			['%s', '%s'],
			['%s', '%s']
		);
		
		/* if ($result) {
			error_log('[WPNTS] Incomplete order marked as completed - Reason: ' . $reason . ', Session: ' . $session_key);
		} */
		
		return $result;
	}

	/**
	 * Track checkout start
	 */
	public function track_checkout_start() {
		$this->update_cart_session([
			'action' => 'checkout_started',
			'timestamp' => time()
		], null);
		
		// Create incomplete order when checkout starts
		$this->create_incomplete_order_from_current_cart();
	}

	/**
	 * Track checkout process
	 */
	public function track_checkout_process() {
		$this->update_cart_session([
			'action' => 'checkout_processing',
			'timestamp' => time()
		], null);
	}

	/**
	 * Maybe track cart state when user visits relevant pages
	 */
	public function maybe_track_cart_on_page_load() {
		// Only track on cart, checkout, or shop pages
		if (!is_cart() && !is_checkout() && !is_shop() && !is_product()) {
			return;
		}
		
		// Only track if cart has items
		if (!function_exists('WC') || !WC()->cart || WC()->cart->is_empty()) {
			return;
		}
		
		$cart_data = $this->get_current_cart_data();
		if (empty($cart_data['items'])) {
			return;
		}
		
		// Update cart session
		$this->update_cart_session([
			'action' => 'page_load_with_cart',
			'page_type' => is_cart() ? 'cart' : (is_checkout() ? 'checkout' : 'other'),
			'timestamp' => time()
		], null);
		
		// Create/update incomplete order
		$result = $this->create_incomplete_order_from_current_cart();
	}

	/**
	 * Update cart session data (public method for external access)
	 */
	public function update_cart_session_external($activity_data = [], $session_key = null) {
		return $this->update_cart_session($activity_data, $session_key);
	}

	/**
	 * Create incomplete order from current cart (public method for external access)
	 */
	public function create_incomplete_order_external() {
		return $this->create_incomplete_order_from_current_cart();
	}

	/**
	 * Update cart session data
	 */
	private function update_cart_session($activity_data = [], $session_key = null) {
		if (!$session_key) {
			$session_key = $this->get_session_key();
		}
		
		if (!$session_key) {
			return;
		}

		$cart_data = $this->get_current_cart_data();
		$user_data = $this->get_current_user_data();
		
		// Always track if we have activity data or cart items
		// Don't skip tracking - we want to capture all cart states
		
		$session_data = [
			'session_key' => $session_key,
			'user_id' => get_current_user_id(),
			'user_email' => $user_data['email'],
			'user_name' => $user_data['name'],
			'cart_contents' => json_encode($cart_data),
			'last_activity' => current_time('mysql'),
			'ip_address' => isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : '',
			'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '',
			'page_url' => isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash($_SERVER['REQUEST_URI'])) : '',
			'activity_data' => json_encode($activity_data),
			'status' => 'active',
		];

		$this->save_cart_session($session_data);
		
	}

	/**
	 * Get current cart data
	 */
	private function get_current_cart_data() {
		if (!function_exists('WC') || !WC()->cart) {
			return ['items' => [], 'total' => 0, 'item_count' => 0];
		}

		$cart = WC()->cart;
		$items = [];
		$total = 0;

		foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
			$product = $cart_item['data'];
			$product_id = $cart_item['product_id'];
			$variation_id = $cart_item['variation_id'] ?? 0;
			
			// Get the actual line total from WooCommerce
			$line_total = $cart_item['line_total'] ?? 0;
			
			// If line_total is 0, calculate it manually
			if ($line_total == 0) {
				$product_price = $product->get_price();
				$line_total = $product_price * $cart_item['quantity'];
			}
			
			$items[] = [
				'cart_item_key' => $cart_item_key,
				'product_id' => $product_id, // This should now be the actual product ID
				'variation_id' => $variation_id,
				'quantity' => $cart_item['quantity'],
				'name' => $product->get_name(),
				'price' => $product->get_price(),
				'total' => $line_total,
				'permalink' => get_permalink($product_id)
			];
			$total += $line_total;
		}

		// Get WooCommerce calculated totals (more reliable)
		$cart_total = $cart->get_total('edit'); // Get raw total without formatting
		$cart_subtotal = $cart->get_subtotal();
		$tax_total = $cart->get_total_tax();
		$shipping_total = $cart->get_shipping_total();
		$discount_total = $cart->get_discount_total();

		return [
			'items' => $items,
			'total' => floatval($cart_total), // Use WooCommerce calculated total
			'item_count' => $cart->get_cart_contents_count(),
			'subtotal' => floatval($cart_subtotal),
			'tax_total' => floatval($tax_total),
			'shipping_total' => floatval($shipping_total),
			'discount_total' => floatval($discount_total)
		];
	}

	/**
	 * Get current user data
	 */
	private function get_current_user_data() {
		$user_data = ['email' => '', 'name' => ''];
		
		// Try logged-in user first
		if (is_user_logged_in()) {
			$user = wp_get_current_user();
			$user_data['email'] = $user->user_email;
			$user_data['name'] = $user->display_name;
		}
		
		// Try WooCommerce customer data
		if (function_exists('WC') && WC()->customer) {
			$customer = WC()->customer;
			if (empty($user_data['email'])) {
				$user_data['email'] = $customer->get_billing_email();
			}
			if (empty($user_data['name'])) {
				$first_name = $customer->get_billing_first_name();
				$last_name = $customer->get_billing_last_name();
				$user_data['name'] = trim($first_name . ' ' . $last_name);
			}
		}

		return $user_data;
	}

	/**
	 * Get or create session key
	 */
	private function get_session_key() {
		// Try to get from cookie first
		if ( isset($_COOKIE['wpnts_cart_session']) ) {
			return sanitize_text_field(wp_unslash($_COOKIE['wpnts_cart_session']));
		}

		// Try to get from WooCommerce session
		if ( function_exists('WC') && WC()->session ) {
			$wc_session_key = WC()->session->get_customer_id();
			if ( $wc_session_key ) {
				$session_key = 'wpnts_wc_' . $wc_session_key;
				// Set cookie for frontend tracking
				setcookie('wpnts_cart_session', $session_key, time() + ( 30 * 24 * 60 * 60 ), '/');
				return $session_key;
			}
		}

		// Create new session key
		$session_key = 'wpnts_' . time() . '_' . wp_generate_password(8, false);
		setcookie('wpnts_cart_session', $session_key, time() + ( 30 * 24 * 60 * 60 ), '/');

		return $session_key;
	}

	/**
	 * Save cart session to database
	 */
	private function save_cart_session($session_data) {
		global $wpdb;
		
		$table_name = $wpdb->prefix . 'wpnts_cart_sessions';
		
		// Create table if it doesn't exist
		$this->create_cart_sessions_table();
		
		// Check if session exists
		$existing = $wpdb->get_row($wpdb->prepare(
			"SELECT id FROM $table_name WHERE session_key = %s",
			$session_data['session_key']
		));
		
		if ($existing) {
			// Update existing session
			$wpdb->update(
				$table_name,
				$session_data,
				['id' => $existing->id],
				['%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'],
				['%d']
			);
		} else {
			// Insert new session
			$wpdb->insert(
				$table_name,
				$session_data,
				['%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s']
			);
		}
	}

	/**
	 * Create cart sessions table
	 */
	private function create_cart_sessions_table() {
		global $wpdb;
		
		$table_name = $wpdb->prefix . 'wpnts_cart_sessions';
		
		$charset_collate = $wpdb->get_charset_collate();
		
		$sql = "CREATE TABLE IF NOT EXISTS $table_name (
			id int(11) NOT NULL AUTO_INCREMENT,
			session_key varchar(255) NOT NULL,
			user_id bigint(20) DEFAULT 0,
			user_email varchar(191) DEFAULT '',
			user_name varchar(255) DEFAULT '',
			cart_contents longtext,
			last_activity datetime DEFAULT CURRENT_TIMESTAMP,
			ip_address varchar(45) DEFAULT '',
			user_agent text,
			page_url varchar(500) DEFAULT '',
			activity_data text,
			status varchar(50) DEFAULT 'active',
			created_at datetime DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			UNIQUE KEY session_key (session_key),
			KEY user_id (user_id),
			KEY user_email (user_email),
			KEY last_activity (last_activity),
			KEY status (status)
		) $charset_collate;";
		
		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($sql);
	}

	/**
	 * Process cart abandonment (runs via cron every 5 minutes)
	 */
	public function process_cart_abandonment() {
		global $wpdb;
		
		$table_name = $wpdb->prefix . 'wpnts_cart_sessions';
		
		// Get abandonment delay from settings (use the correct field name from React)
		$schedules_int = get_option('wpnts_schedules_interval_woocommerce_settings');
		$schedules_interval = json_decode($schedules_int, true);
		$abandonment_delay = $schedules_interval['abandonment_delay_minutes'] ?? 15;
		
		// Find sessions that are abandoned (no activity for X minutes)
		$cutoff_time = date('Y-m-d H:i:s', strtotime("-{$abandonment_delay} minutes"));
		
		$abandoned_sessions = $wpdb->get_results($wpdb->prepare(
			"SELECT * FROM $table_name 
			 WHERE status = 'active' 
			 AND last_activity < %s 
			 AND cart_contents IS NOT NULL 
			 AND cart_contents != ''
			 ORDER BY last_activity ASC
			 LIMIT 50", // Process in batches to avoid performance issues
			$cutoff_time
		));
		
		foreach ($abandoned_sessions as $session) {
			$this->process_abandoned_session($session);
		}
	}

	/**
	 * Process a single abandoned session
	 */
	private function process_abandoned_session($session) {
		global $wpdb;
		
		$cart_contents = json_decode($session->cart_contents, true);
		
		// Skip if cart is empty
		if (empty($cart_contents['items'])) {
			$this->mark_session_processed($session->id);
			return;
		}
		
		// Check if user has completed an order since this session
		if ($this->user_has_recent_order($session)) {
			$this->mark_session_completed($session->id);
			return;
		}
		
		// Extract product information from cart contents
		$product_ids = [];
		$product_names = [];
		$product_links = [];
		
		foreach ($cart_contents['items'] as $item) {
			if (!empty($item['product_id'])) {
				$product_ids[] = $item['product_id'];
			}
			if (!empty($item['name'])) {
				$product_names[] = $item['name'];
			}
			if (!empty($item['permalink'])) {
				$product_links[] = $item['permalink'];
			}
		}
		
		// Create incomplete order record
		$incomplete_order_data = [
			'session_key' => $session->session_key,
			'user_id' => $session->user_id,
			'email' => $session->user_email,
			'name' => $session->user_name,
			'phone' => '',
			'address' => '',
			'product_ids' => json_encode($product_ids),
			'product_names' => json_encode($product_names),
			'product_links' => json_encode($product_links),
			'cart_data' => $session->cart_contents,
			'total_amount' => $cart_contents['total'] ?? 0,
			'cart_interactions' => $session->activity_data ?? '[]',
			'is_abandonment' => true,
			'time_on_checkout' => 0,
			'ip' => $session->ip_address,
			'user_agent' => $session->user_agent,
		];
		
		$wpnts_db_instance = new DatabaseManager();
		$incomplete_order_id = $wpnts_db_instance->save_incomplete_order($incomplete_order_data);
		
		if ($incomplete_order_id) {
			$this->mark_session_abandoned($session->id);
		} 
	}

	/**
	 * Check if user has completed an order recently
	 */
	private function user_has_recent_order($session) {
		if (empty($session->user_email) && $session->user_id == 0) {
			return false;
		}
		
		$args = [
			'limit' => 5,
			'status' => ['completed', 'processing', 'on-hold'],
			'date_created' => '>' . $session->last_activity,
		];
		
		if ($session->user_id > 0) {
			$args['customer_id'] = $session->user_id;
		} elseif (!empty($session->user_email)) {
			$args['billing_email'] = $session->user_email;
		}
		
		$orders = wc_get_orders($args);
		return !empty($orders);
	}

	/**
	 * Mark session as processed
	 */
	private function mark_session_processed($session_id) {
		global $wpdb;
		$table_name = $wpdb->prefix . 'wpnts_cart_sessions';
		
		$wpdb->update(
			$table_name,
			['status' => 'processed'],
			['id' => $session_id],
			['%s'],
			['%d']
		);
	}

	/**
	 * Mark session as completed (user made purchase)
	 */
	private function mark_session_completed($session_id) {
		global $wpdb;
		$table_name = $wpdb->prefix . 'wpnts_cart_sessions';
		
		$wpdb->update(
			$table_name,
			['status' => 'completed'],
			['id' => $session_id],
			['%s'],
			['%d']
		);
	}

	/**
	 * Mark session as abandoned
	 */
	private function mark_session_abandoned($session_id) {
		global $wpdb;
		$table_name = $wpdb->prefix . 'wpnts_cart_sessions';
		
		$wpdb->update(
			$table_name,
			['status' => 'abandoned'],
			['id' => $session_id],
			['%s'],
			['%d']
		);
	}

	/**
	 * Clear cart session when order is completed
	 */
	public function clear_cart_session($order_id) {
		$session_key = $this->get_session_key();
		if (!$session_key) {
			return;
		}
		
		global $wpdb;
		$table_name = $wpdb->prefix . 'wpnts_cart_sessions';
		
		// Mark session as completed
		$wpdb->update(
			$table_name,
			['status' => 'completed'],
			['session_key' => $session_key],
			['%s'],
			['%s']
		);
		
		// Also mark any incomplete orders for this session as completed
		$incomplete_table = $wpdb->prefix . 'wpnts_incomplete_orders';
		$wpdb->update(
			$incomplete_table,
			[
				'status' => 'completed',
				'order_id' => $order_id,
				'updated_at' => current_time('mysql')
			],
			['session_key' => $session_key],
			['%s', '%d', '%s'],
			['%s']
		);
		
		// Clear the cookie
		setcookie('wpnts_cart_session', '', time() - 3600, '/');
		
	}

	/**
	 * AJAX handler for frontend cart session tracking
	 */
	public function track_cart_session() {
		// Verify nonce
		if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpnts_checkout_tracking')) {
			wp_send_json_error(['message' => 'Invalid nonce']);
			return;
		}
		
		$session_key = isset($_POST['session_key']) ? sanitize_text_field(wp_unslash($_POST['session_key'])) : '';
		$activity_data = isset($_POST['activity']) ? wp_unslash($_POST['activity']) : []; // Sanitize later 
		
		// If activity_data is a JSON string, decode it
		if (is_string($activity_data)) {
			$activity_data = json_decode($activity_data, true);
		}
		
		// Sanitize activity data if it's an array
		if (is_array($activity_data)) {
			$activity_data = array_map('sanitize_text_field', $activity_data);
		} else {
			$activity_data = [];
		}
		
		if (empty($session_key)) {
			wp_send_json_error(['message' => 'Missing session key']);
			return;
		}
		
		// Update cart session
		$this->update_cart_session($activity_data, $session_key);
		
		// If this is a cart-related activity, also create/update incomplete order
		if (isset($activity_data['action']) && in_array($activity_data['action'], ['added_to_cart', 'removed_from_cart', 'quantity_change', 'cart_updated'])) {
			$this->create_incomplete_order_from_current_cart();
		}
		
		wp_send_json_success(['message' => 'Cart session tracked']);
	}

	/**
	 * AJAX handler for cart interaction tracking (used by enhanced checkout tracking)
	 * This bridges the gap between the two tracking systems
	 */
	public function track_cart_interaction_bridge() {
		// Verify nonce
		if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpnts_checkout_tracking')) {
			wp_send_json_error(['message' => 'Invalid nonce']);
			return;
		}
		
		$session_key = isset($_POST['session_key']) ? sanitize_text_field(wp_unslash($_POST['session_key'])) : '';
		$interaction_data = isset($_POST['interaction']) ? sanitize_text_field(wp_unslash($_POST['interaction'])) : '';
		
		if (empty($session_key) || empty($interaction_data)) {
			wp_send_json_error(['message' => 'Missing required data']);
			return;
		}
		
		$interaction = json_decode($interaction_data, true);
		if (!$interaction) {
			wp_send_json_error(['message' => 'Invalid interaction data']);
			return;
		}
		
		// Save the interaction to the interactions table (for analytics)
		$wpnts_db_instance = new DatabaseManager();
		$interaction_result = $wpnts_db_instance->save_cart_interaction($session_key, $interaction);
		
		// Also update the cart session with this activity
		$this->update_cart_session([
			'action' => 'cart_interaction',
			'interaction_type' => $interaction['type'] ?? '',
			'product' => $interaction['product'] ?? '',
			'quantity' => $interaction['quantity'] ?? 0,
			'timestamp' => time()
		], $session_key);
		
		// Create/update incomplete order with current cart state
		$this->create_incomplete_order_from_current_cart();
		
		if ($interaction_result) {
			wp_send_json_success(['message' => 'Cart interaction tracked successfully']);
		} else {
			wp_send_json_error(['message' => 'Failed to track cart interaction']);
		}
	}

	/**
	 * Manual method to capture current cart state (for testing/debugging)
	 */
	public function capture_current_cart_state() {
		
		$session_key = $this->get_session_key();
		if (!$session_key) {
			return false;
		}
		
		$cart_data = $this->get_current_cart_data();
		
		if (empty($cart_data['items'])) {
			return false;
		}
		
		$result = $this->create_incomplete_order_from_current_cart();
		
		return $result;
	}

	/**
	 * Debug method to test cart data collection (accessible via AJAX)
	 */
	public function debug_cart_data() {
		if (!current_user_can('manage_options')) {
			wp_send_json_error(['message' => 'Insufficient permissions']);
			return;
		}
		
		$cart_data = $this->get_current_cart_data();
		$session_key = $this->get_session_key();
		$user_data = $this->get_current_user_data();
		
		// Also get current settings
		$schedules_int = get_option('wpnts_schedules_interval_woocommerce_settings');
		$schedules_interval = json_decode($schedules_int, true);
		
		wp_send_json_success([
			'session_key' => $session_key,
			'cart_data' => $cart_data,
			'user_data' => $user_data,
			'cart_empty' => function_exists('WC') && WC()->cart ? WC()->cart->is_empty() : 'WC not available',
			'cart_count' => function_exists('WC') && WC()->cart ? WC()->cart->get_cart_contents_count() : 0,
			'settings' => [
				'abandonment_delay_minutes' => $schedules_interval['abandonment_delay_minutes'] ?? 15,
				'cleanup_incomplete_orders_days' => $schedules_interval['cleanup_incomplete_orders_days'] ?? 30
			]
		]);
	}

	/**
	 * Test cart tracking functionality (accessible via AJAX for testing)
	 */
	public function test_cart_tracking() {
		if (!current_user_can('manage_options')) {
			wp_send_json_error(['message' => 'Insufficient permissions']);
			return;
		}
		
		// Test creating an incomplete order from current cart
		$result = $this->create_incomplete_order_from_current_cart();
		
		// Get current cart data for debugging
		$cart_data = $this->get_current_cart_data();
		$session_key = $this->get_session_key();
		
		// Also test the abandonment processing
		$this->process_cart_abandonment();
		
		wp_send_json_success([
			'message' => 'Cart tracking test completed',
			'incomplete_order_id' => $result,
			'session_key' => $session_key,
			'cart_data' => $cart_data,
			'cart_has_items' => !empty($cart_data['items']),
			'cart_total' => $cart_data['total'],
			'product_count' => count($cart_data['items']),
			'woocommerce_available' => function_exists('WC'),
			'cart_available' => function_exists('WC') && WC()->cart ? true : false,
			'cart_empty' => function_exists('WC') && WC()->cart ? WC()->cart->is_empty() : 'N/A'
		]);
	}

	/**
	 * Manual cleanup trigger (accessible via AJAX for testing)
	 */
	public function manual_cleanup() {
		if (!current_user_can('manage_options')) {
			wp_send_json_error(['message' => 'Insufficient permissions']);
			return;
		}
		
		$result = $this->cleanup_old_sessions();
		
		wp_send_json_success([
			'message' => 'Cleanup completed successfully',
			'deleted_counts' => $result
		]);
	}

	/**
	 * Cleanup old cart sessions and WooCommerce data (runs daily)
	 */
	public function cleanup_old_sessions() {
		global $wpdb;
		
		// Get cleanup delay from settings (use the correct field name from React)
		$schedules_int = get_option('wpnts_schedules_interval_woocommerce_settings');
		$schedules_interval = json_decode($schedules_int, true);
		$cleanup_days = $schedules_interval['cleanup_incomplete_orders_days'] ?? 30;
		
		$cutoff_date = date('Y-m-d H:i:s', strtotime("-{$cleanup_days} days"));
		
		// 1. Clean up cart sessions
		$cart_sessions_table = $wpdb->prefix . 'wpnts_cart_sessions';
		$deleted_sessions = $wpdb->query($wpdb->prepare(
			"DELETE FROM $cart_sessions_table WHERE created_at < %s",
			$cutoff_date
		));
		
		// 2. Clean up incomplete orders
		$incomplete_orders_table = $wpdb->prefix . 'wpnts_incomplete_orders';
		$deleted_incomplete = $wpdb->query($wpdb->prepare(
			"DELETE FROM $incomplete_orders_table WHERE created_at < %s",
			$cutoff_date
		));
		
		// 3. Clean up cart interactions
		$cart_interactions_table = $wpdb->prefix . 'wpnts_cart_interactions';
		$deleted_interactions = $wpdb->query($wpdb->prepare(
			"DELETE FROM $cart_interactions_table WHERE created_at < %s",
			$cutoff_date
		));
		
		// 4. Clean up WooCommerce analytics data (if table exists)
		$woo_analytics_table = $wpdb->prefix . 'wpnts_woo_analytics';
		$deleted_analytics = 0;
		if ($wpdb->get_var("SHOW TABLES LIKE '$woo_analytics_table'") == $woo_analytics_table) {
			$deleted_analytics = $wpdb->query($wpdb->prepare(
				"DELETE FROM $woo_analytics_table WHERE created_at < %s",
				$cutoff_date
			));
		}
		
		// 5. Clean up any other WooCommerce tracking tables
		$tracking_tables = [
			$wpdb->prefix . 'wpnts_order_tracking',
			$wpdb->prefix . 'wpnts_product_tracking',
			$wpdb->prefix . 'wpnts_customer_tracking'
		];
		
		$total_tracking_deleted = 0;
		foreach ($tracking_tables as $table) {
			if ($wpdb->get_var("SHOW TABLES LIKE '$table'") == $table) {
				$deleted = $wpdb->query($wpdb->prepare(
					"DELETE FROM $table WHERE created_at < %s OR updated_at < %s",
					$cutoff_date,
					$cutoff_date
				));
				$total_tracking_deleted += $deleted;
			}
		}
		
		// Log cleanup results
		/* error_log('  - Cart sessions deleted: ' . $deleted_sessions);
		error_log('  - Incomplete orders deleted: ' . $deleted_incomplete);
		error_log('  - Cart interactions deleted: ' . $deleted_interactions);
		error_log('  - Analytics data deleted: ' . $deleted_analytics);
		error_log('  - Tracking data deleted: ' . $total_tracking_deleted); */
		
		// Return summary for potential use
		return [
			'cart_sessions' => $deleted_sessions,
			'incomplete_orders' => $deleted_incomplete,
			'cart_interactions' => $deleted_interactions,
			'analytics_data' => $deleted_analytics,
			'tracking_data' => $total_tracking_deleted,
			'total_deleted' => $deleted_sessions + $deleted_incomplete + $deleted_interactions + $deleted_analytics + $total_tracking_deleted
		];
	}
}