<?php
/**
 * Smart Product Creator
 * Creates variable products with variations across multiple stores
 */

if (!defined('ABSPATH')) {
    exit;
}

class ShopCentral_Smart_Product_Creator {

    private static $instance = null;
    private $namespace = 'shopcentral/v1/smart-creator';

    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    /**
     * Register REST API routes
     */
    public function register_routes() {
        // Get stores
        register_rest_route($namespace = $this->namespace, '/stores', [
            'methods'  => 'GET',
            'callback' => [$this, 'get_stores'],
            'permission_callback' => [$this, 'check_permissions'],
        ]);

        // Create product
        register_rest_route($namespace, '/create', [
            'methods'  => 'POST',
            'callback' => [$this, 'create_product'],
            'permission_callback' => [$this, 'check_permissions'],
        ]);

        // Upload image
        register_rest_route($namespace, '/upload-image', [
            'methods'  => 'POST',
            'callback' => [$this, 'upload_image'],
            'permission_callback' => [$this, 'check_permissions'],
        ]);

        // Get failed jobs
        register_rest_route($namespace, '/failed-jobs', [
            'methods'  => 'GET',
            'callback' => [$this, 'get_failed_jobs'],
            'permission_callback' => [$this, 'check_permissions'],
        ]);

        // Retry failed job
        register_rest_route($namespace, '/retry/(?P<job_id>\d+)', [
            'methods'  => 'POST',
            'callback' => [$this, 'retry_job'],
            'permission_callback' => [$this, 'check_permissions'],
        ]);
    }

    /**
     * Check permissions
     */
    public function check_permissions() {
        return current_user_can('manage_woocommerce');
    }

    /**
     * Get all connected stores
     */
    public function get_stores() {
        global $wpdb;

        $stores = $wpdb->get_results(
            "SELECT id, name, url, is_current FROM {$wpdb->prefix}shopcentral_stores",
            ARRAY_A
        );

        return new WP_REST_Response([
            'stores' => $stores ?: [],
        ], 200);
    }

    /**
     * Upload image to media library
     */
    public function upload_image($request) {
        if (!class_exists('WooCommerce')) {
            return new WP_Error('no_woocommerce', 'WooCommerce is not active');
        }

        $files = $request->get_file_params();

        if (empty($files['image'])) {
            return new WP_Error('no_image', 'No image file provided', ['status' => 400]);
        }

        require_once(ABSPATH . 'wp-admin/includes/image.php');
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');

        $file = $files['image'];

        // Validate image
        $valid_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        if (!in_array($file['type'], $valid_types)) {
            return new WP_Error('invalid_type', 'Invalid image type. Allowed: JPG, PNG, GIF, WebP', ['status' => 400]);
        }

        $upload = wp_handle_upload($file, ['test_form' => false]);

        if (isset($upload['error'])) {
            return new WP_Error('upload_failed', $upload['error'], ['status' => 400]);
        }

        // Create attachment
        $attachment = [
            'post_mime_type' => $upload['type'],
            'post_title'     => sanitize_file_name($file['name']),
            'post_content'   => '',
            'post_status'    => 'inherit',
        ];

        $attachment_id = wp_insert_attachment($attachment, $upload['file']);

        if (is_wp_error($attachment_id)) {
            return new WP_Error('attachment_failed', $attachment_id->get_error_message());
        }

        // Generate metadata
        $attach_data = wp_generate_attachment_metadata($attachment_id, $upload['file']);
        wp_update_attachment_metadata($attachment_id, $attach_data);

        return new WP_REST_Response([
            'id'  => $attachment_id,
            'url' => $upload['url'],
        ], 200);
    }

    /**
     * Create product across stores (simple or variable)
     */
    public function create_product($request) {
        global $wpdb;

        $params = $request->get_json_params();

        $store_ids = array_map('intval', $params['store_ids'] ?? []);
        $product_type = sanitize_text_field($params['product_type'] ?? 'simple');
        $product_data = $params['product_data'] ?? [];
        $variations = $params['variations'] ?? [];
        $price_adjustments = $params['price_adjustments'] ?? [];

        // Simple product fields
        $regular_price = $params['regular_price'] ?? '';
        $sale_price = $params['sale_price'] ?? '';
        $stock_quantity = intval($params['stock_quantity'] ?? 0);
        $manage_stock = (bool) ($params['manage_stock'] ?? true);

        if (empty($store_ids)) {
            return new WP_Error('no_stores', 'No stores selected', ['status' => 400]);
        }

        if (empty($product_data['name'])) {
            return new WP_Error('no_name', 'Product name is required', ['status' => 400]);
        }

        // Validation based on product type
        if ($product_type === 'simple') {
            if (empty($regular_price) || floatval($regular_price) <= 0) {
                return new WP_Error('no_price', 'Regular price is required for simple products', ['status' => 400]);
            }
        } else {
            if (empty($variations)) {
                return new WP_Error('no_variations', 'At least one variation is required for variable products', ['status' => 400]);
            }
        }

        $results = [];
        $parent_id = null;

        foreach ($store_ids as $store_id) {
            $store = $wpdb->get_row(
                $wpdb->prepare("SELECT * FROM {$wpdb->prefix}shopcentral_stores WHERE id = %d", $store_id),
                ARRAY_A
            );

            if (!$store) {
                $results[] = [
                    'store_id'   => $store_id,
                    'store_name' => 'Unknown',
                    'status'     => 'error',
                    'message'    => 'Store not found',
                ];
                continue;
            }

            // Check if main store
            $main_site_url = home_url();
            $store_url = trailingslashit($store['url']);
            $is_main_site = (trailingslashit($main_site_url) === $store_url) || !empty($store['is_current']);

            // Get price adjustment for this store
            $adjustment = $price_adjustments[$store_id] ?? 0;

            if ($product_type === 'simple') {
                // Create simple product
                if ($is_main_site) {
                    $result = self::create_simple_product_local($product_data, $regular_price, $sale_price, $stock_quantity, $manage_stock, $adjustment);
                } else {
                    $result = self::create_simple_product_remote($store, $product_data, $regular_price, $sale_price, $stock_quantity, $manage_stock, $adjustment);
                }
            } else {
                // Create variable product
                if ($is_main_site) {
                    $result = self::create_variable_product_local($product_data, $variations, $adjustment, $parent_id);
                } else {
                    $result = self::create_variable_product_remote($store, $product_data, $variations, $adjustment, $parent_id);
                }
            }

            // Store parent ID for consistency across stores
            if ($result['success'] && isset($result['product_id'])) {
                if ($parent_id === null) {
                    $parent_id = $result['product_id'];
                }

                $message = $product_type === 'simple'
                    ? 'Simple product created'
                    : 'Variable product created with ' . count($variations) . ' variations';

                $results[] = [
                    'store_id'   => $store_id,
                    'store_name' => $store['name'],
                    'status'     => 'success',
                    'message'    => $message,
                    'product_id' => $result['product_id'],
                ];
            } else {
                // Log failed job
                $log_id = self::log_failed_job([
                    'store_id'     => $store_id,
                    'store_name'   => $store['name'],
                    'product_data' => $product_data,
                    'variations'   => $variations,
                    'adjustment'   => $adjustment,
                    'error'        => $result['message'],
                ]);

                $results[] = [
                    'store_id'   => $store_id,
                    'store_name' => $store['name'],
                    'status'     => 'error',
                    'message'    => $result['message'],
                    'retry_id'   => $log_id,
                ];
            }
        }

        $success_count = count(array_filter($results, fn($r) => $r['status'] === 'success'));
        $error_count = count(array_filter($results, fn($r) => $r['status'] === 'error'));

        return new WP_REST_Response([
            'message' => "Product creation completed: $success_count succeeded, $error_count failed",
            'results' => $results,
        ], 200);
    }

    /**
     * Process categories - get or create category IDs
     */
    private static function process_categories($categories) {
        $category_ids = [];
        foreach ($categories as $cat_name) {
            $cat_name = trim($cat_name);
            if (empty($cat_name)) continue;

            // Check if category exists
            $term = get_term_by('name', $cat_name, 'product_cat');
            if ($term) {
                $category_ids[] = $term->term_id;
            } else {
                // Create category
                $result = wp_insert_term($cat_name, 'product_cat');
                if (!is_wp_error($result)) {
                    $category_ids[] = $result['term_id'];
                }
            }
        }
        return $category_ids;
    }

    /**
     * Process tags - get or create tag IDs
     */
    private static function process_tags($tags) {
        $tag_ids = [];
        foreach ($tags as $tag_name) {
            $tag_name = trim($tag_name);
            if (empty($tag_name)) continue;

            // Check if tag exists
            $term = get_term_by('name', $tag_name, 'product_tag');
            if ($term) {
                $tag_ids[] = $term->term_id;
            } else {
                // Create tag
                $result = wp_insert_term($tag_name, 'product_tag');
                if (!is_wp_error($result)) {
                    $tag_ids[] = $result['term_id'];
                }
            }
        }
        return $tag_ids;
    }

    /**
     * Format categories for REST API - ensures categories exist on remote store
     * Returns array of category IDs for the remote store
     */
    private static function format_categories_for_api($categories, $store) {
        if (empty($categories)) {
            return [];
        }

        $base_url = trailingslashit($store['url']);
        $auth = base64_encode($store['consumer_key'] . ':' . $store['consumer_secret']);
        $category_ids = [];

        foreach ($categories as $cat_name) {
            $cat_name = trim($cat_name);
            if (empty($cat_name)) continue;

            // First, try to find existing category by name
            $search_response = wp_remote_get(
                $base_url . 'wp-json/wc/v3/products/categories?' . http_build_query([
                    'search' => $cat_name,
                    'per_page' => 1,
                ]),
                [
                    'headers' => [
                        'Authorization' => 'Basic ' . $auth,
                    ],
                    'timeout' => 30,
                ]
            );

            $found_id = null;
            if (!is_wp_error($search_response)) {
                $search_body = json_decode(wp_remote_retrieve_body($search_response), true);
                if (is_array($search_body) && !empty($search_body)) {
                    foreach ($search_body as $cat) {
                        if (strcasecmp($cat['name'], $cat_name) === 0) {
                            $found_id = $cat['id'];
                            break;
                        }
                    }
                }
            }

            // If found, use it
            if ($found_id) {
                $category_ids[] = ['id' => $found_id];
                continue;
            }

            // Category not found, create it
            $create_response = wp_remote_post(
                $base_url . 'wp-json/wc/v3/products/categories',
                [
                    'headers' => [
                        'Authorization' => 'Basic ' . $auth,
                        'Content-Type'  => 'application/json',
                    ],
                    'body'    => wp_json_encode(['name' => $cat_name]),
                    'timeout' => 30,
                ]
            );

            if (!is_wp_error($create_response)) {
                $create_body = json_decode(wp_remote_retrieve_body($create_response), true);
                if (isset($create_body['id'])) {
                    $category_ids[] = ['id' => $create_body['id']];
                }
            }
        }

        return $category_ids;
    }

    /**
     * Format tags for REST API
     */
    private static function format_tags_for_api($tags) {
        $formatted = [];
        foreach ($tags as $tag_name) {
            $tag_name = trim($tag_name);
            if (empty($tag_name)) continue;

            $formatted[] = ['name' => $tag_name];
        }
        return $formatted;
    }

    /**
     * Create simple product on local store
     */
    private static function create_simple_product_local($product_data, $regular_price, $sale_price, $stock_quantity, $manage_stock, $adjustment) {
        if (!class_exists('WooCommerce')) {
            return ['success' => false, 'message' => 'WooCommerce not active'];
        }

        try {
            $product = new WC_Product_Simple();
            $product->set_name($product_data['name']);
            $product->set_status($product_data['status'] ?? 'publish');
            $product->set_description($product_data['description'] ?? '');
            $product->set_short_description($product_data['short_description'] ?? '');
            $product->set_sku($product_data['sku'] ?? '');
            $product->set_catalog_visibility('visible');

            // Apply price adjustment
            $adj_regular = floatval($regular_price);
            $adj_sale = floatval($sale_price);

            if ($adjustment != 0) {
                $adj_regular = $adj_regular * (1 + $adjustment / 100);
                if ($adj_sale > 0) {
                    $adj_sale = $adj_sale * (1 + $adjustment / 100);
                }
            }

            $product->set_regular_price(number_format($adj_regular, 2, '.', ''));
            if ($adj_sale > 0) {
                $product->set_sale_price(number_format($adj_sale, 2, '.', ''));
            }

            // Set stock
            $product->set_manage_stock($manage_stock);
            $product->set_stock_quantity($stock_quantity);
            $product->set_stock_status($stock_quantity > 0 ? 'instock' : 'outofstock');

            // Set featured image
            if (!empty($product_data['featured_image_id'])) {
                $product->set_image_id(intval($product_data['featured_image_id']));
            }

            // Set categories
            if (!empty($product_data['categories'])) {
                $category_ids = self::process_categories($product_data['categories']);
                $product->set_category_ids($category_ids);
            }

            // Set tags
            if (!empty($product_data['tags'])) {
                $tag_ids = self::process_tags($product_data['tags']);
                $product->set_tag_ids($tag_ids);
            }

            $product->save();

            return ['success' => true, 'product_id' => $product->get_id()];
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    /**
     * Create simple product on remote store
     */
    private static function create_simple_product_remote($store, $product_data, $regular_price, $sale_price, $stock_quantity, $manage_stock, $adjustment) {
        $base_url = trailingslashit($store['url']);
        $auth = base64_encode($store['consumer_key'] . ':' . $store['consumer_secret']);

        // Apply price adjustment
        $adj_regular = floatval($regular_price);
        $adj_sale = floatval($sale_price);

        if ($adjustment != 0) {
            $adj_regular = $adj_regular * (1 + $adjustment / 100);
            if ($adj_sale > 0) {
                $adj_sale = $adj_sale * (1 + $adjustment / 100);
            }
        }

        $payload = [
            'name'              => $product_data['name'],
            'type'              => 'simple',
            'status'            => $product_data['status'] ?? 'publish',
            'description'       => $product_data['description'] ?? '',
            'short_description' => $product_data['short_description'] ?? '',
            'sku'               => $product_data['sku'] ?? '',
            'regular_price'     => number_format($adj_regular, 2, '.', ''),
            'sale_price'        => $adj_sale > 0 ? number_format($adj_sale, 2, '.', '') : '',
            'manage_stock'      => $manage_stock,
            'stock_quantity'    => $stock_quantity,
            'stock_status'      => $stock_quantity > 0 ? 'instock' : 'outofstock',
            'catalog_visibility'=> 'visible',
        ];

        // Add featured image
        if (!empty($product_data['featured_image_url'])) {
            $payload['images'] = [['src' => $product_data['featured_image_url']]];
        }

        // Add categories
        if (!empty($product_data['categories'])) {
            $payload['categories'] = self::format_categories_for_api($product_data['categories'], $store);
        }

        // Add tags
        if (!empty($product_data['tags'])) {
            $payload['tags'] = self::format_tags_for_api($product_data['tags']);
        }

        $response = wp_remote_post($base_url . 'wp-json/wc/v3/products', [
            'headers' => [
                'Authorization' => 'Basic ' . $auth,
                'Content-Type'  => 'application/json',
            ],
            'body'    => wp_json_encode($payload),
            'timeout' => 60,
        ]);

        if (is_wp_error($response)) {
            return ['success' => false, 'message' => $response->get_error_message()];
        }

        $status_code = wp_remote_retrieve_response_code($response);
        $body = json_decode(wp_remote_retrieve_body($response), true);

        if ($status_code < 200 || $status_code > 299) {
            $error_msg = isset($body['message']) ? $body['message'] : "HTTP Error: $status_code";
            return ['success' => false, 'message' => $error_msg];
        }

        return ['success' => true, 'product_id' => $body['id']];
    }

    /**
     * Create variable product on local store
     */
    private static function create_variable_product_local($product_data, $variations, $adjustment, $parent_id = null) {
        if (!class_exists('WooCommerce')) {
            return ['success' => false, 'message' => 'WooCommerce not active'];
        }

        try {
            // Create variable product
            $product = new WC_Product_Variable();
            $product->set_name($product_data['name']);
            $product->set_status($product_data['status'] ?? 'publish');
            $product->set_description($product_data['description'] ?? '');
            $product->set_short_description($product_data['short_description'] ?? '');
            $product->set_sku($product_data['sku'] ?? '');
            $product->set_catalog_visibility('visible');

            // Set featured image
            if (!empty($product_data['featured_image_id'])) {
                $product->set_image_id(intval($product_data['featured_image_id']));
            }

            // Set gallery images
            if (!empty($product_data['gallery_image_ids'])) {
                $product->set_gallery_image_ids(array_map('intval', $product_data['gallery_image_ids']));
            }

            // Set attributes
            $attributes = [];
            foreach ($product_data['attributes'] ?? [] as $attr_data) {
                $attribute = new WC_Product_Attribute();
                $attribute->set_name($attr_data['name']);
                $attribute->set_options($attr_data['options']);
                $attribute->set_visible(true);
                $attribute->set_variation(true);
                $attributes[] = $attribute;
            }
            $product->set_attributes($attributes);
            $product->save();

            $parent_product_id = $product->get_id();

            // Create variations using batch
            $variation_objects = [];
            foreach ($variations as $var_data) {
                $variation = new WC_Product_Variation();
                $variation->set_parent_id($parent_product_id);

                // Apply price adjustment
                $regular_price = floatval($var_data['regular_price']);
                $sale_price = floatval($var_data['sale_price'] ?? 0);

                if ($adjustment != 0) {
                    $regular_price = $regular_price * (1 + $adjustment / 100);
                    if ($sale_price > 0) {
                        $sale_price = $sale_price * (1 + $adjustment / 100);
                    }
                }

                $variation->set_regular_price(number_format($regular_price, 2, '.', ''));
                if ($sale_price > 0) {
                    $variation->set_sale_price(number_format($sale_price, 2, '.', ''));
                }
                $variation->set_sku($var_data['sku'] ?? '');
                $variation->set_manage_stock(true);
                $variation->set_stock_quantity(intval($var_data['stock_quantity'] ?? 0));
                $variation->set_stock_status('instock');

                // Set variation attributes
                $var_attributes = [];
                foreach ($var_data['attributes'] as $name => $option) {
                    $var_attributes['attribute_' . sanitize_title($name)] = $option;
                }
                $variation->set_attributes($var_attributes);
                $variation_objects[] = $variation;
            }

            // Save all variations
            foreach ($variation_objects as $variation) {
                $variation->save();
            }

            // Set categories
            if (!empty($product_data['categories'])) {
                $category_ids = self::process_categories($product_data['categories']);
                $product->set_category_ids($category_ids);
                $product->save();
            }

            // Set tags
            if (!empty($product_data['tags'])) {
                $tag_ids = self::process_tags($product_data['tags']);
                $product->set_tag_ids($tag_ids);
                $product->save();
            }

            return ['success' => true, 'product_id' => $parent_product_id];
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    /**
     * Create variable product on remote store via REST API
     */
    private static function create_variable_product_remote($store, $product_data, $variations, $adjustment, $parent_id = null) {
        $base_url = trailingslashit($store['url']);
        $auth = base64_encode($store['consumer_key'] . ':' . $store['consumer_secret']);

        // Prepare attributes
        $attributes = [];
        foreach ($product_data['attributes'] ?? [] as $attr_data) {
            $attributes[] = [
                'id'        => 0, // Local attribute
                'name'      => $attr_data['name'],
                'visible'   => true,
                'variation' => true,
                'options'   => $attr_data['options'],
            ];
        }

        // Prepare images
        $images = [];
        if (!empty($product_data['featured_image_url'])) {
            $images[] = ['src' => $product_data['featured_image_url']];
        }

        // Create parent product
        $product_payload = [
            'name'              => $product_data['name'],
            'type'              => 'variable',
            'status'            => $product_data['status'] ?? 'publish',
            'description'       => $product_data['description'] ?? '',
            'short_description' => $product_data['short_description'] ?? '',
            'sku'               => $product_data['sku'] ?? '',
            'catalog_visibility'=> 'visible',
            'attributes'        => $attributes,
            'images'            => $images,
        ];

        // Add categories
        if (!empty($product_data['categories'])) {
            $product_payload['categories'] = self::format_categories_for_api($product_data['categories'], $store);
        }

        // Add tags
        if (!empty($product_data['tags'])) {
            $product_payload['tags'] = self::format_tags_for_api($product_data['tags']);
        }

        $response = wp_remote_post($base_url . 'wp-json/wc/v3/products', [
            'headers' => [
                'Authorization' => 'Basic ' . $auth,
                'Content-Type'  => 'application/json',
            ],
            'body'    => wp_json_encode($product_payload),
            'timeout' => 60,
        ]);

        if (is_wp_error($response)) {
            return ['success' => false, 'message' => $response->get_error_message()];
        }

        $status_code = wp_remote_retrieve_response_code($response);
        $body = json_decode(wp_remote_retrieve_body($response), true);

        if ($status_code < 200 || $status_code > 299) {
            $error_msg = isset($body['message']) ? $body['message'] : "HTTP Error: $status_code";
            return ['success' => false, 'message' => $error_msg];
        }

        $remote_product_id = $body['id'];

        // Create variations using batch API
        $batch_variations = [];
        foreach ($variations as $var_data) {
            // Apply price adjustment
            $regular_price = floatval($var_data['regular_price']);
            $sale_price = floatval($var_data['sale_price'] ?? 0);

            if ($adjustment != 0) {
                $regular_price = $regular_price * (1 + $adjustment / 100);
                if ($sale_price > 0) {
                    $sale_price = $sale_price * (1 + $adjustment / 100);
                }
            }

            $var_attributes = [];
            foreach ($var_data['attributes'] as $name => $option) {
                $var_attributes[] = [
                    'name'   => $name,
                    'option' => $option,
                ];
            }

            $batch_variations[] = [
                'regular_price'   => number_format($regular_price, 2, '.', ''),
                'sale_price'      => $sale_price > 0 ? number_format($sale_price, 2, '.', '') : '',
                'sku'             => $var_data['sku'] ?? '',
                'manage_stock'    => true,
                'stock_quantity'  => intval($var_data['stock_quantity'] ?? 0),
                'stock_status'    => 'instock',
                'attributes'      => $var_attributes,
            ];
        }

        // Send batch variations in chunks of 100
        $chunks = array_chunk($batch_variations, 100);
        $success_count = 0;

        foreach ($chunks as $chunk) {
            $batch_response = wp_remote_post(
                $base_url . "wp-json/wc/v3/products/$remote_product_id/variations/batch",
                [
                    'headers' => [
                        'Authorization' => 'Basic ' . $auth,
                        'Content-Type'  => 'application/json',
                    ],
                    'body'    => wp_json_encode(['create' => $chunk]),
                    'timeout' => 120,
                ]
            );

            if (!is_wp_error($batch_response)) {
                $batch_body = json_decode(wp_remote_retrieve_body($batch_response), true);
                if (isset($batch_body['create'])) {
                    $success_count += count($batch_body['create']);
                }
            }
        }

        return [
            'success' => true,
            'product_id' => $remote_product_id,
            'variations_created' => $success_count,
        ];
    }

    /**
     * Log failed job for retry
     */
    private static function log_failed_job($data) {
        global $wpdb;

        $wpdb->insert(
            $wpdb->prefix . 'smart_creator_logs',
            [
                'store_id'     => $data['store_id'],
                'store_name'   => $data['store_name'],
                'product_data' => wp_json_encode($data['product_data']),
                'variations'   => wp_json_encode($data['variations']),
                'adjustment'   => $data['adjustment'],
                'error'        => $data['error'],
                'status'       => 'failed',
                'created_at'   => current_time('mysql'),
            ],
            ['%d', '%s', '%s', '%s', '%f', '%s', '%s', '%s']
        );

        return $wpdb->insert_id;
    }

    /**
     * Get failed jobs
     */
    public function get_failed_jobs() {
        global $wpdb;

        $jobs = $wpdb->get_results(
            "SELECT * FROM {$wpdb->prefix}smart_creator_logs WHERE status = 'failed' ORDER BY created_at DESC LIMIT 50",
            ARRAY_A
        );

        return new WP_REST_Response([
            'jobs' => $jobs ?: [],
        ], 200);
    }

    /**
     * Retry failed job
     */
    public function retry_job($request) {
        global $wpdb;

        $job_id = intval($request->get_param('job_id'));

        $job = $wpdb->get_row(
            $wpdb->prepare("SELECT * FROM {$wpdb->prefix}smart_creator_logs WHERE id = %d", $job_id),
            ARRAY_A
        );

        if (!$job) {
            return new WP_Error('not_found', 'Job not found', ['status' => 404]);
        }

        $product_data = json_decode($job['product_data'], true);
        $variations = json_decode($job['variations'], true);
        $store_id = intval($job['store_id']);

        // Get store info
        $store = $wpdb->get_row(
            $wpdb->prepare("SELECT * FROM {$wpdb->prefix}shopcentral_stores WHERE id = %d", $store_id),
            ARRAY_A
        );

        if (!$store) {
            return new WP_Error('not_found', 'Store not found', ['status' => 404]);
        }

        // Retry creation
        $main_site_url = home_url();
        $store_url = trailingslashit($store['url']);
        $is_main_site = (trailingslashit($main_site_url) === $store_url) || !empty($store['is_current']);

        if ($is_main_site) {
            $result = self::create_product_local($product_data, $variations, floatval($job['adjustment']));
        } else {
            $result = self::create_product_remote($store, $product_data, $variations, floatval($job['adjustment']));
        }

        if ($result['success']) {
            // Update log status
            $wpdb->update(
                $wpdb->prefix . 'smart_creator_logs',
                ['status' => 'completed', 'retry_at' => current_time('mysql')],
                ['id' => $job_id],
                ['%s', '%s'],
                ['%d']
            );

            return new WP_REST_Response([
                'status'  => 'success',
                'message' => 'Product created successfully on retry',
                'product_id' => $result['product_id'] ?? null,
            ], 200);
        }

        return new WP_REST_Response([
            'status'  => 'error',
            'message' => $result['message'],
        ], 200);
    }
}

// Initialize
ShopCentral_Smart_Product_Creator::instance();
