CartRecord = $record; $order->UserId = intval($record->user_id); // Deserialize cart contents $cart = json_decode($record->cart_contents, true); if (!is_array($cart)) $cart = []; $order->CartData = $cart; // Add line items from cart foreach ($cart as $cartItem) { $productId = isset($cartItem['product_id']) ? intval($cartItem['product_id']) : 0; $variationId = isset($cartItem['variation_id']) ? intval($cartItem['variation_id']) : 0; $quantity = isset($cartItem['quantity']) ? intval($cartItem['quantity']) : 1; $product = wc_get_product($variationId > 0 ? $variationId : $productId); if (!$product) continue; $item = new \WC_Order_Item_Product(); $item->set_product($product); $item->set_quantity($quantity); $item->set_subtotal($product->get_price() * $quantity); $item->set_total($product->get_price() * $quantity); $item->set_name($product->get_name()); $order->add_item($item); } // Set billing email if (!empty($record->email)) $order->set_billing_email($record->email); // For logged-in users, populate billing/shipping from user meta if ($order->UserId > 0) { $billingKeys = ['first_name', 'last_name', 'phone', 'address_1', 'address_2', 'city', 'state', 'postcode', 'country', 'company']; foreach ($billingKeys as $key) { $setter = "set_billing_$key"; $value = get_user_meta($order->UserId, "billing_$key", true); if (method_exists($order, $setter) && $value !== '') $order->$setter($value); } $shippingKeys = ['first_name', 'last_name', 'address_1', 'address_2', 'city', 'state', 'postcode', 'country', 'company', 'phone']; foreach ($shippingKeys as $key) { $setter = "set_shipping_$key"; $value = get_user_meta($order->UserId, "shipping_$key", true); if (method_exists($order, $setter) && $value !== '') $order->$setter($value); } } // Calculate totals from the items $order->calculate_totals(false); return $order; } }