<?php
/**
 * Ajax Handler for Shop Explorer
 *
 * @package ShopExplorer
 */

namespace ShopExplorer\Ajax;

/**
 * Ajax Handler Class
 */
class SHOPEX_AjaxHandler {

	/**
	 * Initialize Ajax handlers
	 */
	public function __construct() {
		$this->init_hooks();
	}

	/**
	 * Initialize WordPress hooks
	 */
	private function init_hooks() {
		// Additional Ajax endpoints
		add_action( 'wp_ajax_shopex_create_category', [ $this, 'create_category' ] );
		add_action( 'wp_ajax_shopex_create_tag', [ $this, 'create_tag' ] );
		add_action( 'wp_ajax_shopex_create_brand', [ $this, 'create_brand' ] );

		// WooCommerce status check
		add_action( 'wp_ajax_nts_is_woocommerce_installed', [ $this, 'check_woocommerce_status' ] );

		// Settings check
		add_action( 'wp_ajax_notice_settings', [ $this, 'get_notice_settings' ] );

		// WooCommerce Analytics AJAX handler
		add_action( 'wp_ajax_wpnts_woo_analytics_data', [ $this, 'get_woo_analytics_data' ] );
		// 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' ] );
	}

	/**
	 * Check WooCommerce status
	 */
	public function check_woocommerce_status() {
		// 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.', 'shop-explorer' ),
			]);
		}

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

		// Include plugin functions if not already loaded
		if ( ! function_exists( 'is_plugin_active' ) ) {
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
		}

		// Check if WooCommerce is active
		$woocommerce_active = class_exists( 'WooCommerce' );
		$woocommerce_version = $woocommerce_active && defined( 'WC_VERSION' ) ? WC_VERSION : null;

		// Additional checks
		$plugin_active = function_exists( 'is_plugin_active' ) ? is_plugin_active( 'woocommerce/woocommerce.php' ) : false;
		$functions_exist = function_exists( 'wc_get_orders' ) && function_exists( 'wc_get_products' );

		// More comprehensive WooCommerce detection
		$is_woo_active = $woocommerce_active || $plugin_active || $functions_exist;

		wp_send_json_success([
			'status' => $is_woo_active ? 'active' : 'inactive',
			'version' => $woocommerce_version,
			'plugin_active' => $plugin_active,
			'functions_exist' => $functions_exist,
			'class_exists' => class_exists( 'WooCommerce' ),
			'message' => $is_woo_active ? 
				__( 'WooCommerce is active and ready.', 'shop-explorer' ) : 
				__( 'WooCommerce is not active.', 'shop-explorer' )
		]);
	}

	/**
	 * Get notice settings (WooCommerce settings)
	 */
	public function get_notice_settings() {
		// 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.', 'shop-explorer' ),
			]);
		}

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

		// Get WooCommerce settings
		$woo_settings = get_option( 'wpnts_schedules_interval_woocommerce_settings', [] );
		if ( is_string( $woo_settings ) ) {
			$woo_settings = json_decode( $woo_settings, true );
		}
		if ( ! is_array( $woo_settings ) ) {
			$woo_settings = [];
		}

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


	/**
	 * Create product category via Ajax
	 */
	public function create_category() {
		// Verify nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'shopex_create_category' ) ) {
			wp_send_json_error( [
				'message' => __( 'Invalid security token.', 'shop-explorer' ),
			] );
		}

		// Check user permissions
		if ( ! current_user_can( 'manage_product_terms' ) ) {
			wp_send_json_error( [
				'message' => __( 'You do not have permission to create categories.', 'shop-explorer' ),
			] );
		}

		$name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
		$slug = isset( $_POST['slug'] ) ? sanitize_title( wp_unslash( $_POST['slug'] ) ) : '';
		$description = isset( $_POST['description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['description'] ) ) : '';

		if ( empty( $name ) ) {
			wp_send_json_error( [
				'message' => __( 'Category name is required.', 'shop-explorer' ),
			] );
		}

		$args = [
			'description' => $description,
		];

		if ( ! empty( $slug ) ) {
			$args['slug'] = $slug;
		}

		$result = wp_insert_term( $name, 'product_cat', $args );

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

		$term = get_term( $result['term_id'], 'product_cat' );

		wp_send_json_success( [
			'id' => $term->term_id,
			'name' => $term->name,
			'slug' => $term->slug,
			'description' => $term->description,
		] );
	}

	/**
	 * Create product tag via Ajax
	 */
	public function create_tag() {
		// Verify nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'shopex_create_tag' ) ) {
			wp_send_json_error( [
				'message' => __( 'Invalid security token.', 'shop-explorer' ),
			] );
		}

		// Check user permissions
		if ( ! current_user_can( 'manage_product_terms' ) ) {
			wp_send_json_error( [
				'message' => __( 'You do not have permission to create tags.', 'shop-explorer' ),
			] );
		}

		$name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
		$slug = isset( $_POST['slug'] ) ? sanitize_title( wp_unslash( $_POST['slug'] ) ) : '';
		$description = isset( $_POST['description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['description'] ) ) : '';

		if ( empty( $name ) ) {
			wp_send_json_error( [
				'message' => __( 'Tag name is required.', 'shop-explorer' ),
			] );
		}

		$args = [
			'description' => $description,
		];

		if ( ! empty( $slug ) ) {
			$args['slug'] = $slug;
		}

		$result = wp_insert_term( $name, 'product_tag', $args );

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

		$term = get_term( $result['term_id'], 'product_tag' );

		wp_send_json_success( [
			'id' => $term->term_id,
			'name' => $term->name,
			'slug' => $term->slug,
			'description' => $term->description,
		] );
	}

	/**
	 * Create product brand via Ajax
	 */
	public function create_brand() {
		// Verify nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'shopex_create_brand' ) ) {
			wp_send_json_error( [
				'message' => __( 'Invalid security token.', 'shop-explorer' ),
			] );
		}

		// Check user permissions
		if ( ! current_user_can( 'manage_product_terms' ) ) {
			wp_send_json_error( [
				'message' => __( 'You do not have permission to create brands.', 'shop-explorer' ),
			] );
		}

		$name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
		$slug = isset( $_POST['slug'] ) ? sanitize_title( wp_unslash( $_POST['slug'] ) ) : '';
		$description = isset( $_POST['description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['description'] ) ) : '';

		if ( empty( $name ) ) {
			wp_send_json_error( [
				'message' => __( 'Brand name is required.', 'shop-explorer' ),
			] );
		}

		// Ensure brand taxonomy exists
		if ( ! taxonomy_exists( 'shopex_product_brand' ) ) {
			// Register the taxonomy if it doesn't exist
			$this->register_brand_taxonomy();
		}

		$args = [
			'description' => $description,
		];

		if ( ! empty( $slug ) ) {
			$args['slug'] = $slug;
		}

		$result = wp_insert_term( $name, 'shopex_product_brand', $args );

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

		$term = get_term( $result['term_id'], 'shopex_product_brand' );

		wp_send_json_success( [
			'id' => $term->term_id,
			'name' => $term->name,
			'slug' => $term->slug,
			'description' => $term->description,
		] );
	}

	/**
	 * Register brand taxonomy
	 */
	private function register_brand_taxonomy() {
		$labels = [
			'name'              => _x( 'Brands', 'taxonomy general name', 'shop-explorer' ),
			'singular_name'     => _x( 'Brand', 'taxonomy singular name', 'shop-explorer' ),
			'search_items'      => __( 'Search Brands', 'shop-explorer' ),
			'all_items'         => __( 'All Brands', 'shop-explorer' ),
			'parent_item'       => __( 'Parent Brand', 'shop-explorer' ),
			'parent_item_colon' => __( 'Parent Brand:', 'shop-explorer' ),
			'edit_item'         => __( 'Edit Brand', 'shop-explorer' ),
			'update_item'       => __( 'Update Brand', 'shop-explorer' ),
			'add_new_item'      => __( 'Add New Brand', 'shop-explorer' ),
			'new_item_name'     => __( 'New Brand Name', 'shop-explorer' ),
			'menu_name'         => __( 'Brands', 'shop-explorer' ),
		];

		$args = [
			'hierarchical'      => false,
			'labels'            => $labels,
			'show_ui'           => true,
			'show_admin_column' => true,
			'query_var'         => true,
			'rewrite'           => [ 'slug' => 'brand' ],
			'show_in_rest'      => true,
		];

		register_taxonomy( 'shopex_product_brand', [ 'product' ], $args );
	}


	/**
	 * 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 \SHOPEXPLORER\Database\DatabaseManager();
		$analytics_data = $wpnts_db_instance->get_woo_analytics_data();

		wp_send_json_success([
			'analytics_data' => $analytics_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 \SHOPEXPLORER\Database\DatabaseManager();

		$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 \SHOPEXPLORER\Database\DatabaseManager();
		$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'] ) ? 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' ),
			]);
		}

		// Save the interaction to the interactions table
		$wpnts_db_instance = new \SHOPEXPLORER\Database\DatabaseManager();
		$result = $wpnts_db_instance->save_cart_interaction( $session_key, $interaction );

		// Also trigger cart abandonment tracker to update cart session and incomplete order
		// Create a new instance to update cart session
		$cart_tracker = new \SHOPEXPLORER\Ajax\SHOPEX_CartAbandonmentTracker();
		
		// Update cart session with this interaction
		$activity_data = [
			'action' => 'cart_interaction',
			'interaction_type' => $interaction['type'] ?? '',
			'product' => $interaction['product'] ?? '',
			'quantity' => $interaction['quantity'] ?? 0,
			'timestamp' => time()
		];
		
		$cart_tracker->update_cart_session_external( $activity_data, $session_key );
		$cart_tracker->create_incomplete_order_external();

		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 \SHOPEXPLORER\Database\DatabaseManager();
		$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 \SHOPEXPLORER\Database\DatabaseManager();
		$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 \SHOPEXPLORER\Database\DatabaseManager();
		$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' ),
			]);
		}
	}

}
