schedule_cron(); // Auto-check table exists on init (migration safety). $this->ensure_table_exists(); } /** * Automatically ensure cart is tracked when visitor visits checkout directly. */ public function maybe_track_checkout_visit(): void { if ( function_exists( 'is_checkout' ) && is_checkout() && ! is_order_received_page() ) { $this->on_cart_updated(); } } /** * Register the 15-minute cron schedule if not already present. * * @param array $schedules Registered schedules. * @return array */ public function add_cron_schedules( array $schedules ): array { if ( ! isset( $schedules['fifteen_minutes'] ) ) { $schedules['fifteen_minutes'] = array( 'interval' => 15 * MINUTE_IN_SECONDS, 'display' => __( 'Every 15 Minutes', 'ai-marketing-expert' ), ); } return $schedules; } /** * Return full table name with WordPress prefix. */ public static function get_table_name(): string { global $wpdb; return $wpdb->prefix . self::TABLE_NAME; } /** * Ensure the database table exists. */ public function ensure_table_exists(): void { global $wpdb; $table = self::get_table_name(); if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) { $this->create_tables(); } } /** * Create or update the abandoned carts database table. * * @param string $charset_collate Optional charset collate. */ public function create_tables( string $charset_collate = '' ): void { global $wpdb; if ( empty( $charset_collate ) ) { $charset_collate = $wpdb->get_charset_collate(); } if ( ! function_exists( 'dbDelta' ) ) { require_once ABSPATH . 'wp-admin/includes/upgrade.php'; } $table = self::get_table_name(); $sql = "CREATE TABLE {$table} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, cart_token varchar(64) NOT NULL, recovery_token varchar(64) NOT NULL, user_id bigint(20) unsigned NOT NULL DEFAULT 0, email varchar(191) NOT NULL DEFAULT '', customer_name varchar(191) NOT NULL DEFAULT '', phone varchar(50) NOT NULL DEFAULT '', cart_contents longtext NOT NULL, cart_total decimal(10,2) NOT NULL DEFAULT 0.00, currency varchar(10) NOT NULL DEFAULT 'USD', items_count int(11) NOT NULL DEFAULT 0, status varchar(20) NOT NULL DEFAULT 'in_progress', recovered_order_id bigint(20) unsigned NOT NULL DEFAULT 0, ip_address varchar(45) NOT NULL DEFAULT '', created_at datetime NOT NULL, updated_at datetime NOT NULL, abandoned_at datetime DEFAULT NULL, recovered_at datetime DEFAULT NULL, PRIMARY KEY (id), UNIQUE KEY recovery_token (recovery_token), KEY cart_token (cart_token), KEY email (email), KEY status_updated (status, updated_at) ) {$charset_collate};"; dbDelta( $sql ); } /** * Schedule the 15-minute inactivity detection cron event. */ private function schedule_cron(): void { if ( ! wp_next_scheduled( self::CRON_HOOK ) ) { wp_schedule_event( time() + 300, 'fifteen_minutes', self::CRON_HOOK ); } } /** * Get or generate a persistent cart session token. */ public function get_cart_token(): string { if ( is_user_logged_in() ) { return 'usr_' . get_current_user_id(); } if ( ! empty( $_COOKIE[ self::COOKIE_NAME ] ) ) { $token = sanitize_text_field( wp_unslash( $_COOKIE[ self::COOKIE_NAME ] ) ); if ( preg_match( '/^[a-zA-Z0-9_-]{20,64}$/', $token ) ) { return $token; } } $token = 'gst_' . wp_generate_password( 32, false ); if ( ! headers_sent() ) { // Cookie valid for 30 days. setcookie( self::COOKIE_NAME, $token, time() + ( 30 * DAY_IN_SECONDS ), COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true ); } $_COOKIE[ self::COOKIE_NAME ] = $token; return $token; } /** * Listener: Called whenever WooCommerce updates the cart. */ public function on_cart_updated(): void { if ( function_exists( 'wc_load_cart' ) && function_exists( 'WC' ) && ! WC()->cart ) { wc_load_cart(); } if ( ! function_exists( 'WC' ) || ! WC()->cart || is_admin() && ! wp_doing_ajax() ) { return; } $cart = WC()->cart; if ( $cart->is_empty() ) { return; } $cart_token = $this->get_cart_token(); $user_id = get_current_user_id(); $email = ''; $name = ''; $phone = ''; if ( $user_id ) { $user = wp_get_current_user(); $email = $user->user_email; $name = trim( $user->first_name . ' ' . $user->last_name ); if ( empty( $name ) ) { $name = $user->display_name; } $billing_phone = get_user_meta( $user_id, 'billing_phone', true ); if ( ! empty( $billing_phone ) ) { $phone = sanitize_text_field( $billing_phone ); } } $items = array(); $cart_content = $cart->get_cart(); foreach ( $cart_content as $cart_item_key => $values ) { /** @var \WC_Product $product */ $product = $values['data'] ?? null; if ( ! $product instanceof \WC_Product ) { continue; } $image_id = $product->get_image_id(); $image_url = $image_id ? wp_get_attachment_image_url( $image_id, 'medium' ) : ''; $items[] = array( 'key' => $cart_item_key, 'product_id' => $values['product_id'], 'variation_id' => $values['variation_id'] ?? 0, 'quantity' => $values['quantity'], 'name' => $product->get_name(), 'price' => (float) wc_get_price_to_display( $product ), 'line_total' => (float) ( $values['line_total'] ?? 0 ), 'image' => $image_url, 'permalink' => $product->get_permalink(), 'variation' => $values['variation'] ?? array(), ); } if ( empty( $items ) ) { return; } $cart_total = (float) $cart->get_total( 'edit' ); $items_count = (int) $cart->get_cart_contents_count(); $currency = get_woocommerce_currency(); $ip_address = ''; // Privacy compliance (Guideline 7): do not store visitor IP addresses. global $wpdb; $table = self::get_table_name(); // Check if active record exists for this token. $existing = $wpdb->get_row( $wpdb->prepare( 'SELECT id, email, customer_name, recovery_token, status FROM %i WHERE cart_token = %s ORDER BY id DESC LIMIT 1', $table, $cart_token ) ); $now = current_time( 'mysql', true ); if ( $existing && self::STATUS_RECOVERED !== $existing->status ) { // Maintain captured email if new scan didn't provide one. if ( empty( $email ) && ! empty( $existing->email ) ) { $email = $existing->email; } if ( empty( $name ) && ! empty( $existing->customer_name ) ) { $name = $existing->customer_name; } $wpdb->update( $table, array( 'user_id' => $user_id, 'email' => $email, 'customer_name' => $name, 'phone' => $phone, 'cart_contents' => wp_json_encode( $items ), 'cart_total' => $cart_total, 'currency' => $currency, 'items_count' => $items_count, 'status' => self::STATUS_IN_PROGRESS, 'ip_address' => $ip_address, 'updated_at' => $now, ), array( 'id' => $existing->id ), array( '%d', '%s', '%s', '%s', '%s', '%f', '%s', '%d', '%s', '%s', '%s' ), array( '%d' ) ); } else { $recovery_token = wp_generate_password( 32, false ); $wpdb->insert( $table, array( 'cart_token' => $cart_token, 'recovery_token' => $recovery_token, 'user_id' => $user_id, 'email' => $email, 'customer_name' => $name, 'phone' => $phone, 'cart_contents' => wp_json_encode( $items ), 'cart_total' => $cart_total, 'currency' => $currency, 'items_count' => $items_count, 'status' => self::STATUS_IN_PROGRESS, 'ip_address' => $ip_address, 'created_at' => $now, 'updated_at' => $now, ), array( '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%f', '%s', '%d', '%s', '%s', '%s' ) ); } } /** * Enqueue frontend capture script on WooCommerce checkout page. */ public function enqueue_checkout_scripts(): void { if ( ! function_exists( 'is_checkout' ) || ! is_checkout() || is_order_received_page() ) { return; } // Only load guest checkout recovery script if explicitly enabled in settings. $settings = get_option( 'aime_settings', array() ); if ( empty( $settings['enable_guest_cart_capture'] ) ) { return; } $data = array( 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( self::NONCE_ACTION ), 'consentLabel' => __( 'Save my cart and send me a recovery link if I do not complete checkout.', 'ai-marketing-expert' ), ); $script = " (function() { function captureGuestEmail() { var emailInput = document.getElementById('billing_email') || document.querySelector('input[name=\"billing_email\"]') || document.querySelector('input[type=\"email\"]') || document.querySelector('input[autocomplete=\"email\"]'); if (!emailInput) return; var consentId = 'aime-cart-recovery-consent'; var consentBox = document.getElementById(consentId); if (!consentBox && emailInput.parentNode) { var wrapper = document.createElement('label'); wrapper.style.cssText = 'display:flex;align-items:center;gap:6px;margin-top:6px;font-size:12px;font-weight:normal;cursor:pointer;'; consentBox = document.createElement('input'); consentBox.type = 'checkbox'; consentBox.id = consentId; wrapper.appendChild(consentBox); wrapper.appendChild(document.createTextNode('" . esc_js( $data['consentLabel'] ) . "')); emailInput.parentNode.appendChild(wrapper); } var lastSent = ''; function sendData() { if (!consentBox || !consentBox.checked) return; var email = (emailInput.value || '').trim(); if (!email || email === lastSent || !email.includes('@')) return; var firstNameInput = document.getElementById('billing_first_name') || document.querySelector('input[name=\"billing_first_name\"]') || document.querySelector('input[autocomplete=\"given-name\"]') || document.querySelector('#shipping-first_name'); var lastNameInput = document.getElementById('billing_last_name') || document.querySelector('input[name=\"billing_last_name\"]') || document.querySelector('input[autocomplete=\"family-name\"]') || document.querySelector('#shipping-last_name'); var phoneInput = document.getElementById('billing_phone') || document.querySelector('input[name=\"billing_phone\"]') || document.querySelector('input[autocomplete=\"tel\"]'); var name = ((firstNameInput ? firstNameInput.value : '') + ' ' + (lastNameInput ? lastNameInput.value : '')).trim(); var phone = phoneInput ? phoneInput.value : ''; lastSent = email; var formData = new URLSearchParams(); formData.append('action', 'aime_capture_guest_cart'); formData.append('nonce', '" . esc_js( $data['nonce'] ) . "'); formData.append('consent', '1'); formData.append('email', email); formData.append('name', name); formData.append('phone', phone); fetch('" . esc_url( $data['ajaxUrl'] ) . "', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: formData }).catch(function(err) { /* silent */ }); } if (consentBox) { consentBox.addEventListener('change', sendData); } emailInput.addEventListener('blur', sendData); emailInput.addEventListener('change', sendData); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', captureGuestEmail); } else { captureGuestEmail(); } })(); "; // Dedicated handle ensures script is always output regardless of theme or block checkout. wp_register_script( 'aime-checkout-cart-tracker', '', array(), AIME_VERSION, true ); wp_enqueue_script( 'aime-checkout-cart-tracker' ); wp_add_inline_script( 'aime-checkout-cart-tracker', $script ); } /** * AJAX Handler: Capture guest details typed on checkout before purchase. */ public function ajax_capture_guest_cart(): void { check_ajax_referer( self::NONCE_ACTION, 'nonce' ); if ( empty( $_POST['consent'] ) || '1' !== sanitize_text_field( wp_unslash( $_POST['consent'] ) ) ) { wp_send_json_error( array( 'message' => __( 'Visitor opt-in consent is required.', 'ai-marketing-expert' ) ), 403 ); } if ( function_exists( 'wc_load_cart' ) && function_exists( 'WC' ) && ! WC()->cart ) { wc_load_cart(); } $email = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : ''; if ( ! is_email( $email ) ) { wp_send_json_error( array( 'message' => __( 'Invalid email', 'ai-marketing-expert' ) ), 400 ); } $name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : ''; $phone = isset( $_POST['phone'] ) ? sanitize_text_field( wp_unslash( $_POST['phone'] ) ) : ''; $cart_token = $this->get_cart_token(); global $wpdb; $table = self::get_table_name(); $existing_id = $wpdb->get_var( $wpdb->prepare( 'SELECT id FROM %i WHERE cart_token = %s AND status = %s ORDER BY id DESC LIMIT 1', $table, $cart_token, self::STATUS_IN_PROGRESS ) ); if ( ! $existing_id ) { // In case cart row wasn't recorded yet (e.g. direct Buy Now redirect), record it now from active session. $this->on_cart_updated(); $existing_id = $wpdb->get_var( $wpdb->prepare( 'SELECT id FROM %i WHERE cart_token = %s AND status = %s ORDER BY id DESC LIMIT 1', $table, $cart_token, self::STATUS_IN_PROGRESS ) ); } if ( $existing_id ) { $wpdb->update( $table, array( 'email' => $email, 'customer_name' => $name, 'phone' => $phone, 'updated_at' => current_time( 'mysql', true ), ), array( 'id' => $existing_id ), array( '%s', '%s', '%s', '%s' ), array( '%d' ) ); } wp_send_json_success( array( 'captured' => true ) ); } /** * Background Cron: Check for carts that have been inactive and mark them as abandoned. */ public function process_abandoned_carts(): void { global $wpdb; $table = self::get_table_name(); $settings = get_option( 'aime_settings', array() ); $cutoff_minutes = isset( $settings['woo_cart_cutoff_minutes'] ) ? (int) $settings['woo_cart_cutoff_minutes'] : (int) get_option( 'aime_abandoned_cart_cutoff_minutes', self::DEFAULT_INACTIVITY_MINUTES ); $cutoff_minutes = (int) apply_filters( 'aime_abandoned_cart_cutoff_minutes', $cutoff_minutes ); if ( $cutoff_minutes < 1 ) { $cutoff_minutes = self::DEFAULT_INACTIVITY_MINUTES; } $cutoff_time = gmdate( 'Y-m-d H:i:s', time() - ( $cutoff_minutes * MINUTE_IN_SECONDS ) ); // Only carts with captured email and status = in_progress are eligible for recovery workflows. $abandoned_rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE status = %s AND email != "" AND updated_at < %s LIMIT 50', $table, self::STATUS_IN_PROGRESS, $cutoff_time ) ); if ( empty( $abandoned_rows ) ) { return; } $now = current_time( 'mysql', true ); foreach ( $abandoned_rows as $row ) { // Atomic claim: only proceed if this process transitioned status from in_progress to abandoned. $claimed = $wpdb->query( $wpdb->prepare( 'UPDATE %i SET status = %s, abandoned_at = %s WHERE id = %d AND status = %s', $table, self::STATUS_ABANDONED, $now, (int) $row->id, self::STATUS_IN_PROGRESS ) ); if ( 1 !== (int) $claimed ) { continue; } $cart_items = json_decode( (string) $row->cart_contents, true ); $cart_items = is_array( $cart_items ) ? $cart_items : array(); $product_names = array(); $total_quantity = 0; $distinct_items_count = count( $cart_items ); $single_item_links_list = array(); foreach ( $cart_items as $item ) { $p_name = (string) ( $item['name'] ?? '' ); $p_qty = max( 1, absint( $item['quantity'] ?? 1 ) ); $p_price = (float) ( $item['price'] ?? 0 ); $p_id = absint( $item['variation_id'] ?? 0 ) ?: absint( $item['product_id'] ?? 0 ); if ( ! empty( $p_name ) ) { $product_names[] = $p_name; } $total_quantity += $p_qty; if ( $p_id > 0 ) { $item_url = $this->get_recovery_url( (string) $row->recovery_token, array( 'item_id' => $p_id, 'qty' => 1 ) ); $price_text = $p_price > 0 && function_exists( 'wc_price' ) ? ' (' . wp_strip_all_tags( wc_price( $p_price ) ) . ')' : ''; $single_item_links_list[] = sprintf( '
' . esc_html__( 'Click below to restore these saved items into your cart and continue to checkout:', 'ai-marketing-expert' ) . '
'; $html .= $item_list_html; $html .= '