function sync_stock_to_mobicare($product) { error_log("SYNC: Function sync_stock_to_mobicare called."); if (is_numeric($product)) { error_log("SYNC: Product is numeric, ID = $product"); $product = wc_get_product($product); } else { error_log("SYNC: Product is NOT numeric"); } if (!$product instanceof WC_Product) { error_log("SYNC: Invalid product passed to sync_stock_to_mobicare."); return; } $sku = $product->get_sku(); $stock_quantity = $product->get_stock_quantity(); error_log("SYNC: SKU is '$sku'"); error_log("SYNC: Stock quantity is '$stock_quantity'"); if (!$sku || $stock_quantity === null) { error_log("SYNC: Missing SKU or stock quantity."); return; } error_log("SYNC: Passed SKU and stock quantity check."); // WooCommerce API credentials $consumer_key = 'ck_eb68442e0852c92e1aa3920080b41811b4ecc81e'; $consumer_secret = 'cs_07ba61e921ad2e735c54738a7698c0ab37c35c05'; // Step 1: Find the product by SKU on mobicarenepal.com $url = 'https://mobicarenepal.com/wp-json/wc/v3/products?sku=' . urlencode($sku); $response = wp_remote_get($url, [ 'headers' => [ 'Authorization' => 'Basic ' . base64_encode($consumer_key . ':' . $consumer_secret), ] ]); if (is_wp_error($response)) { error_log("SYNC: Error fetching SKU $sku: " . $response->get_error_message()); return; } $body = json_decode(wp_remote_retrieve_body($response), true); if (empty($body) || !isset($body[0]['id'])) { error_log("SYNC: Product with SKU $sku not found on remote site."); return; } $remote_product_id = $body[0]['id']; $update_url = 'https://mobicarenepal.com/wp-json/wc/v3/products/' . $remote_product_id; // Step 2: Build and log the JSON body $json_body = json_encode([ 'stock_quantity' => is_numeric($stock_quantity) ? (int)$stock_quantity : 0, 'manage_stock' => true, ]); if ($json_body === false) { error_log("SYNC: JSON encoding failed: " . json_last_error_msg()); return; } error_log("SYNC: JSON body to send: " . $json_body); // Step 3: Send the PUT request to update stock $update_response = wp_remote_request($update_url, [ 'method' => 'PUT', 'headers' => [ 'Authorization' => 'Basic ' . base64_encode($consumer_key . ':' . $consumer_secret), 'Content-Type' => 'application/json', ], 'body' => $json_body, ]); if (is_wp_error($update_response)) { error_log("SYNC: Error updating product $sku: " . $update_response->get_error_message()); return; } $update_code = wp_remote_retrieve_response_code($update_response); $update_body = wp_remote_retrieve_body($update_response); error_log("SYNC: Update response code: $update_code"); error_log("SYNC: Update response body: $update_body"); if ($update_code >= 200 && $update_code < 300) { error_log("SYNC: Successfully updated SKU $sku."); } else { error_log("SYNC: Failed to update SKU $sku. HTTP $update_code. Body: $update_body"); } }