<?php
/**
 * Activity Guard – Real Time Notifier to Slack Rest Route
 *
 * This class is used to response and all rest route works
 *
 * @package WPNTS\Inc
 */

namespace WPNTS\Inc\Ajax;

use WPNTS\Inc\Database\DB;

defined('ABSPATH') || die('Hey, what are you doing here? You silly human!');
/**
 * Update used to rest route created
 *
 * @since 1.0.0
 */
class Ajax {

	/**
	 * Construct method.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		add_action( 'wp_ajax_wpnts_dashboard_data', [ $this, 'get_all' ] );
		add_action( 'wp_ajax_wpnts_woocommercewoocommerce_status', [ $this, 'woocommercewoocommerce_status' ] );
		add_action( 'wp_ajax_wpnts_debug_mode_status', [ $this, 'debug_mode_status' ] );
		add_action( 'wp_ajax_maintenannotice_mode_status', [ $this, 'maintenannotice_mode_status' ] );

		add_action( 'wp_ajax_global_settings', [ $this, 'global_settings' ] );

		add_action( 'wp_ajax_nts_is_woocommerce_installed', [ $this, 'IS_woocommerce_installed' ] );

		add_action( 'wp_ajax_nts_is_cf7_installed', [ $this, 'IS_CF7_installed' ] );

		add_action( 'wp_ajax_nts_is_formflow_installed', [ $this, 'IS_formflow_installed' ] );

		add_action( 'wp_ajax_wpnts_get_visitor_data', [ $this, 'get_visitor_data' ] );
		add_action( 'wp_ajax_wpnts_visitor_data_delete_leads', [ $this, 'visitor_data_delete' ] );
		add_action( 'wp_ajax_wpnts_visitor_data_bulk_delete_leads', [ $this, 'visitor_data_bulk_delete' ] );
		
		// Frontend visitor tracking (both logged-in and non-logged-in users)
		add_action( 'wp_ajax_wpnts_track_visitor', [ $this, 'track_visitor' ] );
		add_action( 'wp_ajax_nopriv_wpnts_track_visitor', [ $this, 'track_visitor' ] );

		add_action( 'wp_ajax_update_active_users_data', [ $this, 'update_active_users_data' ] );
		add_action('wp_ajax_get_active_logged_in_users', [ $this, 'get_active_logged_in_users' ]);

		add_action( 'wp_ajax_notice_settings', [ $this, 'notice_settings' ] );
		add_action( 'wp_ajax_activity_table', [ $this, 'activity_table' ] );

		add_action( 'wp_ajax_gswpts_notice_action', [ $this, 'manage_notices' ] );
		add_action( 'wp_ajax_nopriv_gswpts_notice_action', [ $this, 'manage_notices' ] );

		add_action( 'wp_ajax_wpnts_activity_data_resets', [ $this, 'activity_data_resets' ] );
		
		// Activity log individual and bulk delete endpoints
		add_action( 'wp_ajax_wpnts_activity_log_delete', [ $this, 'activity_log_delete' ] );
		add_action( 'wp_ajax_wpnts_activity_log_bulk_delete', [ $this, 'activity_log_bulk_delete' ] );
		
		// Telegram test endpoint
		add_action( 'wp_ajax_wpnts_test_telegram', [ $this, 'test_telegram_configuration' ] );
		
		// Maintenance leads AJAX handler
		add_action( 'wp_ajax_get_maintenance_leads', [ $this, 'get_maintenance_leads' ] );
		add_action( 'wp_ajax_delete_maintenance_lead', [ $this, 'delete_maintenance_lead' ] );
		add_action( 'wp_ajax_bulk_delete_maintenance_leads', [ $this, 'bulk_delete_maintenance_leads' ] );
		
		// WooCommerce Analytics AJAX handler
		add_action( 'wp_ajax_wpnts_woo_analytics_data', [ $this, 'get_woo_analytics_data' ] );
		
		// IP Blocking Stats AJAX handler
		add_action( 'wp_ajax_wpnts_ip_blocking_stats', [ $this, 'get_ip_blocking_stats' ] );
		
		// 7-Day Rolling Analytics AJAX handlers
		add_action( 'wp_ajax_wpnts_seven_day_rolling_analytics', [ $this, 'get_seven_day_rolling_analytics' ] );
		add_action( 'wp_ajax_wpnts_seven_day_detailed_analytics', [ $this, 'get_seven_day_detailed_analytics' ] );
		
		// Incomplete Orders AJAX handlers
		add_action( 'wp_ajax_wpnts_save_incomplete_order', [ $this, 'save_incomplete_order' ] );
		add_action( 'wp_ajax_nopriv_wpnts_save_incomplete_order', [ $this, 'save_incomplete_order' ] );
		add_action( 'wp_ajax_wpnts_get_incomplete_orders', [ $this, 'get_incomplete_orders' ] );
		add_action( 'wp_ajax_wpnts_incomplete_orders_analytics', [ $this, 'get_incomplete_orders_analytics' ] );
		
		// Cart interaction tracking
		add_action( 'wp_ajax_wpnts_track_cart_interaction', [ $this, 'track_cart_interaction' ] );
		add_action( 'wp_ajax_nopriv_wpnts_track_cart_interaction', [ $this, 'track_cart_interaction' ] );
		add_action( 'wp_ajax_wpnts_get_cart_interactions_analytics', [ $this, 'get_cart_interactions_analytics' ] );
		
		// Debug endpoints
		add_action( 'wp_ajax_wpnts_debug_cart_interactions', [ $this, 'debug_cart_interactions' ] );
		add_action( 'wp_ajax_wpnts_update_database_schema', [ $this, 'update_database_schema' ] );
		add_action( 'wp_ajax_wpnts_mark_incomplete_order_contacted', [ $this, 'mark_incomplete_order_contacted' ] );
	}

	public function get_all() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wp_rest' ) ) {
			wp_send_json_error([
				'message' => __( 'Invalid nonce.', 'notifier-to-slack' ),
			]);
		}

		$wpnts_db_instance = new DB();
		$dashboard_data = $wpnts_db_instance->get_all();

		wp_send_json_success([
			'tables'       => $dashboard_data,
		]);
	}
	public function woocommercewoocommerce_status() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wp_rest' ) ) {
			wp_send_json_error([
				'message' => __( 'Invalid nonce.', 'notifier-to-slack' ),
			]);
		}

		$woocommerce = is_plugin_active('woocommerce/woocommerce.php');
		if ( $woocommerce ) {
			wp_send_json_success([
				'status'       => $woocommerce,
			]);
		} else {
			wp_send_json_success([
				'status'       => $woocommerce,
			]);
		}
		wp_die();
	}


	public function debug_mode_status() {
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		$wpnts_db_instance = new DB();
		$debug_mode_status = $wpnts_db_instance->debug_mode_status();

		wp_send_json_success([
			'debug_data'       => $debug_mode_status,
		]);
	}

	public function maintenannotice_mode_status() {
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		$wpnts_db_instance = new DB();
		$maintenance_mode_status = $wpnts_db_instance->maintenannotice_mode_status();

		wp_send_json_success([
			'maintenance_status'       => $maintenance_mode_status,
		]);
	}

	public function global_settings() {
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		$wpnts_db_instance = new DB();
		$global_settings = $wpnts_db_instance->global_settings();

		wp_send_json_success([
			'global_settings_status'       => $global_settings,
		]);
	}

	public function notice_settings() {
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		$wpnts_db_instance = new DB();
		$notice_settings = $wpnts_db_instance->notice_settings();

		wp_send_json_success([
			'notice_settings'       => $notice_settings,
		]);
	}

	/**
	 * Activity log
	 */
	public function activity_table() {
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		$wpnts_db_instance = new DB();
		$activity_logs = $wpnts_db_instance->get_all_activity_logs();

		wp_send_json_success([
			'activity_logs'       => $activity_logs,
		]);
	}

	/**
	 * Get maintenance mode form leads
	 */
	public function get_maintenance_leads() {
		// Check nonce for security
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error([
				'message' => __('Insufficient permissions.', 'notifier-to-slack'),
			]);
		}

		// Get maintenance mode queries from options
		$maintenance_leads = get_option( 'maintenance_mode_queries', array() );

		// Format leads for response
		$formatted_leads = array();
		foreach ( $maintenance_leads as $email => $lead_data ) {
			$formatted_leads[] = array(
				'email' => $email,
				'message' => isset( $lead_data['user_message'] ) ? $lead_data['user_message'] : '',
				'ip_address' => isset( $lead_data['ip_address'] ) ? $lead_data['ip_address'] : '',
				'submitted_at' => isset( $lead_data['submitted_at'] ) ? $lead_data['submitted_at'] : '',
			);
		}

		wp_send_json_success([
			'success' => 1,
			'leads' => $formatted_leads,
		]);
	}

	/**
	 * Delete single maintenance lead
	 */
	public function delete_maintenance_lead() {
		// Check nonce for security
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error([
				'message' => __('Insufficient permissions.', 'notifier-to-slack'),
			]);
		}

		// Get email to delete
		$email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
		
		if ( empty($email) ) {
			wp_send_json_error([
				'message' => __('Invalid email provided.', 'notifier-to-slack'),
			]);
		}

		// Get current maintenance leads
		$maintenance_leads = get_option( 'maintenance_mode_queries', array() );

		// Check if lead exists
		if ( ! isset($maintenance_leads[$email]) ) {
			wp_send_json_error([
				'message' => __('Lead not found.', 'notifier-to-slack'),
			]);
		}

		// Remove the lead
		unset($maintenance_leads[$email]);

		// Update the option
		if ( update_option('maintenance_mode_queries', $maintenance_leads) ) {
			wp_send_json_success([
				'success' => 1,
				'message' => __('Lead deleted successfully.', 'notifier-to-slack'),
			]);
		} else {
			wp_send_json_error([
				'message' => __('Failed to delete lead.', 'notifier-to-slack'),
			]);
		}
	}

	/**
	 * Delete multiple maintenance leads
	 */
	public function bulk_delete_maintenance_leads() {
		// Check nonce for security
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error([
				'message' => __('Insufficient permissions.', 'notifier-to-slack'),
			]);
		}

		// Get emails to delete
		$emails = isset($_POST['emails']) ? array_map('sanitize_email', wp_unslash($_POST['emails'])) : array();
		
		if ( empty($emails) || ! is_array($emails) ) {
			wp_send_json_error([
				'message' => __('No valid emails provided.', 'notifier-to-slack'),
			]);
		}

		// Get current maintenance leads
		$maintenance_leads = get_option( 'maintenance_mode_queries', array() );
		$deleted_count = 0;

		// Remove the leads
		foreach ( $emails as $email ) {
			if ( isset($maintenance_leads[$email]) ) {
				unset($maintenance_leads[$email]);
				$deleted_count++;
			}
		}

		if ( $deleted_count === 0 ) {
			wp_send_json_error([
				'message' => __('No leads were found to delete.', 'notifier-to-slack'),
			]);
		}

		// Update the option
		if ( update_option('maintenance_mode_queries', $maintenance_leads) ) {
			wp_send_json_success([
				'success' => 1,
				'message' => sprintf(__('%d leads deleted successfully.', 'notifier-to-slack'), $deleted_count),
			]);
		} else {
			wp_send_json_error([
				'message' => __('Failed to delete leads.', 'notifier-to-slack'),
			]);
		}
	}

	/**
	 * Get WooCommerce analytics data
	 */
	public function get_woo_analytics_data() {
		// Check nonce for security
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error([
				'message' => __('Insufficient permissions.', 'notifier-to-slack'),
			]);
		}

		// Check if WooCommerce is active
		if ( ! class_exists( 'WooCommerce' ) ) {
			wp_send_json_error([
				'message' => __('WooCommerce is not active.', 'notifier-to-slack'),
			]);
		}

		$wpnts_db_instance = new DB();
		$analytics_data = $wpnts_db_instance->get_woo_analytics_data();

		wp_send_json_success([
			'analytics_data' => $analytics_data,
		]);
	}

	/**
	 * Get IP blocking statistics
	 */
	public function get_ip_blocking_stats() {
		// Check nonce for security
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error([
				'message' => __('Insufficient permissions.', 'notifier-to-slack'),
			]);
		}

		$wpnts_db_instance = new DB();
		$ip_stats = $wpnts_db_instance->get_ip_blocking_stats();

		wp_send_json_success([
			'ip_stats' => $ip_stats,
		]);
	}



	/**
	 * WooCommerce
	 */
	public function IS_woocommerce_installed() {
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		if ( is_plugin_active('woocommerce/woocommerce.php') ) {
			wp_send_json_success([
				'status'       => 'active',
			]);

		} elseif ( file_exists(WP_PLUGIN_DIR . '/woocommerce/woocommerce.php') ) {
				// 'Installed but not activated' .
				wp_send_json_success([
					'status'       => 'inactive',
				]);
		} else {
			wp_send_json_success([
				'status'       => 'notinstalled',
			]);
		}
	}


	 /**
	  * Contact Form 7
	  */
	public function IS_CF7_installed() {
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		if ( is_plugin_active('contact-form-7/wp-contact-form-7.php') ) {
			wp_send_json_success([
				'status'       => 'active',
			]);

		} elseif ( file_exists(WP_PLUGIN_DIR . '/contact-form-7/wp-contact-form-7.php') ) {
				// 'Installed but not activated' .
				wp_send_json_success([
					'status'       => 'inactive',
				]);
		} else {
			wp_send_json_success([
				'status'       => 'notinstalled',
			]);
		}
	}


	/**
	 * FormFlow
	 */
	public function IS_formflow_installed() {
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		if ( is_plugin_active('simple-form/simple-form.php') ) {
			wp_send_json_success([
				'status'       => 'active',
			]);

		} elseif ( file_exists(WP_PLUGIN_DIR . '/simple-form/simple-form.php') ) {
				// 'Installed but not activated' .
				wp_send_json_success([
					'status'       => 'inactive',
				]);
		} else {
			wp_send_json_success([
				'status'       => 'notinstalled',
			]);
		}
	}


	/**
	 * Visitor data
	 */
	public function get_visitor_data() {

		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		$wpnts_db_instance = new DB();
		$visitor_data = $wpnts_db_instance->visitor_data();

		wp_send_json_success([
			'visitor_data'       => $visitor_data,
		]);
	}


	public function visitor_data_delete() {
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __( 'Invalid nonce.', 'notifier-to-slack' ),
			]);
		}

		$id = ! empty( $_POST['id'] ) ? absint( $_POST['id'] ) : false;

		if ( $id ) {
			$wpnts_db_instance = new DB();
			$response = $wpnts_db_instance->visitor_data_delete( $id );

			if ( $response ) {
				wp_send_json_success([
					'message' => sprintf( __( 'Visitors deleted.', 'notifier-to-slack' ),
					$response ),
				]);
			}

			wp_send_json_error([
				'message' => sprintf( __( 'Invalid Visitors to delete.', 'notifier-to-slack' ) ),
			]);
		}

		wp_send_json_error([
			'message' => sprintf( __( 'Invalid Visitors to delete.', 'notifier-to-slack' ) ),
		]);
	}

	/**
	 * Truncate the activity log
	 */
	public function activity_data_resets() {
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		$confirm = ! empty( $_POST['confirm'] ) ? filter_var( wp_unslash( $_POST['confirm'] ), FILTER_VALIDATE_BOOLEAN ) : false;

		if ( $confirm === true ) {
			$wpnts_db_instance = new DB();
			$response = $wpnts_db_instance->activity_log_truncate( $confirm );

			if ( $response ) {
				wp_send_json_success([// phpcs:ignore
					'message' => __('Truncate success.', 'notifier-to-slack'),
					'status' => __('success', 'notifier-to-slack'),
				]);
			}

			wp_send_json_error([
				'message' => __('Truncate failed.', 'notifier-to-slack'),
				'status' => __('failed', 'notifier-to-slack'),
			]);
		}

		wp_send_json_error([
			'message' => __('Truncate errors.', 'notifier-to-slack'),
			'status' => __('errors', 'notifier-to-slack'),
		]);
	}

	/**
	 * Delete individual activity log entry
	 */
	public function activity_log_delete() {
		// Check nonce
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error([
				'message' => __('Insufficient permissions.', 'notifier-to-slack'),
			]);
		}

		// Get activity log ID
		$log_id = isset($_POST['log_id']) ? absint(wp_unslash($_POST['log_id'])) : 0;

		if ( ! $log_id ) {
			wp_send_json_error([
				'message' => __('Invalid log ID.', 'notifier-to-slack'),
			]);
		}

		$wpnts_db_instance = new DB();
		$result = $wpnts_db_instance->delete_activity_log($log_id);

		if ( $result ) {
			wp_send_json_success([
				'message' => __('Activity log deleted successfully.', 'notifier-to-slack'),
			]);
		} else {
			wp_send_json_error([
				'message' => __('Failed to delete activity log.', 'notifier-to-slack'),
			]);
		}
	}

	/**
	 * Delete multiple activity log entries
	 */
	public function activity_log_bulk_delete() {
		// Check nonce
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error([
				'message' => __('Insufficient permissions.', 'notifier-to-slack'),
			]);
		}

		// Get activity log IDs
		$log_ids = isset($_POST['log_ids']) && is_array($_POST['log_ids']) 
			? array_map('absint', wp_unslash($_POST['log_ids'])) 
			: [];

		// Remove any zero values
		$log_ids = array_filter($log_ids);

		if ( empty($log_ids) ) {
			wp_send_json_error([
				'message' => __('No valid log IDs provided.', 'notifier-to-slack'),
			]);
		}

		$wpnts_db_instance = new DB();
		$result = $wpnts_db_instance->bulk_delete_activity_logs($log_ids);

		if ( $result !== false ) {
			wp_send_json_success([
				'message' => sprintf(__('%d activity logs deleted successfully.', 'notifier-to-slack'), $result),
				'deleted_count' => $result,
			]);
		} else {
			wp_send_json_error([
				'message' => __('Failed to delete activity logs.', 'notifier-to-slack'),
			]);
		}
	}

	/**
	 * Delete multiple visitor data
	 */
	public function visitor_data_bulk_delete() {
		// Validate nonce
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		// Sanitize array of IDs - absint ensures positive integers only
		$post_ids_raw = isset($_POST['id']) && is_array($_POST['id']) 
			? array_map('absint', wp_unslash($_POST['id'])) 
			: [];
		
		// Remove any zero values that absint might have created from invalid input
		$post_ids_raw = array_filter($post_ids_raw);

		if ( ! empty($post_ids_raw) ) {
			$wpnts_db_instance = new DB();
			$response = $wpnts_db_instance->visitor_data_bulk_delete($post_ids_raw);
			if ( false !== $response ) {
				wp_send_json_success([
					'message' => sprintf(__('%d Visitors deleted.', 'notifier-to-slack'), $response),
				]);
			} else {
				wp_send_json_error([
					'message' => __('Failed to delete.', 'notifier-to-slack'),
				]);
			}
		} else {
			wp_send_json_error([
				'message' => __('Invalid IDs to delete.', 'notifier-to-slack'),
			]);
		}
	}


	/**
	 * Track frontend visitor
	 */
	public function track_visitor() {
		// Check if visitor tracking is enabled
		$analytics_settings = get_option('wpnts_analytics_settings', '{}');
		$settings = json_decode($analytics_settings, true);
		$visitor_tracking_enabled = isset($settings['visitors_traffic_list']) ? 
			filter_var($settings['visitors_traffic_list'], FILTER_VALIDATE_BOOLEAN) : true;
		
		if (!$visitor_tracking_enabled) {
			wp_send_json_error([
				'message' => __('Visitor tracking is disabled.', 'notifier-to-slack'),
			]);
		}

		// Verify nonce
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wpnts_visitor_tracking') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		// Validate required fields
		$session_id = isset($_POST['session_id']) ? sanitize_text_field(wp_unslash($_POST['session_id'])) : '';
		if (empty($session_id)) {
			wp_send_json_error([
				'message' => __('Session ID is required.', 'notifier-to-slack'),
			]);
		}

		// Get visitor data with proper validation
		$page_url = isset($_POST['page_url']) ? esc_url_raw(wp_unslash($_POST['page_url'])) : '';
		$referrer = isset($_POST['referrer']) ? esc_url_raw(wp_unslash($_POST['referrer'])) : '';
		$user_agent = isset($_POST['user_agent']) ? sanitize_text_field(wp_unslash($_POST['user_agent'])) : '';
		$screen_resolution = isset($_POST['screen_resolution']) ? sanitize_text_field(wp_unslash($_POST['screen_resolution'])) : '';
		$language = isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : '';
		$frontend_ip = isset($_POST['frontend_ip']) ? sanitize_text_field(wp_unslash($_POST['frontend_ip'])) : '';

		// Validate page URL
		if (empty($page_url) || !filter_var($page_url, FILTER_VALIDATE_URL)) {
			wp_send_json_error([
				'message' => __('Invalid page URL.', 'notifier-to-slack'),
			]);
		}

		// Get IP address from backend
		$backend_ip = $this->get_visitor_ip();
		
		// Use frontend IP if available and valid, otherwise use backend IP
		$ip = '';
		$ip_source = '';
		
		if (!empty($frontend_ip) && filter_var($frontend_ip, FILTER_VALIDATE_IP)) {
			$ip = $frontend_ip;
			$ip_source = 'Frontend';
		} else {
			$ip = $backend_ip;
			$ip_source = 'Backend';
			
			// If backend IP is also invalid, log more details
			if (!filter_var($backend_ip, FILTER_VALIDATE_IP)) {
				$ip_source = 'Backend (Invalid)';
			}
		}

		// Validate final IP
		if (empty($ip)) {
			wp_send_json_error([
				'message' => __('Unable to determine visitor IP address.', 'notifier-to-slack'),
			]);
		}

		// Get geolocation data (you can integrate with a geolocation API)
		$geo_data = $this->get_geolocation($ip);

		// Prepare visitor data
		$visitor_data = [
			'session_id' => $session_id,
			'ip' => $ip,
			'ip_source' => $ip_source,
			'frontend_ip' => $frontend_ip,
			'backend_ip' => $backend_ip,
			'country' => $geo_data['country'],
			'city' => $geo_data['city'],
			'page_url' => $page_url,
			'referrer' => $referrer, // Can be empty string
			'user_agent' => $user_agent,
			'screen_resolution' => $screen_resolution,
			'language' => $language,
		];

		// Save to database with error handling
		try {
			$wpnts_db_instance = new DB();
			$result = $wpnts_db_instance->save_visitor_data($visitor_data);

			if ($result) {
				wp_send_json_success([
					'message' => __('Visitor tracked successfully.', 'notifier-to-slack'),
				]);
			} else {
				wp_send_json_error([
					'message' => __('Failed to save visitor data to database.', 'notifier-to-slack'),
				]);
			}
		} catch (Exception $e) {
			error_log('Visitor tracking error: ' . $e->getMessage());
			wp_send_json_error([
				'message' => __('Database error occurred while tracking visitor.', 'notifier-to-slack'),
			]);
		}
	}

	/**
	 * Get visitor IP address with improved error handling
	 */
	private function get_visitor_ip() {
		$ip = '';
		
		// Check various IP headers in order of preference
		$ip_headers = [
			'HTTP_CLIENT_IP',
			'HTTP_X_FORWARDED_FOR',
			'HTTP_X_FORWARDED',
			'HTTP_X_CLUSTER_CLIENT_IP',
			'HTTP_FORWARDED_FOR',
			'HTTP_FORWARDED',
			'REMOTE_ADDR'
		];
		
		foreach ($ip_headers as $header) {
			if (isset($_SERVER[$header]) && !empty($_SERVER[$header])) {
				$ip = sanitize_text_field(wp_unslash($_SERVER[$header]));
				
				// Handle multiple IPs (proxy chain)
				if (strpos($ip, ',') !== false) {
					$ip_array = explode(',', $ip);
					$ip = trim($ip_array[0]);
				}
				
				// Validate IP format
				if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
					break;
				} else {
					$ip = '';
				}
			} 
			/* else {
				error_log('IP Detection - ' . $header . ': not set');
			} */
		}
		
		// Fallback to REMOTE_ADDR even if it's private/reserved (for local development)
		if (empty($ip) && isset($_SERVER['REMOTE_ADDR'])) {
			$ip = sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR']));
		}
		
		// Final validation
		if (empty($ip) || !filter_var($ip, FILTER_VALIDATE_IP)) {
			$ip = '127.0.0.1'; // Ultimate fallback
		}
		
		return $ip;
	}

	/**
	 * Get geolocation data from IP with improved error handling
	 */
	private function get_geolocation($ip) {
		// Default values
		$geo_data = [
			'country' => 'Unknown',
			'city' => 'Unknown',
		];

		// Validate IP address format
		if (empty($ip) || !filter_var($ip, FILTER_VALIDATE_IP)) {
			return $geo_data;
		}

		// Skip for local/private IPs
		if ($ip === '127.0.0.1' || $ip === '::1' || 
			strpos($ip, '192.168.') === 0 || 
			strpos($ip, '10.') === 0 || 
			strpos($ip, '172.') === 0) {
			$geo_data['country'] = 'Local';
			$geo_data['city'] = 'Local';
			return $geo_data;
		}

		// Try to get cached geolocation data
		$cache_key = 'wpnts_geo_' . md5($ip);
		$cached_data = get_transient($cache_key);
		
		if ($cached_data !== false) {
			return $cached_data;
		}

		// Attempt to get geolocation data
		$location_data = $this->fetch_geolocation_data($ip);

		// Process the location data
		if (!empty($location_data) && isset($location_data->status) && 'success' === $location_data->status) {
			error_log('Geolocation: API Success for IP ' . $ip . ' - Data: ' . json_encode($location_data));
			
			// Check if country exists and is not empty
			if (isset($location_data->country) && !empty($location_data->country) && $location_data->country !== null) {
				$geo_data['country'] = sanitize_text_field($location_data->country);
			}
			
			// Check if city exists and is not empty
			if (isset($location_data->city) && !empty($location_data->city) && $location_data->city !== null) {
				$geo_data['city'] = sanitize_text_field($location_data->city);
			}
		} else {
			error_log('Geolocation: API Failed for IP ' . $ip . ' - Response: ' . json_encode($location_data));
		}

		// Cache the result for 24 hours (even if failed, to avoid repeated API calls)
		set_transient($cache_key, $geo_data, DAY_IN_SECONDS);

		return $geo_data;
	}

	/**
	 * Fetch geolocation data from ip-api.com with improved error handling
	 *
	 * @param string $ip IP address to lookup
	 * @return object|null Location data object or null on failure
	 */
	private function fetch_geolocation_data($ip) {
		$api_url = 'http://ip-api.com/json/' . $ip;
		
		$response = wp_remote_get($api_url, [
			'timeout' => 10,
			'sslverify' => false,
			'user-agent' => 'WordPress/Activity-Guard-Plugin'
		]);

		if (is_wp_error($response)) {
			error_log('Geolocation API Error: ' . $response->get_error_message());
			return null;
		}

		$response_code = wp_remote_retrieve_response_code($response);
		if ($response_code !== 200) {
			error_log('Geolocation API HTTP Error: ' . $response_code);
			return null;
		}

		$body = wp_remote_retrieve_body($response);
		if (empty($body)) {
			error_log('Geolocation API: Empty response body');
			return null;
		}

		$location_data = json_decode($body);
		
		if (json_last_error() !== JSON_ERROR_NONE) {
			error_log('Geolocation API: JSON decode error - ' . json_last_error_msg());
			return null;
		}

		return $location_data;
	}

	/**
	 * Get active users data from options table
	 */
	public function update_active_users_data() {
		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wp_rest' ) ) {
			wp_send_json_error( [
				'message' => __( 'Invalid nonce.', 'notifier-to-slack' ),
			] );
		}

		// Get user ID
		$user_id = isset( $_POST['user_id'] ) ? absint( $_POST['user_id'] ) : 0;

		// Get active users data from options table
		$active_users_data = get_option( 'active_users_data', [] );

		// Remove user data from active users data
		if ( isset( $active_users_data[ $user_id ] ) ) {
			unset( $active_users_data[ $user_id ] );
		}

		// Update the option with active users data
		update_option( 'active_users_data', $active_users_data );

		// Send success response
		wp_send_json_success();
	}

	/**
	 * Get active users data from options table
	 */
	public function get_active_logged_in_users() {
		// Check nonce
		if ( ! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wp_rest') ) {
			wp_send_json_error([
				'message' => __('Invalid nonce.', 'notifier-to-slack'),
			]);
		}

		// Get active users data from options table
		$active_users_data = get_option('active_users_data', []);

		// If active_users_data is empty, populate it with details of the current active user.
		if ( empty($active_users_data) ) {
			$current_user = wp_get_current_user();
			$user_id = $current_user->ID;
			$user_name = $current_user->display_name;
			$activation_time = current_time('timestamp');

			$active_users_data[ $user_id ] = [
				'user_name' => $user_name,
				'activation_time' => $activation_time,
			];

			// Update the active users option
			update_option('active_users_data', $active_users_data);
		}

		// Count total active users
		$total_active_users = count($active_users_data);

		// Extract user names and login times
		$user_names = [];
		$login_time = [];
		$user_sessions = []; // Store session data
		foreach ( $active_users_data as $user_id => $user_data ) {
			$user_names[ $user_id ] = $user_data['user_name'];
			$login_time[ $user_id ] = $user_data['activation_time'];
			// Store session data if available
			if ( isset( $user_data['sessions'] ) ) {
				$user_sessions[ $user_id ] = $user_data['sessions'];
			} else {
				// If no sessions data, create empty sessions array
				$user_sessions[ $user_id ] = [];
			}
		}

		// Send the data to the frontend
		wp_send_json_success([
			'total_active_users' => $total_active_users,
			'user_names' => $user_names,
			'login_time' => $login_time,
			'user_sessions' => $user_sessions, // Include session data
		]);
	}


	/**
	 * Manage notices ajax endpoint response.
	 *
	 * @since 2.12.15
	 */
	public function manage_notices() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'notifier_notices_nonce' ) ) {
			wp_send_json_error([
				'message' => __( 'Invalid action', 'notifier-to-slack' ),
			]);
		}

		$action_type = isset( $_POST['actionType'] ) ? sanitize_text_field( wp_unslash( $_POST['actionType'] ) ) : '';
		$info_type   = isset( $_POST['info']['type'] ) ? sanitize_text_field( wp_unslash( $_POST['info']['type'] ) ) : '';
		$info_value  = isset( $_POST['info']['value'] ) ? sanitize_text_field( wp_unslash( $_POST['info']['value'] ) ) : '';

		if ( 'hide_notice' === $info_type ) {
			$this->hide_notice( $action_type );
		}

		if ( 'reminder' === $info_type ) {
			$this->set_reminder( $action_type, $info_value );
		}
	}

	/**
	 * Hide notices.
	 *
	 * @param string $action_type The action type.
	 * @since 2.12.15
	 */
	public function hide_notice( $action_type ) {
		if ( 'review_notice' === $action_type ) {
			update_option( 'NotifierReviewNotice', true );
		}

		if ( 'upgrade_notice' === $action_type ) {
			update_option( 'NotifierUpgradeNotice', true );
		}

		wp_send_json_success([
			'response_type' => 'success',
		]);
	}

	/**
	 * Set reminder to display notice.
	 *
	 * @param string $action_type The action type.
	 * @param string $info_value  The reminder value.
	 * @since 2.12.15
	 */
	public function set_reminder( $action_type, $info_value = '' ) {
		if ( 'hide_notice' === $info_value ) {
			$this->hide_notice( $action_type );
			wp_send_json_success([
				'response_type' => 'success',
			]);
		} else {

			if ( 'review_notice' === $action_type ) {
				update_option( 'DefaultNTReviewNoticeInterval', ( time() + intval( $info_value ) * 24 * 60 * 60 ) );
			}

			if ( 'upgrade_notice' === $action_type ) {
				update_option( 'DefaultNTUpgradeInterval', ( time() + intval( $info_value ) * 24 * 60 * 60 ) );
			}

			wp_send_json_success([
				'response_type' => 'success',
			]);
		}
	}

	/**
	 * Get 7-day rolling analytics data
	 */
	public function get_seven_day_rolling_analytics() {
		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wp_rest' ) ) {
			wp_send_json_error([
				'message' => __( 'Invalid nonce.', 'notifier-to-slack' ),
			]);
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error([
				'message' => __( 'Insufficient permissions.', 'notifier-to-slack' ),
			]);
		}

		// Temporarily bypass feature check for testing
		// Check if 7-day analytics is enabled
		// $security_settings = get_option( 'wpnts_webhook_site_settings', '{}' );
		// $settings = json_decode( $security_settings, true );
		// 
		// if ( ! isset( $settings['seven_day_rolling_analytics'] ) || $settings['seven_day_rolling_analytics'] !== true ) {
		// 	wp_send_json_error([
		// 		'message' => __( '7-Day Rolling Analytics is not enabled.', 'notifier-to-slack' ),
		// 	]);
		// }

		$wpnts_db_instance = new DB();
		$analytics_data = $wpnts_db_instance->get_seven_day_rolling_analytics();

		wp_send_json_success([
			'analytics' => $analytics_data,
		]);
	}

	/**
	 * Get detailed analytics for a specific day
	 */
	public function get_seven_day_detailed_analytics() {
		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wp_rest' ) ) {
			wp_send_json_error([
				'message' => __( 'Invalid nonce.', 'notifier-to-slack' ),
			]);
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error([
				'message' => __( 'Insufficient permissions.', 'notifier-to-slack' ),
			]);
		}

		// Get the date parameter
		$date = isset( $_POST['date'] ) ? sanitize_text_field( wp_unslash( $_POST['date'] ) ) : '';
		
		if ( empty( $date ) ) {
			wp_send_json_error([
				'message' => __( 'Date parameter is required.', 'notifier-to-slack' ),
			]);
		}

		$wpnts_db_instance = new DB();
		$detailed_data = $wpnts_db_instance->get_seven_day_detailed_analytics( $date );

		wp_send_json_success( $detailed_data );
	}

	/**
	 * Save incomplete order data
	 */
	public function save_incomplete_order() {

		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wpnts_checkout_tracking' ) ) {
			wp_send_json_error([
				'message' => __( 'Invalid nonce.', 'notifier-to-slack' ),
			]);
		}

		$wpnts_db_instance = new DB();

		$session_key = isset( $_POST['session_key'] ) ? sanitize_text_field( wp_unslash( $_POST['session_key'] ) ) : '';
		$email = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
		$name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
		$phone = isset( $_POST['phone'] ) ? sanitize_text_field( wp_unslash( $_POST['phone'] ) ) : '';
		$address = isset( $_POST['address'] ) ? sanitize_textarea_field( wp_unslash( $_POST['address'] ) ) : '';

		// Sanitize JSON strings - use sanitize_text_field for JSON strings
		$product_ids = isset( $_POST['product_ids'] ) ? sanitize_text_field( wp_unslash( $_POST['product_ids'] ) ) : '[]';
		$product_names = isset( $_POST['product_names'] ) ? sanitize_text_field( wp_unslash( $_POST['product_names'] ) ) : '[]';
		$product_links = isset( $_POST['product_links'] ) ? sanitize_text_field( wp_unslash( $_POST['product_links'] ) ) : '[]';
		$cart_data = isset( $_POST['cart_data'] ) ? sanitize_text_field( wp_unslash( $_POST['cart_data'] ) ) : '{}';
		$total_amount = isset( $_POST['total_amount'] ) ? floatval( wp_unslash( $_POST['total_amount'] ) ) : 0;

		// Get additional enhanced tracking data
		$cart_interactions = isset( $_POST['cart_interactions'] ) ? sanitize_text_field( wp_unslash( $_POST['cart_interactions'] ) ) : '[]';
		$is_abandonment = isset( $_POST['is_abandonment'] ) ? filter_var( wp_unslash( $_POST['is_abandonment'] ), FILTER_VALIDATE_BOOLEAN ) : false;
		$time_on_checkout = isset( $_POST['time_on_checkout'] ) ? absint( wp_unslash( $_POST['time_on_checkout'] ) ) : 0;

		// Enhanced validation - check for cart interactions and logged-in users
		$product_names_array = json_decode( $product_names, true );
		$product_ids_array = json_decode( $product_ids, true );
		$cart_interactions_array = json_decode( $cart_interactions, true );

		$has_products = ( is_array( $product_names_array ) && count( $product_names_array ) > 0 ) ||
					( is_array( $product_ids_array ) && count( $product_ids_array ) > 0 );

		$has_interactions = is_array( $cart_interactions_array ) && count( $cart_interactions_array ) > 0;

		// Get logged-in user info if available
		$current_user = wp_get_current_user();
		$user_email = '';
		$user_name = '';

		if ( $current_user && $current_user->ID > 0 ) {
			$user_email = $current_user->user_email;
			$user_name = $current_user->display_name;
		}

		// Use logged-in user data if form data is empty
		if ( empty( $email ) && ! empty( $user_email ) ) {
			$email = $user_email;
		}
		if ( empty( $name ) && ! empty( $user_name ) ) {
			$name = $user_name;
		}

		$has_contact = ! empty( $email ) || ! empty( $phone ) || ! empty( $name );
		$has_logged_user = $current_user && $current_user->ID > 0;

		if ( empty( $session_key ) || ( ! $has_contact && ! $has_products && ! $has_interactions && ! $has_logged_user ) ) {
			wp_send_json_error([
				'message' => __( 'Insufficient data provided.', 'notifier-to-slack' ),
			]);
		}

		// If we have interactions but no products in main arrays, extract from interactions
		if ( $has_interactions && ! $has_products ) {
			$interaction_products = [];
			foreach ( $cart_interactions_array as $interaction ) {
				if ( isset( $interaction['product'] ) && ! empty( $interaction['product'] ) &&
					$interaction['product'] !== 'Unknown Product' && $interaction['product'] !== 'Test Product' ) {
					$interaction_products[] = sanitize_text_field( $interaction['product'] );
				}
			}
			if ( ! empty( $interaction_products ) ) {
				$product_names = wp_json_encode( array_unique( $interaction_products ) );
			}
		}

		// Sanitize server variables
		$remote_addr = 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'] ) ) : '';

		$incomplete_order_data = [
			'session_key' => $session_key,
			'user_id' => $current_user && $current_user->ID > 0 ? $current_user->ID : 0,
			'email' => $email,
			'name' => $name,
			'phone' => $phone,
			'address' => $address,
			'product_ids' => $product_ids,
			'product_names' => $product_names,
			'product_links' => $product_links,
			'cart_data' => $cart_data,
			'total_amount' => $total_amount,
			'cart_interactions' => $cart_interactions,
			'is_abandonment' => $is_abandonment,
			'time_on_checkout' => $time_on_checkout,
			'ip' => $remote_addr,
			'user_agent' => $user_agent,
		];

		$result = $wpnts_db_instance->save_incomplete_order( $incomplete_order_data );

	
		if ( $result ) {
			wp_send_json_success([
				'id' => $result,
				'message' => __( 'Incomplete order saved successfully.', 'notifier-to-slack' ),
			]);
		} else {
			wp_send_json_error([
				'message' => __( 'Failed to save incomplete order.', 'notifier-to-slack' ),
			]);
		}
	}

	/**
	 * Get incomplete orders data
	 */
	public function get_incomplete_orders() {
		// Check nonce for security
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wp_rest' ) ) {
			wp_send_json_error([
				'message' => __( 'Invalid nonce.', 'notifier-to-slack' ),
			]);
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error([
				'message' => __( 'Insufficient permissions.', 'notifier-to-slack' ),
			]);
		}

		$wpnts_db_instance = new DB();
		$incomplete_orders = $wpnts_db_instance->get_incomplete_orders();

		wp_send_json_success([
			'incomplete_orders' => $incomplete_orders,
		]);
	}

	/**
	 * Track cart interactions (quantity changes, removals, etc.)
	 */
	public function track_cart_interaction() {
		// Check nonce for security
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wpnts_checkout_tracking' ) ) {
			wp_send_json_error([
				'message' => __( 'Invalid nonce.', 'notifier-to-slack' ),
			]);
		}

		/* $session_key = isset( $_POST['session_key'] ) ? sanitize_text_field( wp_unslash( $_POST['session_key'] ) ) : '';
		$interaction_data = isset( $_POST['interaction'] ) ? wp_unslash( $_POST['interaction'] ) : ''; */

		$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.', 'notifier-to-slack' ),
			]);
		}

		$interaction = json_decode( $interaction_data, true );
		if ( ! $interaction ) {
			wp_send_json_error([
				'message' => __( 'Invalid interaction data.', 'notifier-to-slack' ),
			]);
		}

		$wpnts_db_instance = new DB();
		$result = $wpnts_db_instance->save_cart_interaction( $session_key, $interaction );

		if ( $result ) {
			wp_send_json_success([
				'message' => __( 'Cart interaction tracked successfully.', 'notifier-to-slack' ),
			]);
		} else {
			wp_send_json_error([
				'message' => __( 'Failed to track cart interaction.', 'notifier-to-slack' ),
			]);
		}
	}

	/**
	 * Get cart interactions analytics
	 */
	public function get_cart_interactions_analytics() {
		// Check nonce for security
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wp_rest' ) ) {
			wp_send_json_error([
				'message' => __( 'Invalid nonce.', 'notifier-to-slack' ),
			]);
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error([
				'message' => __( 'Insufficient permissions.', 'notifier-to-slack' ),
			]);
		}

		$wpnts_db_instance = new DB();
		$analytics_data = $wpnts_db_instance->get_cart_interactions_analytics();

		wp_send_json_success( $analytics_data );
	}

	/**
	 * Debug cart interactions - get recent interactions for troubleshooting
	 */
	public function debug_cart_interactions() {
		// Check nonce for security
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wp_rest' ) ) {
			wp_send_json_error([
				'message' => __( 'Invalid nonce.', 'notifier-to-slack' ),
			]);
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error([
				'message' => __( 'Insufficient permissions.', 'notifier-to-slack' ),
			]);
		}

		global $wpdb;
		
		// Get recent cart interactions
		$interactions_table = $wpdb->prefix . 'wpnts_cart_interactions';
		$incomplete_table = $wpdb->prefix . 'wpnts_incomplete_orders';
		
		$recent_interactions = $wpdb->get_results(
			"SELECT * FROM $interactions_table 
			 ORDER BY created_at DESC 
			 LIMIT 20"
		);
		
		$recent_incomplete = $wpdb->get_results(
			"SELECT * FROM $incomplete_table 
			 ORDER BY created_at DESC 
			 LIMIT 10"
		);

		wp_send_json_success([
			'interactions' => $recent_interactions,
			'incomplete_orders' => $recent_incomplete,
			'tables_exist' => [
				'interactions' => $wpdb->get_var("SHOW TABLES LIKE '$interactions_table'") === $interactions_table,
				'incomplete' => $wpdb->get_var("SHOW TABLES LIKE '$incomplete_table'") === $incomplete_table,
			]
		]);
	}

	/**
	 * Manually update database schema
	 */
	public function update_database_schema() {
		// Check nonce for security
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wp_rest' ) ) {
			wp_send_json_error([
				'message' => __( 'Invalid nonce.', 'notifier-to-slack' ),
			]);
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error([
				'message' => __( 'Insufficient permissions.', 'notifier-to-slack' ),
			]);
		}

		// Trigger database update
		$db_tables = new \WPNTS\Inc\DbTables();
		$db_tables->check_and_update_tables();

		wp_send_json_success([
			'message' => 'Database schema update triggered. Check error logs for results.',
		]);
	}

	/**
	 * Get incomplete orders analytics
	 */
	public function get_incomplete_orders_analytics() {
		// Check nonce for security
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wp_rest' ) ) {
			wp_send_json_error([
				'message' => __( 'Invalid nonce.', 'notifier-to-slack' ),
			]);
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error([
				'message' => __( 'Insufficient permissions.', 'notifier-to-slack' ),
			]);
		}

		$wpnts_db_instance = new DB();
		$analytics = $wpnts_db_instance->get_incomplete_orders_analytics();

		wp_send_json_success([
			'analytics' => $analytics,
		]);
	}

	/**
	 * Mark incomplete order as contacted
	 */
	public function mark_incomplete_order_contacted() {
		// Check nonce for security
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wp_rest' ) ) {
			wp_send_json_error([
				'message' => __( 'Invalid nonce.', 'notifier-to-slack' ),
			]);
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error([
				'message' => __( 'Insufficient permissions.', 'notifier-to-slack' ),
			]);
		}

		$order_id = isset( $_POST['order_id'] ) ? intval( wp_unslash( $_POST['order_id'] ) ) : 0;

		if ( ! $order_id ) {
			wp_send_json_error([
				'message' => __( 'Invalid order ID.', 'notifier-to-slack' ),
			]);
		}

		$wpnts_db_instance = new DB();
		$result = $wpnts_db_instance->mark_incomplete_order_contacted( $order_id );

		if ( $result ) {
			wp_send_json_success([
				'message' => __( 'Order marked as contacted.', 'notifier-to-slack' ),
			]);
		} else {
			wp_send_json_error([
				'message' => __( 'Failed to update order status.', 'notifier-to-slack' ),
			]);
		}
	}

	/**
	 * Test Telegram bot configuration
	 */
	public function test_telegram_configuration() {
		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wp_rest' ) ) {
			wp_send_json_error([
				'message' => __( 'Invalid nonce.', 'notifier-to-slack' ),
			]);
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error([
				'message' => __( 'Insufficient permissions.', 'notifier-to-slack' ),
			]);
		}

		// Get bot token and chat ID from POST data
		$bot_token = isset( $_POST['bot_token'] ) ? sanitize_text_field( wp_unslash( $_POST['bot_token'] ) ) : '';
		$chat_id = isset( $_POST['chat_id'] ) ? sanitize_text_field( wp_unslash( $_POST['chat_id'] ) ) : '';
		$test_message = isset( $_POST['test_message'] ) ? sanitize_text_field( wp_unslash( $_POST['test_message'] ) ) : 'Test message from Activity Guard';

		if ( empty( $bot_token ) || empty( $chat_id ) ) {
			wp_send_json_error([
				'message' => __( 'Bot token and chat ID are required.', 'notifier-to-slack' ),
			]);
		}

		// Initialize Telegram notifier
		$telegram_notifier = new \WPNTS\Inc\TelegramNotifier();

		// Test the configuration
		$result = $telegram_notifier->test_telegram_configuration( $bot_token, $chat_id );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error([
				'message' => $result->get_error_message(),
			]);
		}

		wp_send_json_success([
			'message' => __( 'Telegram test message sent successfully!', 'notifier-to-slack' ),
			'telegram_response' => $result,
		]);
	}
}