<?php

defined('ABSPATH') || exit;

/**
 * Class ShopCentral_Product_Sync_Manager
 * Handles automatic product and inventory synchronization across multiple stores.
 */
class ShopCentral_Product_Sync_Manager
{
    private $namespace = 'shopcentral/v1';

    public function __construct()
    {
        // Hook for product updates (details like price, description, etc.)
        add_action('woocommerce_update_product', [$this, 'sync_product_details'], 20, 1);
        
        // Hook for stock changes
        add_action('woocommerce_product_set_stock', [$this, 'sync_product_stock'], 20, 1);
        add_action('woocommerce_variation_set_stock', [$this, 'sync_product_stock'], 20, 1);
        
        // Handle stock reduction during checkout
        add_action('woocommerce_reduce_order_stock', [$this, 'sync_order_stock_reduction'], 20, 1);

        // Register REST API route for incoming syncs (Bidirectional)
        add_action('rest_api_init', [$this, 'register_sync_routes']);
    }

    /**
     * Register REST API routes for bidirectional sync
     */
    public function register_sync_routes()
    {
        register_rest_route($this->namespace, '/sync/order-callback', [
            'methods' => 'POST',
            'callback' => [$this, 'handle_remote_order'],
            'permission_callback' => '__return_true', // Verification handled via source ID or IP in production
        ]);
    }

    /**
     * Handle incoming order notifications from secondary stores
     */
    public function handle_remote_order($request)
    {
        $params = $request->get_json_params();
        $source_url = $request->get_param('store_url'); // Optional tracking

        if (empty($params) || !isset($params['line_items'])) {
            return new WP_REST_Response(['status' => 'ignored'], 200);
        }

        foreach ($params['line_items'] as $item) {
            $sku = $item['sku'] ?? '';
            $qty = (int)($item['quantity'] ?? 0);

            if ($sku && $qty > 0) {
                $product_id = wc_get_product_id_by_sku($sku);
                if ($product_id) {
                    $product = wc_get_product($product_id);
                    if ($product && $product->managing_stock()) {
                        
                        // Pass the source URL through a global to prevent pushing back to the site that sent it
                        global $shopcentral_exclude_url;
                        $shopcentral_exclude_url = $source_url;
                        
                        $new_stock = wc_update_product_stock($product, $qty, 'decrease');
                        
                        // Important: Get a FRESH product object after stock update to ensure correct quantity is pushed
                        $product = wc_get_product($product->get_id());
                        
                        // Reset the global
                        $shopcentral_exclude_url = null;
                    }
                }
            }
        }

        return new WP_REST_Response(['status' => 'success'], 200);
    }

    /**
     * Check if auto-sync is enabled in settings
     */
    private function is_sync_enabled()
    {
        return get_option('shopcentral_auto_sync', 'no') === 'yes';
    }

    /**
     * Sync product details when local product is updated
     */
    public function sync_product_details($product_id)
    {
        if (!$this->is_sync_enabled()) return;

        // Avoid infinite loops if this was triggered by a sync
        if (defined('SHOPCENTRAL_SYNCING_IN_PROGRESS') && SHOPCENTRAL_SYNCING_IN_PROGRESS) {
            return;
        }

        $product = wc_get_product($product_id);
        if (!$product || !$product->get_sku()) {
            return; // SKU is required for matching across stores
        }

        // Support exclusion URL from global
        global $shopcentral_exclude_url;
        $exclude_url = !empty($shopcentral_exclude_url) ? $shopcentral_exclude_url : null;

        $this->push_to_remote_stores($product, 'all', $exclude_url);
    }

    /**
     * Sync product stock when local stock is changed
     */
    public function sync_product_stock($product, $exclude_url = null)
    {
        if (!$this->is_sync_enabled()) return;

        if (defined('SHOPCENTRAL_SYNCING_IN_PROGRESS') && SHOPCENTRAL_SYNCING_IN_PROGRESS) {
            return;
        }

        if (!is_object($product)) {
            $product = wc_get_product($product);
        }

        if (!$product || !$product->get_sku()) {
            return;
        }

        // Check if we have an exclusion URL passed via global (from remote order callback)
        global $shopcentral_exclude_url;
        if (!$exclude_url && !empty($shopcentral_exclude_url)) {
            $exclude_url = $shopcentral_exclude_url;
        }

        $this->push_to_remote_stores($product, 'stock', $exclude_url);
    }

    /**
     * Sync stock reduction when an order is placed
     */
    public function sync_order_stock_reduction($order)
    {
        if (!$this->is_sync_enabled()) return;

        if (!is_object($order)) {
            $order = wc_get_order($order);
        }
        
        if (!$order) return;

        foreach ($order->get_items() as $item) {
            $product = $item->get_product();
            if ($product && $product->get_sku()) {
                $this->push_to_remote_stores($product, 'stock');
            }
        }
    }

    /**
     * Logic to push updates to all other registered stores
     */
    private function push_to_remote_stores($product, $type = 'all', $exclude_url = null)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'shopcentral_stores';
        
        // Get all stores except the current one and the excluded one
        $current_url = home_url();
        $query = "SELECT * FROM $table WHERE url != %s";
        $args = [$current_url];

        if ($exclude_url) {
            $query .= " AND url != %s";
            $args[] = $exclude_url;
        }

        $stores = $wpdb->get_results($wpdb->prepare($query, $args));

        if (empty($stores)) {
            return;
        }

        if (!defined('SHOPCENTRAL_SYNCING_IN_PROGRESS')) {
            define('SHOPCENTRAL_SYNCING_IN_PROGRESS', true);
        }

        $sku = $product->get_sku();
        
        // Prepare payload based on sync type
        $payload = [];
        
        if ($type === 'details' || $type === 'all') {
            $payload['name'] = $product->get_name();
            $payload['regular_price'] = $product->get_regular_price();
            $payload['sale_price'] = $product->get_sale_price();
            $payload['description'] = $product->get_description();
            $payload['short_description'] = $product->get_short_description();
            
            // Images
            $image_ids = array_merge([$product->get_image_id()], $product->get_gallery_image_ids());
            $images = [];
            foreach ($image_ids as $id) {
                if ($id) {
                    $url = wp_get_attachment_url($id);
                    if ($url) $images[] = ['src' => $url];
                }
            }
            if (!empty($images)) {
                $payload['images'] = $images;
            }
        }

        if ($type === 'stock' || $type === 'all') {
            // Ensure we have fresh stock info
            if (!is_object($product)) {
                $product = wc_get_product($product);
            }
            
            $payload['manage_stock'] = $product->managing_stock();
            $payload['stock_quantity'] = $product->get_stock_quantity();
            $payload['stock_status'] = $product->get_stock_status();
            
            // Fallback for stock_quantity if it's null but managing stock
            if ($payload['stock_quantity'] === null && $payload['manage_stock']) {
                $payload['stock_quantity'] = get_post_meta($product->get_id(), '_stock', true);
            }
        }

        if (empty($payload)) {
            return;
        }

        // Use Store API's helper methods for remote requests
        if (!class_exists('ShopCentral_Store_API')) {
            require_once SHOPCENTRAL_PATH . 'includes/class-shopcentral-store-api.php';
        }
        $store_api = new ShopCentral_Store_API($this->namespace);

        foreach ($stores as $store) {
            // 1. Find product ID in remote store by SKU
            // We use the REST API of the remote store to find the product
            $remote_products = $store_api->send_remote_wc_request($store, 'wc/v3/products', 'GET', null, ['sku' => $sku]);
            
            if (!empty($remote_products) && is_array($remote_products) && isset($remote_products[0]['id'])) {
                $remote_id = $remote_products[0]['id'];
                
                // 2. Update remote product details/stock
                $res = $store_api->send_remote_wc_request($store, "wc/v3/products/$remote_id", 'PUT', $payload);
            }
        }
    }
}
