<?php
/**
 * WooCommerce Integration - product translation, cart, checkout language support
 *
 * @package LangForge
 */

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

class LF_WooCommerce {

    private static $instance = null;
    private $hooks_initialized = false;

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

    private function __construct() {
        add_action('plugins_loaded', [$this, 'maybe_init_hooks'], 20);
        add_action('woocommerce_loaded', [$this, 'maybe_init_hooks']);
        add_action('init', [$this, 'maybe_init_hooks'], 5);
        add_action('lf_translation_created', [$this, 'maybe_init_hooks'], 1, 0);
        $this->maybe_init_hooks();
    }

    public function maybe_init_hooks() {
        if ($this->hooks_initialized) {
            return;
        }

        if (!class_exists('WooCommerce')) {
            return;
        }

        $this->init_hooks();
        $this->hooks_initialized = true;
    }

    private function init_hooks() {
        // Filter products by language on shop pages
        add_action('pre_get_posts', [$this, 'filter_products_by_language'], 20);

        // Cart: map product IDs when switching languages
        add_filter('woocommerce_cart_item_product_id', [$this, 'translate_cart_product_id']);
        add_filter('woocommerce_cart_item_permalink', [$this, 'translate_cart_item_permalink'], 10, 3);

        // Product URL translation
        add_filter('woocommerce_product_get_permalink', [$this, 'translate_product_permalink'], 10, 2);

        // Copy product data when creating translation
        add_action('lf_translation_created', [$this, 'copy_product_data'], 10, 3);

        // Translate WooCommerce pages (shop, cart, checkout, account)
        add_filter('woocommerce_get_shop_page_id', [$this, 'translate_page_id']);
        add_filter('woocommerce_get_cart_page_id', [$this, 'translate_page_id']);
        add_filter('woocommerce_get_checkout_page_id', [$this, 'translate_page_id']);
        add_filter('woocommerce_get_myaccount_page_id', [$this, 'translate_page_id']);

        // Order email language
        add_action('woocommerce_new_order', [$this, 'save_order_language']);
        add_filter('woocommerce_email_setup_locale', [$this, 'setup_email_locale']);

        // Translate add-to-cart button text and other WC strings
        add_filter('woocommerce_product_add_to_cart_text', [$this, 'translate_add_to_cart_text'], 10, 2);
        add_filter('woocommerce_product_single_add_to_cart_text', [$this, 'translate_single_add_to_cart_text'], 10, 2);

        // Sync product price/SKU between translations
        add_action('save_post_product', [$this, 'sync_product_meta'], 20, 2);

        // Add WooCommerce specific data to product translation meta box
        add_action('lf_meta_box_after_translations', [$this, 'product_meta_box_info']);

        // Translate product attributes
        add_filter('woocommerce_attribute_label', [$this, 'translate_attribute_label'], 10, 3);

        // Mini cart widget translation
        add_filter('woocommerce_cart_item_name', [$this, 'translate_cart_item_name'], 10, 3);

        // Breadcrumb translation for shop
        add_filter('woocommerce_get_breadcrumb', [$this, 'translate_breadcrumbs']);
    }

    /**
 * Filter WooCommerce products by current language on shop/archive pages
 */
    public function filter_products_by_language($query) {
        if (is_admin() || !$query->is_main_query()) {
            return;
        }

        if (!is_shop() && !is_product_category() && !is_product_tag() && !is_product_taxonomy()) {
            return;
        }

        if ($query->get('lf_filtered')) {
            return;
        }

        $current_lang = LF_Core::instance()->get_current_language();

        $meta_query = $query->get('meta_query') ?: [];
        $meta_query[] = [
            'relation' => 'OR',
            [
                'key' => '_lf_language',
                'value' => $current_lang,
            ],
            [
                'key' => '_lf_language',
                'compare' => 'NOT EXISTS',
            ],
        ];

        $query->set('meta_query', $meta_query);
        $query->set('lf_filtered', true);
    }

    /**
 * Translate product ID in cart when language changes
 */
    public function translate_cart_product_id($product_id) {
        $current_lang = LF_Core::instance()->get_current_language();
        $product_lang = get_post_meta($product_id, '_lf_language', true);

        if ($product_lang && $product_lang !== $current_lang) {
            $translation_id = LF_Post_Translation::instance()->get_translation($product_id, $current_lang);
            if ($translation_id) {
                return $translation_id;
            }
        }

        return $product_id;
    }

    /**
 * Translate cart item permalink
 */
    public function translate_cart_item_permalink($permalink, $cart_item, $cart_item_key) {
        $product_id = $cart_item['product_id'];
        $current_lang = LF_Core::instance()->get_current_language();
        $translation_id = LF_Post_Translation::instance()->get_translation($product_id, $current_lang);

        if ($translation_id) {
            return get_permalink($translation_id);
        }

        return $permalink;
    }

    /**
 * Translate product permalink on frontend
 */
    public function translate_product_permalink($permalink, $product) {
        if (is_admin()) {
            return $permalink;
        }

        $current_lang = LF_Core::instance()->get_current_language();
        $product_id = $product->get_id();
        $translation_id = LF_Post_Translation::instance()->get_translation($product_id, $current_lang);

        if ($translation_id && $translation_id != $product_id) {
            return get_permalink($translation_id);
        }

        return $permalink;
    }

    /**
 * Copy WooCommerce product data when creating a translation
 */
    public function copy_product_data($original_post_id, $new_post_id, $target_lang) {
        if (get_post_type($original_post_id) !== 'product') {
            return;
        }

        // Copy product meta (price, SKU, stock, etc.)
        $meta_to_copy = [
            '_regular_price', '_sale_price', '_price', '_sku',
            '_stock', '_stock_status', '_manage_stock', '_backorders',
            '_weight', '_length', '_width', '_height',
            '_virtual', '_downloadable', '_tax_status', '_tax_class',
            '_product_image_gallery', '_product_attributes',
        ];

        foreach ($meta_to_copy as $meta_key) {
            $value = get_post_meta($original_post_id, $meta_key, true);
            if ($value !== '') {
                update_post_meta($new_post_id, $meta_key, $value);
            }
        }

        // Copy product type term
        $product_type = wp_get_object_terms($original_post_id, 'product_type', ['fields' => 'slugs']);
        if (!empty($product_type)) {
            wp_set_object_terms($new_post_id, $product_type, 'product_type');
        }

        // Copy product visibility
        $visibility = wp_get_object_terms($original_post_id, 'product_visibility', ['fields' => 'slugs']);
        if (!empty($visibility)) {
            wp_set_object_terms($new_post_id, $visibility, 'product_visibility');
        }
    }

    /**
 * Translate WooCommerce page IDs (shop, cart, checkout, myaccount)
 */
    public function translate_page_id($page_id) {
        if (is_admin() || !$page_id) {
            return $page_id;
        }

        $current_lang = LF_Core::instance()->get_current_language();
        $translation_id = LF_Post_Translation::instance()->get_translation($page_id, $current_lang);

        return $translation_id ?: $page_id;
    }

    /**
 * Save order language when order is created
 */
    public function save_order_language($order_id) {
        $current_lang = LF_Core::instance()->get_current_language();
        update_post_meta($order_id, '_lf_order_language', $current_lang);
    }

    /**
 * Set up locale for order emails based on order language
 */
    public function setup_email_locale($setup) {
        // Get the order from the email args if available
        if (isset($GLOBALS['lf_email_order_id'])) {
            $order_lang = get_post_meta($GLOBALS['lf_email_order_id'], '_lf_order_language', true);
            if ($order_lang) {
                $languages = LF_Core::instance()->get_active_languages();
                if (isset($languages[$order_lang]['locale'])) {
                    switch_to_locale($languages[$order_lang]['locale']);
                }
            }
        }
        return $setup;
    }

    /**
 * Translate "Add to cart" button text
 */
    public function translate_add_to_cart_text($text, $product) {
        return lf__($text, 'woocommerce');
    }

    /**
 * Translate single product "Add to cart" text
 */
    public function translate_single_add_to_cart_text($text, $product) {
        return lf__($text, 'woocommerce');
    }

    /**
 * Sync price and SKU across product translations
 */
    public function sync_product_meta($post_id, $post) {
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        // Prevent infinite loop
        static $syncing = false;
        if ($syncing) {
            return;
        }

        $translations = LF_Post_Translation::instance()->get_translations($post_id);
        if (empty($translations)) {
            return;
        }

        $syncing = true;

        $sync_meta = ['_regular_price', '_sale_price', '_price', '_sku', '_stock', '_stock_status', '_manage_stock'];

        foreach ($translations as $lang => $trans_id) {
            if ($trans_id == $post_id) continue;

            foreach ($sync_meta as $meta_key) {
                $value = get_post_meta($post_id, $meta_key, true);
                update_post_meta($trans_id, $meta_key, $value);
            }
        }

        $syncing = false;
    }

    /**
 * Show product sync info in meta box
 */
    public function product_meta_box_info($post) {
        if (get_post_type($post) !== 'product') {
            return;
        }
        ?>
        <p class="description" style="margin-top:10px;padding:8px;background:#f0f6fc;border-radius:3px;">
            <?php esc_html_e('Price, SKU, and stock are automatically synced across all product translations.', 'langforge'); ?>
        </p>
        <?php
    }

    /**
 * Translate product attribute labels
 */
    public function translate_attribute_label($label, $name, $product) {
        return lf__($label, 'woocommerce-attributes');
    }

    /**
 * Translate product name in cart
 */
    public function translate_cart_item_name($name, $cart_item, $cart_item_key) {
        $product_id = $cart_item['product_id'];
        $current_lang = LF_Core::instance()->get_current_language();
        $translation_id = LF_Post_Translation::instance()->get_translation($product_id, $current_lang);

        if ($translation_id && $translation_id != $product_id) {
            $translated_product = wc_get_product($translation_id);
            if ($translated_product) {
                $link = get_permalink($translation_id);
                return sprintf('<a href="%s">%s</a>', esc_url($link), esc_html($translated_product->get_name()));
            }
        }

        return $name;
    }

    /**
 * Translate WooCommerce breadcrumbs
 */
    public function translate_breadcrumbs($crumbs) {
        foreach ($crumbs as &$crumb) {
            // Translate "Shop" breadcrumb
            if (isset($crumb[0])) {
                $crumb[0] = lf__($crumb[0], 'woocommerce');
            }
        }
        return $crumbs;
    }
}
