<?php
/**
 * AUY Catalog Sync Integration
 *
 * Adds WP REST API endpoints for the AUY Utility portal to push
 * catalog data (categories + products) into WooCommerce.
 *
 * This is the WP-side receiver for the AUY wooSyncService.js.
 * It provides an alternative to the WC REST API approach by accepting
 * the full AUY catalog JSON in one atomic POST and handling the
 * WC product creation internally.
 *
 * Endpoints:
 *   POST /wp-json/m2c/v1/catalog-sync        — Full catalog push
 *   POST /wp-json/m2c/v1/catalog-sync/verify  — Verify connectivity
 *   GET  /wp-json/m2c/v1/catalog-sync/status  — Get sync status
 *
 * @package M2C_Red_Envelope
 * @since   2.17.0
 */

defined('ABSPATH') || exit;

class M2C_Catalog_Sync {

    /** @var self|null */
    private static $instance = null;

    /** Shared secret for AUY → WP authentication */
    const OPTION_SYNC_SECRET = 'm2c_catalog_sync_secret';

    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_endpoints']);
        add_action('admin_init', [$this, 'register_settings']);

        // Auto-sync cron schedule
        add_action('mre_auto_sync_catalog', [$this, 'cron_auto_sync_catalog']);
        add_action('mre_auto_sync_orders', [$this, 'cron_auto_sync_orders']);
        add_filter('cron_schedules', [$this, 'add_cron_intervals']);

        // Schedule/unschedule crons based on gateway settings
        add_action('woocommerce_update_options_payment_gateways_red_envelope', [$this, 'update_cron_schedules']);
        $this->ensure_cron_schedules();

        // Hook into new WC orders for real-time upload
        add_action('woocommerce_new_order', [$this, 'on_new_order'], 20, 1);
    }

    /**
     * Register custom cron interval
     */
    public function add_cron_intervals($schedules) {
        $schedules['every_fifteen_minutes'] = [
            'interval' => 900,
            'display'  => __('Every 15 Minutes', 'ab2bc-red-envelope'),
        ];
        return $schedules;
    }

    /**
     * Ensure cron events match current settings
     */
    public function ensure_cron_schedules() {
        $gateway = $this->get_gateway_settings();

        if (($gateway['auto_sync_catalog'] ?? 'no') === 'yes') {
            if (!wp_next_scheduled('mre_auto_sync_catalog')) {
                wp_schedule_event(time(), 'every_fifteen_minutes', 'mre_auto_sync_catalog');
            }
        } else {
            wp_clear_scheduled_hook('mre_auto_sync_catalog');
        }

        if (($gateway['auto_sync_orders'] ?? 'no') === 'yes') {
            if (!wp_next_scheduled('mre_auto_sync_orders')) {
                wp_schedule_event(time(), 'every_fifteen_minutes', 'mre_auto_sync_orders');
            }
        } else {
            wp_clear_scheduled_hook('mre_auto_sync_orders');
        }
    }

    /**
     * Called when gateway settings are saved — reschedule crons
     */
    public function update_cron_schedules() {
        // Clear all first, then re-schedule based on new settings
        wp_clear_scheduled_hook('mre_auto_sync_catalog');
        wp_clear_scheduled_hook('mre_auto_sync_orders');
        $this->ensure_cron_schedules();
    }

    /**
     * Get gateway settings
     */
    private function get_gateway_settings() {
        return get_option('woocommerce_red_envelope_settings', []);
    }

    /* ================================================================
     *  REST Endpoints
     * ================================================================ */

    public function register_endpoints() {

        // Full catalog sync (AUY → WP)
        register_rest_route('m2c/v1', '/catalog-sync', [
            'methods'             => 'POST',
            'callback'            => [$this, 'handle_catalog_sync'],
            'permission_callback' => [$this, 'verify_sync_auth'],
        ]);

        // Connectivity verification
        register_rest_route('m2c/v1', '/catalog-sync/verify', [
            'methods'             => 'POST',
            'callback'            => [$this, 'handle_verify'],
            'permission_callback' => [$this, 'verify_sync_auth'],
        ]);

        // Sync status
        register_rest_route('m2c/v1', '/catalog-sync/status', [
            'methods'             => 'GET',
            'callback'            => [$this, 'handle_status'],
            'permission_callback' => [$this, 'verify_sync_auth'],
        ]);

        // Pull orders from WooCommerce (AUY calls this)
        register_rest_route('m2c/v1', '/orders', [
            'methods'             => 'GET',
            'callback'            => [$this, 'handle_get_orders'],
            'permission_callback' => [$this, 'verify_sync_auth'],
        ]);

        // Get sync settings (auto-sync flags)
        register_rest_route('m2c/v1', '/sync-settings', [
            'methods'             => 'GET',
            'callback'            => [$this, 'handle_get_sync_settings'],
            'permission_callback' => [$this, 'verify_sync_auth'],
        ]);
    }

    /**
     * Authenticate incoming sync requests.
     * Accepts either:
     *   - WC REST API Basic Auth (consumer_key:consumer_secret)
     *   - Custom header: X-M2C-Sync-Secret matching stored option
     */
    public function verify_sync_auth($request) {
        // Method 1: WC consumer key/secret via Basic Auth
        $auth = $request->get_header('Authorization');
        if ($auth && strpos($auth, 'Basic ') === 0) {
            $decoded = base64_decode(substr($auth, 6));
            $parts = explode(':', $decoded, 2);
            if (count($parts) === 2) {
                // Verify against WC API keys
                global $wpdb;
                $key = $wpdb->get_row($wpdb->prepare(
                    "SELECT * FROM {$wpdb->prefix}woocommerce_api_keys WHERE consumer_key = %s",
                    wc_api_hash($parts[0])
                ));
                if ($key && hash_equals($key->consumer_secret, $parts[1])) {
                    return true;
                }
            }
        }

        // Method 2: Shared secret header
        $secret = $request->get_header('X-M2C-Sync-Secret');
        $stored = get_option(self::OPTION_SYNC_SECRET, '');
        if ($secret && $stored && hash_equals($stored, $secret)) {
            return true;
        }

        // Method 3: Logged-in WP admin
        if (current_user_can('manage_woocommerce')) {
            return true;
        }

        return new \WP_Error('unauthorized', 'Invalid sync credentials', ['status' => 401]);
    }

    /* ================================================================
     *  Verify Endpoint
     * ================================================================ */

    public function handle_verify($request) {
        if (!class_exists('WooCommerce')) {
            return new \WP_REST_Response([
                'verified' => false,
                'error'    => 'WooCommerce is not active',
            ], 503);
        }

        return new \WP_REST_Response([
            'verified'   => true,
            'store_name' => get_bloginfo('name'),
            'wc_version' => WC()->version,
            'wp_version' => get_bloginfo('version'),
            'currency'   => get_woocommerce_currency(),
            'plugin_ver' => defined('MRE_VERSION') ? MRE_VERSION : 'unknown',
        ], 200);
    }

    /* ================================================================
     *  Full Catalog Sync
     * ================================================================ */

    /**
     * Receive full catalog JSON from AUY and create/update WC products.
     *
     * Expected body:
     * {
     *   "catalog_id": "uuid",
     *   "merchant_wallet": "0x...",
     *   "merchant_name": "Golden Dragon",
     *   "catalog_type": "restaurant_menu",
     *   "currency": "USD",
     *   "categories": [
     *     {
     *       "id": "uuid", "name": "Appetizers",
     *       "items": [
     *         { "id": "uuid", "name": "Spring Rolls", "price": 8.99,
     *           "description": "...", "aqy_bonus": 0.5, "image_url": "...",
     *           "dietary_tags": ["vegetarian"], "available": true }
     *       ]
     *     }
     *   ]
     * }
     */
    public function handle_catalog_sync($request) {
        $body = $request->get_json_params();

        if (empty($body['catalog_id']) || empty($body['categories'])) {
            return new \WP_REST_Response([
                'success' => false,
                'error'   => 'catalog_id and categories are required',
            ], 400);
        }

        $stats = [
            'products_created' => 0,
            'products_updated' => 0,
            'errors'           => 0,
            'items'            => [],
        ];

        $catalog_id      = sanitize_text_field($body['catalog_id']);
        $merchant_wallet = sanitize_text_field($body['merchant_wallet'] ?? '');
        $currency        = sanitize_text_field($body['currency'] ?? get_woocommerce_currency());

        foreach ($body['categories'] as $category) {
            // Get or create WC product category
            $wc_cat_id = $this->get_or_create_category($category['name']);

            foreach ($category['items'] ?? [] as $item) {
                try {
                    $result = $this->sync_product($item, $wc_cat_id, $catalog_id, $merchant_wallet, $currency);
                    if ($result['created']) {
                        $stats['products_created']++;
                    } else {
                        $stats['products_updated']++;
                    }
                    $stats['items'][] = [
                        'auy_item_id'    => $item['id'] ?? '',
                        'woo_product_id' => $result['product_id'],
                        'status'         => 'ok',
                    ];
                } catch (\Exception $e) {
                    $stats['errors']++;
                    $stats['items'][] = [
                        'auy_item_id' => $item['id'] ?? '',
                        'error'       => $e->getMessage(),
                        'status'      => 'error',
                    ];
                }
            }
        }

        // Store last sync metadata
        update_option('m2c_last_catalog_sync', [
            'catalog_id' => $catalog_id,
            'timestamp'  => current_time('mysql'),
            'stats'      => $stats,
        ]);

        return new \WP_REST_Response([
            'success' => true,
            'stats'   => $stats,
        ], 200);
    }

    /* ================================================================
     *  Status Endpoint
     * ================================================================ */

    public function handle_status($request) {
        $last_sync = get_option('m2c_last_catalog_sync', null);

        return new \WP_REST_Response([
            'success'   => true,
            'last_sync' => $last_sync,
        ], 200);
    }

    /* ================================================================
     *  Internal: Category Management
     * ================================================================ */

    private function get_or_create_category($name) {
        $name = sanitize_text_field($name);

        // Search existing
        $existing = get_term_by('name', $name, 'product_cat');
        if ($existing) {
            return $existing->term_id;
        }

        // Create
        $result = wp_insert_term($name, 'product_cat');
        if (is_wp_error($result)) {
            // Term might exist with different casing — try slug
            $slug = sanitize_title($name);
            $by_slug = get_term_by('slug', $slug, 'product_cat');
            return $by_slug ? $by_slug->term_id : 0;
        }

        return $result['term_id'];
    }

    /* ================================================================
     *  Internal: Product Sync
     * ================================================================ */

    /**
     * Create or update a WC product from AUY catalog item data.
     */
    private function sync_product($item, $wc_cat_id, $catalog_id, $merchant_wallet, $currency) {
        $auy_item_id = sanitize_text_field($item['id'] ?? '');
        $created = false;

        // Check if product already exists by AUY item ID meta
        $existing_id = $this->find_product_by_auy_id($auy_item_id);

        if ($existing_id) {
            $product = wc_get_product($existing_id);
            if (!$product) {
                $existing_id = null; // Product was deleted in WC
            }
        }

        if (!$existing_id) {
            $product = new \WC_Product_Simple();
            $created = true;
        }

        // Set product fields
        $product->set_name(sanitize_text_field($item['name'] ?? 'Unnamed Item'));
        $product->set_regular_price(floatval($item['price'] ?? 0));
        $product->set_status(!empty($item['available']) ? 'publish' : 'draft');
        $product->set_catalog_visibility('visible');
        $product->set_manage_stock(false);

        // Description
        if (!empty($item['description'])) {
            $product->set_description(wp_kses_post($item['description']));
            $product->set_short_description(wp_trim_words($item['description'], 20));
        }

        // Featured (popular items)
        if (!empty($item['popular'])) {
            $product->set_featured(true);
        }

        // Category
        if ($wc_cat_id > 0) {
            $product->set_category_ids([$wc_cat_id]);
        }

        // Save product first to get ID
        $product_id = $product->save();

        // Set AUY tracking meta
        update_post_meta($product_id, '_auy_catalog_id', $catalog_id);
        update_post_meta($product_id, '_auy_item_id', $auy_item_id);
        update_post_meta($product_id, '_auy_merchant_wallet', $merchant_wallet);

        // Set AQY bonus meta for the WP plugin bonus system
        $aqy_bonus = floatval($item['aqy_bonus'] ?? 0);
        update_post_meta($product_id, M2C_Product_Bonus::META_BONUS_ENABLED, $aqy_bonus > 0 ? 'yes' : 'no');
        update_post_meta($product_id, M2C_Product_Bonus::META_BONUS_AMOUNT, $aqy_bonus);

        // i18n meta
        if (!empty($item['name_i18n'])) {
            update_post_meta($product_id, '_auy_name_i18n', wp_json_encode($item['name_i18n']));
        }
        if (!empty($item['description_i18n'])) {
            update_post_meta($product_id, '_auy_description_i18n', wp_json_encode($item['description_i18n']));
        }

        // Dietary tags as product attribute
        if (!empty($item['dietary_tags']) && is_array($item['dietary_tags'])) {
            $this->set_product_attribute($product_id, 'Dietary', $item['dietary_tags']);
        }

        // Allergens as product attribute
        if (!empty($item['allergens']) && is_array($item['allergens'])) {
            $this->set_product_attribute($product_id, 'Allergens', $item['allergens']);
        }

        // Image (sideload from URL)
        if (!empty($item['image_url'])) {
            $this->maybe_set_product_image($product_id, $item['image_url'], $item['name'] ?? 'product');
        }

        return [
            'product_id' => $product_id,
            'created'    => $created,
        ];
    }

    /**
     * Find WC product by AUY item ID stored in meta
     */
    private function find_product_by_auy_id($auy_item_id) {
        if (empty($auy_item_id)) return null;

        global $wpdb;
        $product_id = $wpdb->get_var($wpdb->prepare(
            "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_auy_item_id' AND meta_value = %s LIMIT 1",
            $auy_item_id
        ));

        return $product_id ? intval($product_id) : null;
    }

    /**
     * Set a WC product attribute (e.g., Dietary: vegetarian, halal)
     */
    private function set_product_attribute($product_id, $attr_name, $values) {
        $product = wc_get_product($product_id);
        if (!$product) return;

        $attributes = $product->get_attributes();

        $attribute = new \WC_Product_Attribute();
        $attribute->set_name($attr_name);
        $attribute->set_options($values);
        $attribute->set_visible(true);
        $attribute->set_variation(false);

        $attr_key = sanitize_title($attr_name);
        $attributes[$attr_key] = $attribute;

        $product->set_attributes($attributes);
        $product->save();
    }

    /**
     * Sideload image from URL and set as product featured image
     */
    private function maybe_set_product_image($product_id, $image_url, $alt_text) {
        // Skip if product already has this image
        $current = get_post_meta($product_id, '_auy_image_url', true);
        if ($current === $image_url) return;

        // Download and attach
        require_once ABSPATH . 'wp-admin/includes/media.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';

        $tmp = download_url($image_url);
        if (is_wp_error($tmp)) return;

        $file_array = [
            'name'     => sanitize_file_name(basename(parse_url($image_url, PHP_URL_PATH)) ?: 'product.jpg'),
            'tmp_name' => $tmp,
        ];

        $attach_id = media_handle_sideload($file_array, $product_id, $alt_text);

        if (!is_wp_error($attach_id)) {
            set_post_thumbnail($product_id, $attach_id);
            update_post_meta($product_id, '_auy_image_url', $image_url);
        }

        // Clean up temp file if it still exists
        if (file_exists($tmp)) {
            @unlink($tmp);
        }
    }

    /* ================================================================
     *  Orders Endpoint — Pull WC orders for AUY
     * ================================================================ */

    /**
     * GET /wp-json/m2c/v1/orders
     *
     * Returns WooCommerce orders in a format AUY can consume.
     * Query params:
     *   ?since=2026-04-01T00:00:00Z  — only orders modified after this date
     *   ?status=processing,completed — filter by order status
     *   ?per_page=50&page=1
     */
    public function handle_get_orders($request) {
        if (!function_exists('wc_get_orders')) {
            return new \WP_REST_Response(['success' => false, 'error' => 'WooCommerce not active'], 503);
        }

        $args = [
            'limit'   => min(intval($request->get_param('per_page') ?: 50), 100),
            'page'    => max(intval($request->get_param('page') ?: 1), 1),
            'orderby' => 'date',
            'order'   => 'DESC',
        ];

        // Filter by status
        $status = $request->get_param('status');
        if ($status) {
            $args['status'] = array_map('sanitize_text_field', explode(',', $status));
        }

        // Filter by modified date
        $since = $request->get_param('since');
        if ($since) {
            $args['date_modified'] = '>=' . sanitize_text_field($since);
        }

        $orders = wc_get_orders($args);
        $result = [];

        foreach ($orders as $order) {
            $result[] = $this->map_order_for_auy($order);
        }

        return new \WP_REST_Response([
            'success' => true,
            'orders'  => $result,
            'total'   => count($result),
            'page'    => $args['page'],
        ], 200);
    }

    /**
     * Map a WC_Order to the AUY order format
     */
    private function map_order_for_auy($order) {
        $items = [];
        foreach ($order->get_items() as $item) {
            $product    = $item->get_product();
            $product_id = $item->get_product_id();
            $items[] = [
                'name'          => $item->get_name(),
                'quantity'      => $item->get_quantity(),
                'price'         => floatval($item->get_total()) / max($item->get_quantity(), 1),
                'total'         => floatval($item->get_total()),
                'sku'           => $product ? $product->get_sku() : '',
                'woo_product_id'=> $product_id,
                'auy_item_id'   => get_post_meta($product_id, '_auy_item_id', true) ?: null,
                'auy_catalog_id'=> get_post_meta($product_id, '_auy_catalog_id', true) ?: null,
            ];
        }

        return [
            'woo_order_id'    => $order->get_id(),
            'order_number'    => $order->get_order_number(),
            'status'          => $order->get_status(),
            'currency'        => $order->get_currency(),
            'total'           => floatval($order->get_total()),
            'subtotal'        => floatval($order->get_subtotal()),
            'tax_total'       => floatval($order->get_total_tax()),
            'shipping_total'  => floatval($order->get_shipping_total()),
            'discount_total'  => floatval($order->get_discount_total()),
            'payment_method'  => $order->get_payment_method(),
            'payment_title'   => $order->get_payment_method_title(),
            'date_created'    => $order->get_date_created() ? $order->get_date_created()->format('c') : null,
            'date_modified'   => $order->get_date_modified() ? $order->get_date_modified()->format('c') : null,
            'customer_email'  => $order->get_billing_email(),
            'customer_name'   => trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name()),
            'billing_address' => [
                'address_1' => $order->get_billing_address_1(),
                'address_2' => $order->get_billing_address_2(),
                'city'      => $order->get_billing_city(),
                'state'     => $order->get_billing_state(),
                'postcode'  => $order->get_billing_postcode(),
                'country'   => $order->get_billing_country(),
                'phone'     => $order->get_billing_phone(),
            ],
            'shipping_address' => [
                'address_1' => $order->get_shipping_address_1(),
                'address_2' => $order->get_shipping_address_2(),
                'city'      => $order->get_shipping_city(),
                'state'     => $order->get_shipping_state(),
                'postcode'  => $order->get_shipping_postcode(),
                'country'   => $order->get_shipping_country(),
            ],
            'items'           => $items,
            'merchant_wallet' => $this->get_merchant_wallet_from_order($order),
            'source'          => 'woocommerce',
        ];
    }

    /**
     * Try to determine merchant wallet from order items' product meta
     */
    private function get_merchant_wallet_from_order($order) {
        foreach ($order->get_items() as $item) {
            $wallet = get_post_meta($item->get_product_id(), '_auy_merchant_wallet', true);
            if ($wallet) return $wallet;
        }
        // Fallback: use gateway setting
        $settings = $this->get_gateway_settings();
        return $settings['merchant_wallet'] ?? '';
    }

    /* ================================================================
     *  Sync Settings Endpoint
     * ================================================================ */

    /**
     * GET /wp-json/m2c/v1/sync-settings — Return current auto-sync flags
     */
    public function handle_get_sync_settings($request) {
        $settings = $this->get_gateway_settings();
        return new \WP_REST_Response([
            'success'            => true,
            'auto_sync_catalog'  => ($settings['auto_sync_catalog'] ?? 'no') === 'yes',
            'auto_sync_orders'   => ($settings['auto_sync_orders'] ?? 'no') === 'yes',
            'last_catalog_sync'  => get_option('m2c_last_catalog_sync', null),
            'last_order_sync'    => get_option('m2c_last_order_sync', null),
        ], 200);
    }

    /* ================================================================
     *  Cron: Auto Catalog Sync
     * ================================================================ */

    /**
     * WP-Cron callback: Pull product changes from WC and notify AUY.
     * Builds the current WC catalog and POSTs it to the AUY API endpoint.
     */
    public function cron_auto_sync_catalog() {
        $settings = $this->get_gateway_settings();
        if (($settings['auto_sync_catalog'] ?? 'no') !== 'yes') return;

        $api_endpoint   = $settings['api_endpoint'] ?? 'https://m2c.ab2bc.com/api';
        $merchant_wallet = $settings['merchant_wallet'] ?? '';
        if (empty($merchant_wallet)) return;

        // Collect all WC product categories and products
        $categories = get_terms(['taxonomy' => 'product_cat', 'hide_empty' => false]);
        $catalog_categories = [];

        foreach ($categories as $cat) {
            $products = wc_get_products([
                'category' => [$cat->slug],
                'limit'    => -1,
                'status'   => ['publish', 'draft'],
            ]);

            $items = [];
            foreach ($products as $product) {
                $items[] = [
                    'woo_product_id'  => $product->get_id(),
                    'auy_item_id'     => get_post_meta($product->get_id(), '_auy_item_id', true) ?: null,
                    'name'            => $product->get_name(),
                    'price'           => floatval($product->get_regular_price()),
                    'sale_price'      => $product->get_sale_price() ? floatval($product->get_sale_price()) : null,
                    'description'     => $product->get_description(),
                    'sku'             => $product->get_sku(),
                    'available'       => $product->get_status() === 'publish',
                    'stock_quantity'  => $product->get_stock_quantity(),
                    'manage_stock'    => $product->get_manage_stock(),
                    'image_url'       => wp_get_attachment_url($product->get_image_id()) ?: null,
                    'aqy_bonus'       => floatval(get_post_meta($product->get_id(), '_m2c_bonus_amount', true) ?: 0),
                ];
            }

            if (!empty($items)) {
                $catalog_categories[] = [
                    'wc_category_id' => $cat->term_id,
                    'name'           => $cat->name,
                    'slug'           => $cat->slug,
                    'items'          => $items,
                ];
            }
        }

        // POST to AUY API
        $url = rtrim($api_endpoint, '/');
        // Use the AUY woo-sync endpoint for inbound catalog data
        $response = wp_remote_post($url . '/../woo-sync/catalog-inbound', [
            'timeout' => 30,
            'headers' => [
                'Content-Type'       => 'application/json',
                'X-Merchant-Wallet'  => $merchant_wallet,
                'X-Sync-Source'      => 'wp-cron',
            ],
            'body' => wp_json_encode([
                'merchant_wallet' => $merchant_wallet,
                'site_url'        => home_url(),
                'categories'      => $catalog_categories,
                'sync_type'       => 'auto',
            ]),
        ]);

        $result = [
            'timestamp'  => current_time('mysql'),
            'categories' => count($catalog_categories),
            'products'   => array_sum(array_map(function ($c) { return count($c['items']); }, $catalog_categories)),
            'success'    => !is_wp_error($response) && wp_remote_retrieve_response_code($response) < 300,
        ];

        if (is_wp_error($response)) {
            $result['error'] = $response->get_error_message();
        }

        update_option('m2c_last_catalog_sync', $result);
        error_log('[M2C CatalogSync] Auto-sync: ' . wp_json_encode($result));
    }

    /* ================================================================
     *  Cron: Auto Order Upload
     * ================================================================ */

    /**
     * WP-Cron callback: Upload recent orders to AUY API.
     */
    public function cron_auto_sync_orders() {
        $settings = $this->get_gateway_settings();
        if (($settings['auto_sync_orders'] ?? 'no') !== 'yes') return;

        $api_endpoint    = $settings['api_endpoint'] ?? 'https://m2c.ab2bc.com/api';
        $merchant_wallet = $settings['merchant_wallet'] ?? '';
        if (empty($merchant_wallet)) return;

        // Get orders modified since last sync
        $last_sync = get_option('m2c_last_order_sync', null);
        $since = $last_sync['timestamp'] ?? gmdate('Y-m-d\TH:i:s\Z', strtotime('-1 hour'));

        $orders = wc_get_orders([
            'date_modified' => '>=' . $since,
            'limit'         => 100,
            'orderby'       => 'date',
            'order'         => 'ASC',
        ]);

        if (empty($orders)) {
            update_option('m2c_last_order_sync', [
                'timestamp' => current_time('mysql'),
                'uploaded'  => 0,
                'success'   => true,
            ]);
            return;
        }

        $mapped = [];
        foreach ($orders as $order) {
            $mapped[] = $this->map_order_for_auy($order);
        }

        $url = rtrim($api_endpoint, '/');
        $response = wp_remote_post($url . '/../woo-sync/orders-inbound', [
            'timeout' => 30,
            'headers' => [
                'Content-Type'       => 'application/json',
                'X-Merchant-Wallet'  => $merchant_wallet,
                'X-Sync-Source'      => 'wp-cron',
            ],
            'body' => wp_json_encode([
                'merchant_wallet' => $merchant_wallet,
                'site_url'        => home_url(),
                'orders'          => $mapped,
            ]),
        ]);

        $result = [
            'timestamp' => current_time('mysql'),
            'uploaded'  => count($mapped),
            'success'   => !is_wp_error($response) && wp_remote_retrieve_response_code($response) < 300,
        ];

        if (is_wp_error($response)) {
            $result['error'] = $response->get_error_message();
        }

        update_option('m2c_last_order_sync', $result);
        error_log('[M2C OrderSync] Auto-sync: ' . wp_json_encode($result));
    }

    /* ================================================================
     *  Real-time Order Hook
     * ================================================================ */

    /**
     * Hook into woocommerce_new_order for immediate upload
     */
    public function on_new_order($order_id) {
        $settings = $this->get_gateway_settings();
        if (($settings['auto_sync_orders'] ?? 'no') !== 'yes') return;

        $api_endpoint    = $settings['api_endpoint'] ?? 'https://m2c.ab2bc.com/api';
        $merchant_wallet = $settings['merchant_wallet'] ?? '';
        if (empty($merchant_wallet)) return;

        $order = wc_get_order($order_id);
        if (!$order) return;

        $mapped = $this->map_order_for_auy($order);

        $url = rtrim($api_endpoint, '/');
        wp_remote_post($url . '/../woo-sync/orders-inbound', [
            'timeout'  => 15,
            'blocking' => false, // Non-blocking — don't slow down checkout
            'headers'  => [
                'Content-Type'       => 'application/json',
                'X-Merchant-Wallet'  => $merchant_wallet,
                'X-Sync-Source'      => 'wp-hook',
            ],
            'body' => wp_json_encode([
                'merchant_wallet' => $merchant_wallet,
                'site_url'        => home_url(),
                'orders'          => [$mapped],
            ]),
        ]);
    }

    /* ================================================================
     *  Admin Settings
     * ================================================================ */

    public function register_settings() {
        register_setting('m2c_catalog_sync', self::OPTION_SYNC_SECRET, [
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
        ]);
    }
}

// Initialize
M2C_Catalog_Sync::instance();
