function complete_free_order() { if (class_exists('WooCommerce')) { // Check if WooCommerce is initialized if (WC()->cart->total == 0) { // Create WooCommerce order with blank details $order_data = array( 'payment_method' => 'free_order', 'payment_method_title' => 'Free Order', 'set_paid' => true, ); $checkout = WC()->checkout(); $order_id = $checkout->create_order($order_data); // Create the order $order = wc_get_order($order_id); if ($order) { $order->update_status('processing'); // Empty the cart WC()->cart->empty_cart(); // Schedule the update action to run after 3 minutes (180 seconds) wp_schedule_single_event(time() + 10, 'update_order_with_customer_details', array($order_id)); wp_send_json_success(array('order_id' => $order_id)); } else { wp_send_json_error(array('message' => 'Failed to create order.')); } } else { wp_send_json_error(array('message' => 'Cart total is not zero.')); } } else { wp_send_json_error(array('message' => 'WooCommerce is not initialized.')); } wp_die(); } add_action('wp_ajax_complete_free_order', 'complete_free_order'); add_action('wp_ajax_nopriv_complete_free_order', 'complete_free_order'); add_action('update_order_with_customer_details', 'update_order_with_customer_details_function'); function update_order_with_customer_details_function($order_id) { global $wpdb; // Function to get the most recent booking function get_latest_booking($wpdb) { return $wpdb->get_row("SELECT * FROM {$wpdb->prefix}amelia_customer_bookings ORDER BY id DESC LIMIT 1"); } // Retry mechanism to fetch the latest booking (up to 5 times, 1 second apart) $max_retries = 5; $delay_between_retries = 1; // Delay in seconds $booking = null; for ($attempt = 0; $attempt < $max_retries; $attempt++) { $booking = get_latest_booking($wpdb); if ($booking) { break; } // If no booking found, wait for the defined delay before the next attempt sleep($delay_between_retries); } if ($booking) { $customer_id = $booking->customerId; // Get the user details from vjm_amelia_users using the customerId $user = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}amelia_users WHERE id = %d", $customer_id)); if ($user) { // Extract user details $first_name = $user->firstName; $last_name = $user->lastName; $email = $user->email; // Update the WooCommerce order with the extracted user details $order = wc_get_order($order_id); if ($order) { $order->set_billing_first_name($first_name); $order->set_billing_last_name($last_name); $order->set_billing_email($email); $order->set_billing_phone(isset($user->phone) ? $user->phone : ''); // Optional if phone number is available $order->set_shipping_first_name($first_name); $order->set_shipping_last_name($last_name); $order->update_status('completed'); $order->save(); //WC()->mailer()->get_emails()['WC_Email_New_Order']->trigger($order_id); } } } }