<?php

defined( 'ABSPATH' ) || exit;
class GSPSYNC_Admin {
    public function init() {
        add_action( 'admin_menu', array($this, 'add_admin_menu') );
        add_action( 'admin_init', array($this, 'register_settings') );
        add_action( 'admin_enqueue_scripts', array($this, 'enqueue_admin_scripts') );
        // Product metabox
        add_action( 'add_meta_boxes', array($this, 'add_product_metabox') );
        add_action( 'save_post', array($this, 'save_product_metabox') );
        // Variation fields
        add_action(
            'woocommerce_save_product_variation',
            array($this, 'save_variation_data'),
            10,
            2
        );
        add_action(
            'woocommerce_update_product_variation',
            array($this, 'save_variation_data'),
            10,
            2
        );
        add_action(
            'woocommerce_product_after_variable_attributes',
            array($this, 'add_variation_fields'),
            10,
            3
        );
        // AJAX handler for live price preview
        add_action( 'wp_ajax_gspsync_calculate_variation_price', array($this, 'ajax_calculate_variation_price') );
    }

    /**
     * AJAX handler for live price calculation in variation metabox
     */
    public function ajax_calculate_variation_price() {
        if ( !check_ajax_referer( 'gspsync_admin_nonce', 'nonce', false ) ) {
            wp_send_json_error( array(
                'message' => 'Invalid nonce',
            ) );
            return;
        }
        if ( !current_user_can( 'edit_products' ) ) {
            wp_send_json_error( array(
                'message' => 'Unauthorized',
            ) );
            return;
        }
        $weight = ( isset( $_POST['weight'] ) ? floatval( $_POST['weight'] ) : 0 );
        $purity = ( isset( $_POST['purity'] ) ? sanitize_text_field( wp_unslash( $_POST['purity'] ) ) : '' );
        $markup = ( isset( $_POST['markup'] ) ? floatval( $_POST['markup'] ) : 0 );
        $metal_type = ( isset( $_POST['metal_type'] ) ? sanitize_text_field( wp_unslash( $_POST['metal_type'] ) ) : 'gold' );
        if ( $weight <= 0 ) {
            wp_send_json_error( array(
                'message' => 'Invalid weight',
            ) );
            return;
        }
        // Get price per gram for the specified metal
        $price_per_gram = (float) get_option( "gspsync_{$metal_type}_price_per_gram", 0 );
        if ( $price_per_gram <= 0 ) {
            wp_send_json_error( array(
                'message' => ucfirst( $metal_type ) . ' price not available',
            ) );
            return;
        }
        $profit_margin = (float) get_option( 'gspsync_profit_margin', 20 );
        // Get purity factors for the metal
        $updater = new GSPSYNC_Metal_Price_Updater();
        $purity_factors = get_option( "gspsync_{$metal_type}_purity_factors", $updater->get_default_purities( $metal_type ) );
        if ( empty( $purity ) ) {
            // Default to first purity option
            $purity = ( !empty( $purity_factors ) ? array_keys( $purity_factors )[0] : '' );
        }
        $purity_factor = ( isset( $purity_factors[$purity] ) ? (float) $purity_factors[$purity] : 1.0 );
        $base_price = $weight * $price_per_gram * $purity_factor;
        $margin_amount = $base_price * ($profit_margin / 100);
        $final_price = $base_price + $margin_amount + $markup;
        wp_send_json_success( array(
            'price'                => round( $final_price, 2 ),
            'formatted_price'      => GSPSYNC_Currency::format( $final_price ),
            'base_price'           => GSPSYNC_Currency::format( $base_price ),
            'margin'               => GSPSYNC_Currency::format( $margin_amount ),
            'markup'               => GSPSYNC_Currency::format( $markup ),
            'purity_used'          => $purity,
            'metal_price_per_gram' => $price_per_gram,
        ) );
    }

    /**
     * Add admin menu under WooCommerce
     */
    public function add_admin_menu() {
        add_submenu_page(
            'woocommerce',
            __( 'Gold & Silver Price Sync Settings', 'gold-silver-price-sync' ),
            __( 'Gold & Silver Price Sync', 'gold-silver-price-sync' ),
            'manage_options',
            'gold-silver-price-sync',
            array($this, 'settings_page')
        );
    }

    /**
     * Register plugin settings
     */
    public function register_settings() {
        register_setting( 'gspsync_options', 'gspsync_profit_margin', array(
            'type'              => 'number',
            'sanitize_callback' => array($this, 'sanitize_profit_margin'),
        ) );
        register_setting( 'gspsync_options', 'gspsync_update_frequency', array(
            'type'              => 'string',
            'sanitize_callback' => array($this, 'sanitize_update_frequency'),
        ) );
        register_setting( 'gspsync_options', 'gspsync_cart_lock_time', array(
            'type'              => 'integer',
            'sanitize_callback' => array($this, 'sanitize_cart_lock_time'),
        ) );
        register_setting( 'gspsync_options', 'gspsync_currency', array(
            'type'              => 'string',
            'sanitize_callback' => array($this, 'sanitize_currency'),
        ) );
        // Per-metal purity factors
        foreach ( array('gold', 'silver') as $metal ) {
            register_setting( 'gspsync_options', "gspsync_{$metal}_purity_factors", array(
                'type'              => 'array',
                'sanitize_callback' => array($this, 'sanitize_purity_factors'),
            ) );
        }
    }

    public function sanitize_profit_margin( $value ) {
        return max( 0, min( floatval( $value ), 500 ) );
    }

    public function sanitize_update_frequency( $value ) {
        $value = sanitize_text_field( $value );
        $allowed = array_keys( gspsync_get_allowed_frequencies() );
        return ( in_array( $value, $allowed, true ) ? $value : 'hourly' );
    }

    public function sanitize_cart_lock_time( $value ) {
        return max( 5, min( absint( $value ), 60 ) );
    }

    public function sanitize_currency( $value ) {
        $value = strtoupper( sanitize_text_field( $value ) );
        return ( GSPSYNC_Currency::is_supported( $value ) ? $value : GSPSYNC_Currency::get() );
    }

    public function sanitize_purity_factors( $factors ) {
        $clean = array();
        if ( is_array( $factors ) ) {
            foreach ( $factors as $purity => $factor ) {
                $factor = floatval( $factor );
                if ( $factor >= 0.1 && $factor <= 1.0 ) {
                    $clean[sanitize_text_field( $purity )] = $factor;
                }
            }
        }
        return $clean;
    }

    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts( $hook ) {
        $is_settings_page = 'woocommerce_page_gold-silver-price-sync' === $hook;
        $is_product_page = in_array( $hook, array('post.php', 'post-new.php'), true );
        if ( $is_product_page ) {
            global $post;
            if ( !$post || $post->post_type !== 'product' ) {
                $is_product_page = false;
            }
        }
        if ( !$is_settings_page && !$is_product_page ) {
            return;
        }
        wp_enqueue_style(
            'gspsync-admin',
            GSPSYNC_URL . 'admin/css/admin.css',
            array(),
            GSPSYNC_VERSION
        );
        wp_enqueue_script(
            'gspsync-admin',
            GSPSYNC_URL . 'admin/js/admin.js',
            array('jquery'),
            GSPSYNC_VERSION,
            true
        );
        wp_enqueue_style( 'dashicons' );
        $updater = new GSPSYNC_Metal_Price_Updater();
        // Build metal prices data for JS
        $metal_prices = array();
        $all_purity_factors = array();
        foreach ( array_keys( $updater->get_metal_config() ) as $metal ) {
            $metal_prices[$metal] = (float) get_option( "gspsync_{$metal}_price_per_gram", 0 );
            $all_purity_factors[$metal] = get_option( "gspsync_{$metal}_purity_factors", $updater->get_default_purities( $metal ) );
        }
        wp_localize_script( 'gspsync-admin', 'gspsync_admin_params', array(
            'ajax_url'       => admin_url( 'admin-ajax.php' ),
            'nonce'          => wp_create_nonce( 'gspsync_admin_nonce' ),
            'metal_prices'   => $metal_prices,
            'profit_margin'  => (float) get_option( 'gspsync_profit_margin', 20 ),
            'purity_factors' => $all_purity_factors,
            'currency'       => GSPSYNC_Currency::get_js_params(),
            'i18n'           => array(
                'calculating'     => __( 'Calculating...', 'gold-silver-price-sync' ),
                'estimated_price' => __( 'Estimated price:', 'gold-silver-price-sync' ),
                'enter_weight'    => __( 'Enter a weight to see the estimated price', 'gold-silver-price-sync' ),
                'error'           => __( 'Calculation error', 'gold-silver-price-sync' ),
                'base'            => __( 'Base', 'gold-silver-price-sync' ),
                'margin'          => __( 'Margin', 'gold-silver-price-sync' ),
                'markup'          => __( 'Markup', 'gold-silver-price-sync' ),
            ),
        ) );
    }

    /**
     * Get all metal products for dashboard table
     */
    private function get_metal_products() {
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-off aggregation across postmeta for the admin dashboard; no WP API equivalent, admin-only page.
        $products = $wpdb->get_results( $wpdb->prepare(
            "\n            SELECT DISTINCT p.ID, p.post_title,\n                   MAX(CASE WHEN pm.meta_key = '_gspsync_metal_type' THEN pm.meta_value END) as metal_type,\n                   MAX(CASE WHEN pm.meta_key = '_is_gold_product' THEN pm.meta_value END) as is_gold_legacy,\n                   MAX(CASE WHEN pm.meta_key = '_gspsync_purity' THEN pm.meta_value END) as purity,\n                   MAX(CASE WHEN pm.meta_key = '_gold_purity' THEN pm.meta_value END) as purity_legacy,\n                   MAX(CASE WHEN pm.meta_key = '_gspsync_weight_grams' THEN pm.meta_value END) as weight_grams,\n                   MAX(CASE WHEN pm.meta_key = '_peso_grammi' THEN pm.meta_value END) as weight_grams_legacy,\n                   MAX(CASE WHEN pm.meta_key = '_price' THEN pm.meta_value END) as static_price\n            FROM {$wpdb->posts} p\n            LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id\n                AND pm.meta_key IN ('_gspsync_metal_type', '_is_gold_product', '_gspsync_purity', '_gold_purity', '_gspsync_weight_grams', '_peso_grammi', '_price')\n            WHERE p.post_type = %s\n            AND p.post_status = 'publish'\n            AND (\n                EXISTS (SELECT 1 FROM {$wpdb->postmeta} pm2 WHERE pm2.post_id = p.ID AND pm2.meta_key = '_gspsync_metal_type' AND pm2.meta_value IN ('gold', 'silver'))\n                OR EXISTS (SELECT 1 FROM {$wpdb->postmeta} pm3 WHERE pm3.post_id = p.ID AND pm3.meta_key = '_is_gold_product' AND pm3.meta_value = 'yes')\n                OR p.post_title LIKE %s OR p.post_title LIKE %s\n                OR p.post_title LIKE %s OR p.post_title LIKE %s\n            )\n            GROUP BY p.ID, p.post_title\n            ORDER BY p.post_title ASC\n        ",
            'product',
            '%oro%',
            '%gold%',
            '%argento%',
            '%silver%'
        ) );
        $updater = new GSPSYNC_Metal_Price_Updater();
        foreach ( $products as $product ) {
            // Resolve metal type (new meta or legacy)
            if ( empty( $product->metal_type ) && $product->is_gold_legacy === 'yes' ) {
                $product->metal_type = 'gold';
            }
            // Resolve purity (new or legacy)
            if ( empty( $product->purity ) && !empty( $product->purity_legacy ) ) {
                $product->purity = $product->purity_legacy;
            }
            // Resolve weight (new or legacy)
            if ( empty( $product->weight_grams ) && !empty( $product->weight_grams_legacy ) ) {
                $product->weight_grams = $product->weight_grams_legacy;
            }
            // Calculate dynamic price
            $wc_product = wc_get_product( $product->ID );
            if ( $wc_product ) {
                $dynamic_price = $updater->calculate_price_by_weight( $wc_product );
                $product->price = ( $dynamic_price !== false ? $dynamic_price : $product->static_price );
            } else {
                $product->price = $product->static_price;
            }
        }
        return $products;
    }

    /**
     * Render the settings page
     */
    public function settings_page() {
        $updater = new GSPSYNC_Metal_Price_Updater();
        // Only auto-fetch if prices are stale (based on the configured frequency)
        $last_update = (int) get_option( 'gspsync_last_update', 0 );
        $now = current_time( 'timestamp' );
        $is_premium = function_exists( 'gspsync_fs' ) && gspsync_fs()->can_use_premium_code();
        $freq_map = gspsync_get_allowed_frequencies();
        $interval = $freq_map[gspsync_get_update_frequency()];
        if ( $now - $last_update >= $interval ) {
            $updater->clear_api_transients();
            $updater->fetch_all_metal_prices();
        }
        // Handle manual price update
        if ( isset( $_POST['update_prices_now'] ) && check_admin_referer( 'gspsync_update_now' ) ) {
            $updater->clear_api_transients();
            $count = $updater->update_all_products();
            echo '<div class="notice notice-success gspsync-notice"><p>' . esc_html( sprintf( __( 'Prices updated for %d products.', 'gold-silver-price-sync' ), $count ) ) . '</p></div>';
        }
        if ( isset( $_GET['settings-updated'] ) && $_GET['settings-updated'] === 'true' ) {
            echo '<div class="notice notice-success gspsync-notice"><p>' . esc_html__( 'Settings saved successfully!', 'gold-silver-price-sync' ) . '</p></div>';
        }
        // Currency the stored figures are denominated in. It can lag behind the
        // configured one if a refetch failed right after a currency switch, so the
        // dashboard labels the numbers with the currency they were actually
        // computed in rather than the one that is merely selected.
        $prices_currency = get_option( 'gspsync_prices_currency', GSPSYNC_Currency::get() );
        if ( !GSPSYNC_Currency::is_supported( $prices_currency ) ) {
            $prices_currency = GSPSYNC_Currency::get();
        }
        $selected_currency = GSPSYNC_Currency::get();
        $store_currency = GSPSYNC_Currency::get_store_currency();
        $currency_mismatch = !GSPSYNC_Currency::matches_store();
        // Gather metal data
        $metals_data = array();
        $metal_config = $updater->get_metal_config();
        foreach ( array_keys( $metal_config ) as $metal ) {
            $unit_key = ( $metal_config[$metal]['unit'] === 'pound' ? 'per_pound' : 'per_ounce' );
            $metals_data[$metal] = array(
                'price_per_unit' => (float) get_option( "gspsync_{$metal}_price_{$unit_key}", 0 ),
                'price_per_gram' => (float) get_option( "gspsync_{$metal}_price_per_gram", 0 ),
                'last_update'    => (int) get_option( "gspsync_{$metal}_last_update", 0 ),
                'unit_label'     => $prices_currency . '/' . (( $metal_config[$metal]['unit'] === 'pound' ? __( 'pound', 'gold-silver-price-sync' ) : __( 'ounce', 'gold-silver-price-sync' ) )),
            );
        }
        $last_update = (int) get_option( 'gspsync_last_update', 0 );
        $now = current_time( 'timestamp' );
        $time_diff = $now - $last_update;
        if ( $time_diff < 60 ) {
            $time_ago = __( 'Less than 1 minute ago', 'gold-silver-price-sync' );
        } elseif ( $time_diff < 3600 ) {
            $m = floor( $time_diff / 60 );
            $time_ago = $m . ' ' . __( 'minute(s) ago', 'gold-silver-price-sync' );
        } elseif ( $time_diff < 86400 ) {
            $h = floor( $time_diff / 3600 );
            $time_ago = $h . ' ' . __( 'hour(s) ago', 'gold-silver-price-sync' );
        } else {
            $d = floor( $time_diff / 86400 );
            $time_ago = $d . ' ' . __( 'day(s) ago', 'gold-silver-price-sync' );
        }
        $profit_margin = (float) get_option( 'gspsync_profit_margin', 20 );
        $metal_products = $this->get_metal_products();
        $is_premium = function_exists( 'gspsync_fs' ) && gspsync_fs()->can_use_premium_code();
        // Determine the stale threshold based on the active update interval
        $freq_intervals = gspsync_get_allowed_frequencies();
        $stale_threshold = $freq_intervals[gspsync_get_update_frequency()] * 2;
        $metal_labels = array(
            'gold'   => __( 'Gold', 'gold-silver-price-sync' ),
            'silver' => __( 'Silver', 'gold-silver-price-sync' ),
        );
        $metal_icons = array(
            'gold'   => '🥇',
            'silver' => '🥈',
        );
        ?>
        <div class="wrap gspsync-admin-wrap">
            <div class="gspsync-header">
                <h1>
                    <span class="dashicons dashicons-money-alt gspsync-header-icon"></span>
                    <?php 
        echo esc_html__( 'Gold & Silver Price Sync', 'gold-silver-price-sync' );
        ?>
                    <?php 
        if ( $is_premium ) {
            ?><span class="gspsync-premium-badge">Premium</span><?php 
        }
        ?>
                </h1>
                <p class="gspsync-subtitle"><?php 
        echo esc_html__( 'Dynamic pricing for gold and silver products', 'gold-silver-price-sync' );
        ?></p>
            </div>

            <?php 
        if ( $currency_mismatch ) {
            ?>
                <div class="notice notice-warning gspsync-notice">
                    <p>
                        <strong><?php 
            echo esc_html__( 'Currency mismatch', 'gold-silver-price-sync' );
            ?></strong><br>
                        <?php 
            printf( 
                /* translators: 1: plugin pricing currency code 2: WooCommerce store currency code */
                esc_html__( 'Prices are being calculated in %1$s while your shop sells in %2$s. WooCommerce stores product prices as plain numbers, so every price this plugin writes will be off by the exchange rate. Set both to the same currency.', 'gold-silver-price-sync' ),
                esc_html( $selected_currency ),
                esc_html( $store_currency )
             );
            ?>
                    </p>
                </div>
            <?php 
        }
        ?>

            <?php 
        if ( !$is_premium ) {
            ?>
            <div class="gspsync-premium-promo">
                <div class="gspsync-promo-content">
                    <div class="gspsync-promo-icon"><span class="dashicons dashicons-star-filled"></span></div>
                    <div class="gspsync-promo-text">
                        <h2><?php 
            echo esc_html__( 'Unlock Gold & Silver Price Sync Premium', 'gold-silver-price-sync' );
            ?></h2>
                        <p><?php 
            echo esc_html__( 'Keep prices fresher and protect your margins from market swings.', 'gold-silver-price-sync' );
            ?></p>
                        <ul class="gspsync-promo-features">
                            <li><span class="dashicons dashicons-clock"></span> <?php 
            echo esc_html__( 'Update prices as often as every 10 minutes, backed by a price feed refreshed every 10 minutes', 'gold-silver-price-sync' );
            ?></li>
                            <li><span class="dashicons dashicons-lock"></span> <?php 
            echo esc_html__( 'Lock the cart price so customers pay what they saw', 'gold-silver-price-sync' );
            ?></li>
                            <li><span class="dashicons dashicons-cart"></span> <?php 
            echo esc_html__( 'Auto-empty the cart when the price timer expires', 'gold-silver-price-sync' );
            ?></li>
                            <li><span class="dashicons dashicons-email-alt"></span> <?php 
            echo esc_html__( 'Priority email support', 'gold-silver-price-sync' );
            ?></li>
                        </ul>
                    </div>
                </div>
                <div class="gspsync-promo-cta">
                    <a href="<?php 
            echo esc_url( gspsync_fs()->get_upgrade_url() );
            ?>" class="gspsync-promo-btn">
                        <span class="dashicons dashicons-star-filled"></span>
                        <?php 
            echo esc_html__( 'Upgrade to Premium', 'gold-silver-price-sync' );
            ?>
                    </a>
                    <span class="gspsync-promo-note"><?php 
            echo esc_html__( 'Instant activation · Secure checkout via Freemius', 'gold-silver-price-sync' );
            ?></span>
                </div>
            </div>
            <?php 
        }
        ?>

            <div class="gspsync-dashboard-grid">
                <!-- Metal Prices Card with Tabs -->
                <div class="gspsync-card gspsync-price-info">
                    <div class="gspsync-card-header">
                        <h2><span class="dashicons dashicons-chart-line"></span> <?php 
        echo esc_html__( 'Current Metal Prices', 'gold-silver-price-sync' );
        ?></h2>
                        <a href="<?php 
        echo esc_url( wp_nonce_url( add_query_arg( 'gspsync_update_prices', '1' ), 'gspsync_update_prices' ) );
        ?>" class="gspsync-refresh-btn" title="<?php 
        echo esc_attr__( 'Update now', 'gold-silver-price-sync' );
        ?>">
                            <span class="dashicons dashicons-update"></span>
                        </a>
                    </div>
                    <div class="gspsync-card-content">
                        <!-- Metal Tabs -->
                        <div class="gspsync-metal-tabs">
                            <?php 
        foreach ( $metals_data as $metal => $data ) {
            ?>
                                <button class="gspsync-metal-tab<?php 
            echo ( $metal === 'gold' ? ' active' : '' );
            ?>" data-metal="<?php 
            echo esc_attr( $metal );
            ?>">
                                    <?php 
            echo esc_html( $metal_labels[$metal] );
            ?>
                                </button>
                            <?php 
        }
        ?>
                        </div>

                        <?php 
        foreach ( $metals_data as $metal => $data ) {
            ?>
                        <div class="gspsync-metal-panel<?php 
            echo ( $metal === 'gold' ? ' active' : '' );
            ?>" id="gspsync-panel-<?php 
            echo esc_attr( $metal );
            ?>">
                            <?php 
            if ( $data['price_per_unit'] > 0 && $data['price_per_gram'] > 0 ) {
                ?>
                                <div class="gspsync-price-grid">
                                    <div class="gspsync-price-item">
                                        <span class="gspsync-price-label"><?php 
                echo esc_html( $data['unit_label'] );
                ?>:</span>
                                        <span class="gspsync-price-value gspsync-metal-<?php 
                echo esc_attr( $metal );
                ?>"><?php 
                echo esc_html( GSPSYNC_Currency::format( $data['price_per_unit'], 2, $prices_currency ) );
                ?></span>
                                    </div>
                                    <div class="gspsync-price-item">
                                        <span class="gspsync-price-label"><?php 
                /* translators: %s: currency code, e.g. USD */
                printf( esc_html__( '%s/gram:', 'gold-silver-price-sync' ), esc_html( $prices_currency ) );
                ?></span>
                                        <span class="gspsync-price-value gspsync-metal-<?php 
                echo esc_attr( $metal );
                ?>"><?php 
                echo esc_html( GSPSYNC_Currency::format( $data['price_per_gram'], 4, $prices_currency ) );
                ?></span>
                                    </div>
                                </div>

                                <div class="gspsync-examples">
                                    <h4><?php 
                echo esc_html__( 'Calculation examples (100g):', 'gold-silver-price-sync' );
                ?></h4>
                                    <div class="gspsync-example-item">
                                        <span><?php 
                echo esc_html__( 'Without margin:', 'gold-silver-price-sync' );
                ?></span>
                                        <strong><?php 
                echo esc_html( GSPSYNC_Currency::format( $data['price_per_gram'] * 100, 2, $prices_currency ) );
                ?></strong>
                                    </div>
                                    <div class="gspsync-example-item">
                                        <span><?php 
                /* translators: %s: profit margin percentage */
                printf( esc_html__( 'With %s%% margin:', 'gold-silver-price-sync' ), esc_html( $profit_margin ) );
                ?></span>
                                        <strong><?php 
                echo esc_html( GSPSYNC_Currency::format( $data['price_per_gram'] * 100 * (1 + $profit_margin / 100), 2, $prices_currency ) );
                ?></strong>
                                    </div>
                                </div>
                            <?php 
            } else {
                ?>
                                <div class="gspsync-error">
                                    <span class="dashicons dashicons-warning"></span>
                                    <?php 
                /* translators: %s: metal name (Gold or Silver) */
                printf( esc_html__( 'No price data available for %s. Check API connection.', 'gold-silver-price-sync' ), esc_html( $metal_labels[$metal] ) );
                ?>
                                </div>
                            <?php 
            }
            ?>
                        </div>
                        <?php 
        }
        ?>

                        <div class="gspsync-last-update">
                            <span class="dashicons dashicons-clock"></span>
                            <?php 
        echo esc_html__( 'Last update:', 'gold-silver-price-sync' );
        ?>
                            <strong><?php 
        echo ( $last_update ? esc_html( $time_ago ) : esc_html__( 'Never', 'gold-silver-price-sync' ) );
        ?></strong>
                            <?php 
        if ( $time_diff > $stale_threshold ) {
            ?>
                                <span class="gspsync-warning">⚠ <?php 
            echo esc_html__( 'Data not recent', 'gold-silver-price-sync' );
            ?></span>
                            <?php 
        }
        ?>
                        </div>
                    </div>
                </div>

                <!-- Settings Card -->
                <div class="gspsync-card gspsync-settings">
                    <div class="gspsync-card-header">
                        <h2><span class="dashicons dashicons-admin-settings"></span> <?php 
        echo esc_html__( 'Settings', 'gold-silver-price-sync' );
        ?></h2>
                    </div>
                    <div class="gspsync-card-content">
                        <form method="post" action="options.php">
                            <?php 
        settings_fields( 'gspsync_options' );
        ?>
                            <?php 
        do_settings_sections( 'gspsync_options' );
        ?>

                            <div class="gspsync-settings-grid">
                                <!-- Pricing Currency -->
                                <div class="gspsync-setting-item">
                                    <label class="gspsync-setting-label">
                                        <span class="dashicons dashicons-money-alt"></span>
                                        <?php 
        echo esc_html__( 'Pricing currency', 'gold-silver-price-sync' );
        ?>
                                    </label>
                                    <select name="gspsync_currency" class="gspsync-select">
                                        <?php 
        foreach ( GSPSYNC_Currency::get_supported() as $code => $name ) {
            ?>
                                            <option value="<?php 
            echo esc_attr( $code );
            ?>" <?php 
            selected( $selected_currency, $code );
            ?>>
                                                <?php 
            echo esc_html( $code . ' — ' . $name );
            ?>
                                            </option>
                                        <?php 
        }
        ?>
                                    </select>
                                    <p class="gspsync-setting-description">
                                        <?php 
        printf( 
            /* translators: %s: WooCommerce store currency code */
            esc_html__( 'Currency the metal quotes are converted into. Keep it identical to your WooCommerce currency (%s). Changing it refreshes all prices immediately.', 'gold-silver-price-sync' ),
            esc_html( $store_currency )
         );
        ?>
                                    </p>
                                </div>

                                <!-- Profit Margin -->
                                <div class="gspsync-setting-item">
                                    <label class="gspsync-setting-label">
                                        <span class="dashicons dashicons-money"></span>
                                        <?php 
        echo esc_html__( 'Profit margin (%)', 'gold-silver-price-sync' );
        ?>
                                    </label>
                                    <input type="number" name="gspsync_profit_margin"
                                        value="<?php 
        echo esc_attr( get_option( 'gspsync_profit_margin', 20 ) );
        ?>"
                                        min="0" step="0.01" class="gspsync-input" />
                                    <p class="gspsync-setting-description">
                                        <?php 
        echo esc_html__( 'Percentage to add to the metal cost to determine the final price.', 'gold-silver-price-sync' );
        ?>
                                    </p>
                                </div>

                                <!-- Update Frequency -->
                                <div class="gspsync-setting-item">
                                    <label class="gspsync-setting-label">
                                        <span class="dashicons dashicons-update"></span>
                                        <?php 
        echo esc_html__( 'Update frequency', 'gold-silver-price-sync' );
        ?>
                                    </label>
                                    <?php 
        $frequency_labels = array(
            'hourly'     => __( 'Every hour', 'gold-silver-price-sync' ),
            'twicedaily' => __( 'Twice daily', 'gold-silver-price-sync' ),
            'daily'      => __( 'Once daily', 'gold-silver-price-sync' ),
        );
        $current_frequency = gspsync_get_update_frequency();
        ?>
                                    <select name="gspsync_update_frequency" class="gspsync-select">
                                        <?php 
        foreach ( $frequency_labels as $freq_key => $freq_label ) {
            ?>
                                            <option value="<?php 
            echo esc_attr( $freq_key );
            ?>" <?php 
            selected( $current_frequency, $freq_key );
            ?>>
                                                <?php 
            echo esc_html( $freq_label );
            ?>
                                            </option>
                                        <?php 
        }
        ?>
                                    </select>
                                    <p class="gspsync-setting-description">
                                        <?php 
        echo esc_html__( 'How often metal prices are refreshed from the price service.', 'gold-silver-price-sync' );
        ?>
                                    </p>
                                    <?php 
        if ( !$is_premium ) {
            ?>
                                        <p class="gspsync-premium-prompt">
                                            <a href="<?php 
            echo esc_url( gspsync_fs()->get_upgrade_url() );
            ?>"><?php 
            echo esc_html__( 'Upgrade to Premium', 'gold-silver-price-sync' );
            ?></a>
                                            <?php 
            echo esc_html__( 'for 10 and 30 minute intervals with a price feed refreshed every 10 minutes.', 'gold-silver-price-sync' );
            ?>
                                        </p>
                                    <?php 
        }
        ?>
                                </div>

                                <!-- Cart Lock Time (Premium) -->
                                <div class="gspsync-setting-item">
                                    <label class="gspsync-setting-label">
                                        <span class="dashicons dashicons-cart"></span>
                                        <?php 
        echo esc_html__( 'Cart price lock time (minutes)', 'gold-silver-price-sync' );
        ?>
                                    </label>
                                    <?php 
        if ( $is_premium ) {
            ?>
                                        <input type="number" name="gspsync_cart_lock_time"
                                            value="<?php 
            echo esc_attr( get_option( 'gspsync_cart_lock_time', 10 ) );
            ?>"
                                            min="5" max="60" step="1" class="gspsync-input" />
                                        <p class="gspsync-setting-description">
                                            <?php 
            echo esc_html__( 'How long (in minutes) prices remain locked after adding to cart.', 'gold-silver-price-sync' );
            ?>
                                        </p>
                                    <?php 
        } else {
            ?>
                                        <input type="text" class="gspsync-input" value="<?php 
            echo esc_attr__( 'Premium feature', 'gold-silver-price-sync' );
            ?>" disabled />
                                        <p class="gspsync-premium-prompt">
                                            <a href="<?php 
            echo esc_url( gspsync_fs()->get_upgrade_url() );
            ?>"><?php 
            echo esc_html__( 'Upgrade to Premium', 'gold-silver-price-sync' );
            ?></a>
                                            <?php 
            echo esc_html__( 'to enable cart price locking.', 'gold-silver-price-sync' );
            ?>
                                        </p>
                                    <?php 
        }
        ?>
                                </div>
                            </div>

                            <!-- Purity Factors per Metal -->
                            <?php 
        foreach ( array('gold', 'silver') as $metal ) {
            $purity_factors = get_option( "gspsync_{$metal}_purity_factors", $updater->get_default_purities( $metal ) );
            if ( empty( $purity_factors ) ) {
                continue;
            }
            ?>
                            <div class="gspsync-purity-section">
                                <h3>
                                    <span class="dashicons dashicons-admin-generic"></span>
                                    <?php 
            /* translators: %s: metal name (Gold or Silver) */
            printf( esc_html__( '%s Purity Factors', 'gold-silver-price-sync' ), esc_html( $metal_labels[$metal] ) );
            ?>
                                </h3>
                                <p class="gspsync-setting-description">
                                    <?php 
            /* translators: %s: metal name in lowercase (gold or silver) */
            printf( esc_html__( 'Set the multiplier factors for each %s purity level (value between 0.1 and 1.0).', 'gold-silver-price-sync' ), esc_html( strtolower( $metal_labels[$metal] ) ) );
            ?>
                                </p>
                                <div class="gspsync-purity-grid">
                                    <?php 
            foreach ( $purity_factors as $purity => $factor ) {
                $factor = (float) $factor;
                ?>
                                        <div class="gspsync-purity-item">
                                            <label class="gspsync-purity-label"><?php 
                echo esc_html( $purity );
                ?></label>
                                            <input type="number"
                                                name="gspsync_<?php 
                echo esc_attr( $metal );
                ?>_purity_factors[<?php 
                echo esc_attr( $purity );
                ?>]"
                                                value="<?php 
                echo esc_attr( $factor );
                ?>"
                                                min="0.1" max="1.0" step="0.001"
                                                class="gspsync-purity-input"
                                                data-purity="<?php 
                echo esc_attr( $purity );
                ?>" />
                                            <span class="gspsync-percentage"><?php 
                echo number_format( $factor * 100, 1 );
                ?>%</span>
                                        </div>
                                    <?php 
            }
            ?>
                                </div>
                            </div>
                            <?php 
        }
        ?>

                            <div class="gspsync-submit-section">
                                <?php 
        submit_button(
            __( 'Save All Settings', 'gold-silver-price-sync' ),
            'primary gspsync-btn-primary',
            'submit',
            false
        );
        ?>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Tools Card -->
                <div class="gspsync-card gspsync-manual-update">
                    <div class="gspsync-card-header">
                        <h2><span class="dashicons dashicons-admin-tools"></span> <?php 
        echo esc_html__( 'Tools', 'gold-silver-price-sync' );
        ?></h2>
                    </div>
                    <div class="gspsync-card-content">
                        <p><?php 
        echo esc_html__( 'Force an immediate price update for all metal products.', 'gold-silver-price-sync' );
        ?></p>
                        <form method="post">
                            <?php 
        wp_nonce_field( 'gspsync_update_now' );
        ?>
                            <input type="hidden" name="update_prices_now" value="1">
                            <?php 
        submit_button(
            __( 'Update Prices Now', 'gold-silver-price-sync' ),
            'secondary gspsync-btn-secondary',
            'update_now',
            false
        );
        ?>
                        </form>

                        <hr class="gspsync-tools-divider">

                        <h3 class="gspsync-tools-subtitle"><span class="dashicons dashicons-info-outline"></span> <?php 
        echo esc_html__( 'System Status', 'gold-silver-price-sync' );
        ?></h3>
                        <ul class="gspsync-status-list">
                            <li>
                                <span><?php 
        echo esc_html__( 'Plan', 'gold-silver-price-sync' );
        ?></span>
                                <strong><?php 
        echo ( $is_premium ? esc_html__( 'Premium', 'gold-silver-price-sync' ) : esc_html__( 'Free', 'gold-silver-price-sync' ) );
        ?></strong>
                            </li>
                            <?php 
        foreach ( $metals_data as $metal => $data ) {
            ?>
                            <li>
                                <span><?php 
            echo esc_html( $metal_labels[$metal] );
            ?></span>
                                <?php 
            if ( $data['price_per_gram'] > 0 ) {
                ?>
                                    <strong class="gspsync-status-ok"><span class="dashicons dashicons-yes-alt"></span> <?php 
                echo esc_html( GSPSYNC_Currency::format( $data['price_per_gram'], 2, $prices_currency ) );
                ?>/g</strong>
                                <?php 
            } else {
                ?>
                                    <strong class="gspsync-status-off"><span class="dashicons dashicons-warning"></span> <?php 
                echo esc_html__( 'N/A', 'gold-silver-price-sync' );
                ?></strong>
                                <?php 
            }
            ?>
                            </li>
                            <?php 
        }
        ?>
                            <li>
                                <span><?php 
        echo esc_html__( 'Last update', 'gold-silver-price-sync' );
        ?></span>
                                <strong><?php 
        echo ( $last_update ? esc_html( $time_ago ) : esc_html__( 'Never', 'gold-silver-price-sync' ) );
        ?></strong>
                            </li>
                            <li>
                                <span><?php 
        echo esc_html__( 'Metal products', 'gold-silver-price-sync' );
        ?></span>
                                <strong><?php 
        echo count( $metal_products );
        ?></strong>
                            </li>
                            <li>
                                <span><?php 
        echo esc_html__( 'Profit margin', 'gold-silver-price-sync' );
        ?></span>
                                <strong><?php 
        echo esc_html( $profit_margin );
        ?>%</strong>
                            </li>
                        </ul>
                    </div>
                </div>

                <!-- Products Table -->
                <div class="gspsync-card gspsync-products-list">
                    <div class="gspsync-card-header">
                        <h2><span class="dashicons dashicons-products"></span> <?php 
        echo esc_html__( 'Metal Products', 'gold-silver-price-sync' );
        ?> (<?php 
        echo count( $metal_products );
        ?>)</h2>
                    </div>
                    <div class="gspsync-card-content">
                        <?php 
        if ( !empty( $metal_products ) ) {
            ?>
                            <div class="gspsync-products-table-wrapper">
                                <table class="gspsync-products-table">
                                    <thead>
                                        <tr>
                                            <th><?php 
            echo esc_html__( 'Product', 'gold-silver-price-sync' );
            ?></th>
                                            <th><?php 
            echo esc_html__( 'Metal', 'gold-silver-price-sync' );
            ?></th>
                                            <th><?php 
            echo esc_html__( 'Weight (g)', 'gold-silver-price-sync' );
            ?></th>
                                            <th><?php 
            echo esc_html__( 'Purity', 'gold-silver-price-sync' );
            ?></th>
                                            <th><?php 
            echo esc_html__( 'Price', 'gold-silver-price-sync' );
            ?></th>
                                            <th><?php 
            echo esc_html__( 'Actions', 'gold-silver-price-sync' );
            ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
            foreach ( $metal_products as $product ) {
                ?>
                                            <tr>
                                                <td class="gspsync-product-name"><strong><?php 
                echo esc_html( $product->post_title );
                ?></strong></td>
                                                <td class="gspsync-product-metal">
                                                    <?php 
                if ( !empty( $product->metal_type ) ) {
                    ?>
                                                        <span class="gspsync-status-badge gspsync-status-<?php 
                    echo esc_attr( $product->metal_type );
                    ?>">
                                                            <?php 
                    echo esc_html( ( isset( $metal_labels[$product->metal_type] ) ? $metal_labels[$product->metal_type] : ucfirst( $product->metal_type ) ) );
                    ?>
                                                        </span>
                                                    <?php 
                } else {
                    ?>
                                                        <span class="gspsync-status-badge gspsync-status-auto">
                                                            <span class="dashicons dashicons-admin-generic"></span>
                                                            <?php 
                    echo esc_html__( 'Auto', 'gold-silver-price-sync' );
                    ?>
                                                        </span>
                                                    <?php 
                }
                ?>
                                                </td>
                                                <td class="gspsync-product-weight">
                                                    <?php 
                if ( !empty( $product->weight_grams ) ) {
                    ?>
                                                        <strong><?php 
                    echo number_format(
                        floatval( $product->weight_grams ),
                        2,
                        ',',
                        '.'
                    );
                    ?>g</strong>
                                                    <?php 
                } else {
                    ?>
                                                        <span class="gspsync-missing">—</span>
                                                    <?php 
                }
                ?>
                                                </td>
                                                <td class="gspsync-product-purity">
                                                    <?php 
                if ( !empty( $product->purity ) ) {
                    ?>
                                                        <span class="gspsync-purity-badge gspsync-purity-<?php 
                    echo esc_attr( str_replace( '.', '', $product->purity ) );
                    ?>">
                                                            <?php 
                    echo esc_html( strtoupper( $product->purity ) );
                    ?>
                                                        </span>
                                                    <?php 
                } else {
                    ?>
                                                        <span class="gspsync-missing"><?php 
                    echo esc_html__( 'N/A', 'gold-silver-price-sync' );
                    ?></span>
                                                    <?php 
                }
                ?>
                                                </td>
                                                <td class="gspsync-product-price">
                                                    <?php 
                if ( !empty( $product->price ) && !empty( $product->metal_type ) ) {
                    ?>
                                                        <strong><?php 
                    echo esc_html( GSPSYNC_Currency::format( $product->price ) );
                    ?></strong>
                                                    <?php 
                } else {
                    ?>
                                                        <span class="gspsync-missing">—</span>
                                                    <?php 
                }
                ?>
                                                </td>
                                                <td class="gspsync-product-actions">
                                                    <a href="<?php 
                echo esc_url( admin_url( 'post.php?post=' . absint( $product->ID ) . '&action=edit' ) );
                ?>"
                                                        class="gspsync-btn gspsync-btn-small">
                                                        <span class="dashicons dashicons-edit"></span>
                                                        <?php 
                echo esc_html__( 'Edit', 'gold-silver-price-sync' );
                ?>
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php 
            }
            ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php 
        } else {
            ?>
                            <div class="gspsync-empty-state">
                                <span class="dashicons dashicons-info"></span>
                                <p><?php 
            echo esc_html__( 'No metal products found.', 'gold-silver-price-sync' );
            ?></p>
                                <p><small><?php 
            echo esc_html__( 'Products are automatically detected if they contain "gold"/"oro" or "silver"/"argento" in their name, or if marked manually.', 'gold-silver-price-sync' );
            ?></small></p>
                            </div>
                        <?php 
        }
        ?>
                    </div>
                </div>
            </div>
        </div>
    <?php 
    }

    /**
     * Add product metabox
     */
    public function add_product_metabox() {
        add_meta_box(
            'gspsync_product_settings',
            __( 'Gold & Silver Price Sync Settings', 'gold-silver-price-sync' ),
            array($this, 'product_metabox_callback'),
            'product',
            'side',
            'default'
        );
    }

    /**
     * Product metabox callback
     */
    public function product_metabox_callback( $post ) {
        wp_nonce_field( 'gspsync_product_meta', 'gspsync_product_nonce' );
        $metal_type = get_post_meta( $post->ID, '_gspsync_metal_type', true );
        // Legacy support
        if ( empty( $metal_type ) && get_post_meta( $post->ID, '_is_gold_product', true ) === 'yes' ) {
            $metal_type = 'gold';
        }
        $purity = get_post_meta( $post->ID, '_gspsync_purity', true );
        if ( empty( $purity ) ) {
            $purity = get_post_meta( $post->ID, '_gold_purity', true );
            // Legacy
        }
        $weight_grams = get_post_meta( $post->ID, '_gspsync_weight_grams', true );
        if ( empty( $weight_grams ) ) {
            $weight_grams = get_post_meta( $post->ID, '_peso_grammi', true );
            // Legacy
        }
        $markup = get_post_meta( $post->ID, '_gspsync_markup', true );
        if ( $markup === '' || $markup === false ) {
            $markup = get_post_meta( $post->ID, '_gold_markup', true );
            // Legacy
        }
        $product = wc_get_product( $post->ID );
        $is_variable = $product && $product->is_type( 'variable' );
        $updater = new GSPSYNC_Metal_Price_Updater();
        ?>
        <table style="width: 100%;">
            <tr>
                <td>
                    <label><strong><?php 
        esc_html_e( 'Metal type:', 'gold-silver-price-sync' );
        ?></strong></label><br>
                    <select name="_gspsync_metal_type" id="gspsync-metal-type" style="width: 100%;">
                        <option value=""><?php 
        esc_html_e( 'Not a metal product', 'gold-silver-price-sync' );
        ?></option>
                        <option value="gold" <?php 
        selected( $metal_type, 'gold' );
        ?>><?php 
        esc_html_e( 'Gold (XAU)', 'gold-silver-price-sync' );
        ?></option>
                        <option value="silver" <?php 
        selected( $metal_type, 'silver' );
        ?>><?php 
        esc_html_e( 'Silver (XAG)', 'gold-silver-price-sync' );
        ?></option>
                    </select>
                </td>
            </tr>

            <?php 
        if ( !$is_variable ) {
            ?>
                <tr>
                    <td>
                        <label><?php 
            esc_html_e( 'Weight in grams:', 'gold-silver-price-sync' );
            ?></label><br>
                        <input type="number" name="_gspsync_weight_grams" value="<?php 
            echo esc_attr( $weight_grams );
            ?>"
                            step="0.01" min="0" style="width: 100%;" placeholder="e.g. 5.5" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <label><?php 
            /* translators: %s: currency symbol, e.g. $ */
            printf( esc_html__( 'Fixed markup (%s):', 'gold-silver-price-sync' ), esc_html( GSPSYNC_Currency::get_symbol_text() ) );
            ?></label><br>
                        <input type="number" name="_gspsync_markup" value="<?php 
            echo esc_attr( $markup );
            ?>" step="0.01" min="0" style="width: 100%;" placeholder="e.g. 10.00" />
                    </td>
                </tr>
            <?php 
        } else {
            ?>
                <tr>
                    <td>
                        <div style="background: #f9f9f9; padding: 10px; border-radius: 3px; margin: 10px 0;">
                            <strong><?php 
            esc_html_e( 'Variable Product', 'gold-silver-price-sync' );
            ?></strong><br>
                            <small style="color: #666;">
                                <?php 
            esc_html_e( 'Configure weight in individual variations. Go to "Variations" to set the weight of each variant.', 'gold-silver-price-sync' );
            ?>
                            </small>
                        </div>
                    </td>
                </tr>
            <?php 
        }
        ?>

            <tr>
                <td>
                    <label><?php 
        esc_html_e( 'Purity (optional):', 'gold-silver-price-sync' );
        ?></label><br>
                    <select name="_gspsync_purity" id="gspsync-purity-select" style="width: 100%;">
                        <option value=""><?php 
        esc_html_e( 'Not specified', 'gold-silver-price-sync' );
        ?></option>
                        <!-- Gold purities -->
                        <optgroup label="<?php 
        echo esc_attr__( 'Gold', 'gold-silver-price-sync' );
        ?>" class="gspsync-purity-gold">
                            <option value="24k" <?php 
        selected( $purity, '24k' );
        ?>>24k (99.9%)</option>
                            <option value="22k" <?php 
        selected( $purity, '22k' );
        ?>>22k (91.7%)</option>
                            <option value="18k" <?php 
        selected( $purity, '18k' );
        ?>>18k (75%)</option>
                            <option value="14k" <?php 
        selected( $purity, '14k' );
        ?>>14k (58.3%)</option>
                            <option value="10k" <?php 
        selected( $purity, '10k' );
        ?>>10k (41.7%)</option>
                        </optgroup>
                        <!-- Silver purities -->
                        <optgroup label="<?php 
        echo esc_attr__( 'Silver', 'gold-silver-price-sync' );
        ?>" class="gspsync-purity-silver">
                            <option value=".999" <?php 
        selected( $purity, '.999' );
        ?>>.999 (Fine Silver 99.9%)</option>
                            <option value=".925" <?php 
        selected( $purity, '.925' );
        ?>>.925 (Sterling 92.5%)</option>
                            <option value=".900" <?php 
        selected( $purity, '.900' );
        ?>>.900 (90%)</option>
                            <option value=".800" <?php 
        selected( $purity, '.800' );
        ?>>.800 (80%)</option>
                        </optgroup>
                    </select>
                </td>
            </tr>
        </table>

        <?php 
        if ( $is_variable ) {
            ?>
            <div style="margin-top: 15px; padding: 10px; background: #e7f3ff; border-left: 4px solid #0073aa;">
                <strong><?php 
            esc_html_e( 'Variation Setup:', 'gold-silver-price-sync' );
            ?></strong><br>
                <small>
                    <?php 
            esc_html_e( '1. Go to the "Variations" section', 'gold-silver-price-sync' );
            ?><br>
                    <?php 
            esc_html_e( '2. For each variation, enter weight in grams', 'gold-silver-price-sync' );
            ?><br>
                    <?php 
            esc_html_e( '3. Price will be calculated automatically', 'gold-silver-price-sync' );
            ?>
                </small>
            </div>
        <?php 
        }
        ?>

        <p style="font-size: 11px; color: #666; margin-top: 10px;">
            <?php 
        esc_html_e( 'The dynamic price will replace the list price when the product is displayed in the store.', 'gold-silver-price-sync' );
        ?>
        </p>
    <?php 
    }

    /**
     * Save product metabox data
     */
    public function save_product_metabox( $post_id ) {
        if ( !isset( $_POST['gspsync_product_nonce'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['gspsync_product_nonce'] ) ), 'gspsync_product_meta' ) ) {
            return;
        }
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }
        if ( !current_user_can( 'edit_post', $post_id ) ) {
            return;
        }
        // Save metal type
        if ( isset( $_POST['_gspsync_metal_type'] ) && !empty( $_POST['_gspsync_metal_type'] ) ) {
            $metal = sanitize_text_field( wp_unslash( $_POST['_gspsync_metal_type'] ) );
            if ( in_array( $metal, array('gold', 'silver'), true ) ) {
                update_post_meta( $post_id, '_gspsync_metal_type', $metal );
            }
        } else {
            delete_post_meta( $post_id, '_gspsync_metal_type' );
            delete_post_meta( $post_id, '_is_gold_product' );
        }
        // Save weight
        if ( isset( $_POST['_gspsync_weight_grams'] ) && !empty( $_POST['_gspsync_weight_grams'] ) ) {
            $weight = floatval( $_POST['_gspsync_weight_grams'] );
            if ( $weight > 0 ) {
                update_post_meta( $post_id, '_gspsync_weight_grams', $weight );
            }
        } else {
            delete_post_meta( $post_id, '_gspsync_weight_grams' );
            delete_post_meta( $post_id, '_peso_grammi' );
        }
        // Save markup
        if ( isset( $_POST['_gspsync_markup'] ) && $_POST['_gspsync_markup'] !== '' ) {
            update_post_meta( $post_id, '_gspsync_markup', floatval( $_POST['_gspsync_markup'] ) );
        } else {
            delete_post_meta( $post_id, '_gspsync_markup' );
            delete_post_meta( $post_id, '_gold_markup' );
        }
        // Save purity
        if ( isset( $_POST['_gspsync_purity'] ) && !empty( $_POST['_gspsync_purity'] ) ) {
            $purity = sanitize_text_field( wp_unslash( $_POST['_gspsync_purity'] ) );
            update_post_meta( $post_id, '_gspsync_purity', $purity );
        } else {
            delete_post_meta( $post_id, '_gspsync_purity' );
            delete_post_meta( $post_id, '_gold_purity' );
        }
    }

    /**
     * Save variation data
     */
    public function save_variation_data( $variation_id, $product ) {
        if ( !isset( $_POST['woocommerce_meta_nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['woocommerce_meta_nonce'] ) ), 'woocommerce_save_data' ) ) {
            return;
        }
        if ( !current_user_can( 'edit_products' ) ) {
            return;
        }
        $actual_variation_id = absint( $variation_id );
        $parent_id = 0;
        if ( $product instanceof WC_Product_Variation ) {
            $actual_variation_id = $product->get_id();
            $parent_id = $product->get_parent_id();
        } elseif ( is_numeric( $product ) ) {
            $parent_id = absint( $product );
        } else {
            $variation = wc_get_product( $variation_id );
            if ( $variation && $variation->is_type( 'variation' ) ) {
                $parent_id = $variation->get_parent_id();
            }
        }
        if ( $parent_id > 0 && !current_user_can( 'edit_post', $parent_id ) ) {
            return;
        }
        // Check parent is a metal product
        $parent_product = wc_get_product( $parent_id );
        if ( !$parent_product ) {
            return;
        }
        $updater = new GSPSYNC_Metal_Price_Updater();
        $metal_type = $updater->is_metal_product( $parent_product );
        if ( !$metal_type ) {
            return;
        }
        // Save weight
        if ( isset( $_POST['_gspsync_weight_grams'][$actual_variation_id] ) && !empty( $_POST['_gspsync_weight_grams'][$actual_variation_id] ) ) {
            $weight = floatval( $_POST['_gspsync_weight_grams'][$actual_variation_id] );
            if ( $weight > 0.01 && $weight <= 10000 ) {
                update_post_meta( $actual_variation_id, '_gspsync_weight_grams', $weight );
            }
        }
        // Save purity
        if ( isset( $_POST['_gspsync_purity'][$actual_variation_id] ) && !empty( $_POST['_gspsync_purity'][$actual_variation_id] ) ) {
            $purity = sanitize_text_field( wp_unslash( $_POST['_gspsync_purity'][$actual_variation_id] ) );
            update_post_meta( $actual_variation_id, '_gspsync_purity', $purity );
        } else {
            // Inherit from parent
            $parent_purity = get_post_meta( $parent_id, '_gspsync_purity', true );
            if ( !empty( $parent_purity ) ) {
                update_post_meta( $actual_variation_id, '_gspsync_purity', $parent_purity );
            }
        }
        // Save markup
        if ( isset( $_POST['_gspsync_markup'][$actual_variation_id] ) && $_POST['_gspsync_markup'][$actual_variation_id] !== '' ) {
            $markup = floatval( $_POST['_gspsync_markup'][$actual_variation_id] );
            if ( $markup >= 0 && $markup <= 100000 ) {
                update_post_meta( $actual_variation_id, '_gspsync_markup', $markup );
            }
        } else {
            delete_post_meta( $actual_variation_id, '_gspsync_markup' );
            delete_post_meta( $actual_variation_id, '_gold_markup' );
        }
        $updater->clear_price_caches( $actual_variation_id );
    }

    /**
     * Add custom fields to variations
     */
    public function add_variation_fields( $loop, $variation_data, $variation ) {
        $variation_id = 0;
        $parent_id = 0;
        if ( $variation instanceof WC_Product_Variation ) {
            $variation_id = $variation->get_id();
            $parent_id = $variation->get_parent_id();
        } elseif ( $variation instanceof WP_Post ) {
            $variation_id = $variation->ID;
            $parent_id = $variation->post_parent;
        } else {
            $variation_id = 'temp_' . $loop;
            $parent_id = get_the_ID();
        }
        $parent_product = wc_get_product( $parent_id );
        if ( !$parent_product ) {
            return;
        }
        $updater = new GSPSYNC_Metal_Price_Updater();
        $metal_type = $updater->is_metal_product( $parent_product );
        if ( !$metal_type ) {
            return;
        }
        // Get data (new or legacy)
        $weight_grams = '';
        $purity = '';
        $markup = '';
        if ( $variation_id && !is_string( $variation_id ) ) {
            $weight_grams = get_post_meta( $variation_id, '_gspsync_weight_grams', true );
            if ( empty( $weight_grams ) ) {
                $weight_grams = get_post_meta( $variation_id, '_peso_grammi', true );
            }
            $purity = get_post_meta( $variation_id, '_gspsync_purity', true );
            if ( empty( $purity ) ) {
                $purity = get_post_meta( $variation_id, '_gold_purity', true );
            }
            $markup = get_post_meta( $variation_id, '_gspsync_markup', true );
            if ( $markup === '' || $markup === false ) {
                $markup = get_post_meta( $variation_id, '_gold_markup', true );
            }
        }
        if ( empty( $purity ) ) {
            $purity = get_post_meta( $parent_id, '_gspsync_purity', true );
            if ( empty( $purity ) ) {
                $purity = get_post_meta( $parent_id, '_gold_purity', true );
            }
        }
        $metal_labels = array(
            'gold'   => __( 'Gold', 'gold-silver-price-sync' ),
            'silver' => __( 'Silver', 'gold-silver-price-sync' ),
        );
        $all_purities = $updater->get_default_purities();
        ?>
        <div class="gspsync-variation-fields" style="padding: 10px; background: #f9f9f9; margin: 10px 0; border-radius: 3px;">
            <h4 style="margin: 0 0 10px 0; color: #0073aa;">
                <span class="dashicons dashicons-admin-generic"></span>
                <?php 
        /* translators: %s: metal name (Gold or Silver) */
        printf( esc_html__( 'Gold & Silver Price Sync - %s', 'gold-silver-price-sync' ), esc_html( ( isset( $metal_labels[$metal_type] ) ? $metal_labels[$metal_type] : ucfirst( $metal_type ) ) ) );
        ?>
            </h4>

            <div style="display: flex; gap: 15px; flex-wrap: wrap;">
                <div style="flex: 1; min-width: 200px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: bold;">
                        <?php 
        esc_html_e( 'Weight (grams):', 'gold-silver-price-sync' );
        ?>
                    </label>
                    <input type="number"
                        name="_gspsync_weight_grams[<?php 
        echo esc_attr( $variation_id );
        ?>]"
                        value="<?php 
        echo esc_attr( $weight_grams );
        ?>"
                        step="0.01" min="0" style="width: 100%;" placeholder="e.g. 5.5" />
                </div>

                <div style="flex: 1; min-width: 200px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: bold;">
                        <?php 
        /* translators: %s: currency symbol, e.g. $ */
        printf( esc_html__( 'Fixed markup (%s):', 'gold-silver-price-sync' ), esc_html( GSPSYNC_Currency::get_symbol_text() ) );
        ?>
                    </label>
                    <input type="number"
                        name="_gspsync_markup[<?php 
        echo esc_attr( $variation_id );
        ?>]"
                        value="<?php 
        echo esc_attr( $markup );
        ?>"
                        step="0.01" min="0" style="width: 100%;" placeholder="e.g. 10.00" />
                </div>

                <?php 
        if ( !empty( $all_purities[$metal_type] ) ) {
            ?>
                <div style="flex: 1; min-width: 200px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: bold;">
                        <?php 
            esc_html_e( 'Purity:', 'gold-silver-price-sync' );
            ?>
                    </label>
                    <select name="_gspsync_purity[<?php 
            echo esc_attr( $variation_id );
            ?>]" style="width: 100%;">
                        <option value=""><?php 
            esc_html_e( 'Inherit from parent', 'gold-silver-price-sync' );
            ?></option>
                        <?php 
            foreach ( $all_purities[$metal_type] as $p_key => $p_factor ) {
                ?>
                            <option value="<?php 
                echo esc_attr( $p_key );
                ?>" <?php 
                selected( $purity, $p_key );
                ?>>
                                <?php 
                echo esc_html( $p_key . ' (' . number_format( $p_factor * 100, 1 ) . '%)' );
                ?>
                            </option>
                        <?php 
            }
            ?>
                    </select>
                </div>
                <?php 
        }
        ?>
            </div>

            <!-- Live Price Preview -->
            <div class="gspsync-live-price-preview"
                 id="gspsync-price-preview-<?php 
        echo esc_attr( $variation_id );
        ?>"
                 data-variation-id="<?php 
        echo esc_attr( $variation_id );
        ?>"
                 data-parent-id="<?php 
        echo esc_attr( $parent_id );
        ?>"
                 data-metal-type="<?php 
        echo esc_attr( $metal_type );
        ?>"
                 style="margin-top: 10px; padding: 10px; background: #e7f3ff; border-radius: 4px; border-left: 3px solid #0073aa;">
                <?php 
        if ( !empty( $weight_grams ) && !is_string( $variation_id ) ) {
            ?>
                    <div class="gspsync-price-display">
                        <strong style="color: #0073aa;"><?php 
            esc_html_e( 'Estimated price:', 'gold-silver-price-sync' );
            ?></strong>
                        <span class="gspsync-calculated-price" style="font-size: 1.1em; font-weight: bold; color: #2e7d32;">
                            <?php 
            try {
                $wc_variation = wc_get_product( $variation_id );
                if ( $wc_variation ) {
                    $est_price = $updater->calculate_price_by_weight( $wc_variation );
                    echo ( $est_price !== false ? esc_html( GSPSYNC_Currency::format( $est_price ) ) : esc_html__( 'N/A', 'gold-silver-price-sync' ) );
                } else {
                    echo esc_html__( 'N/A', 'gold-silver-price-sync' );
                }
            } catch ( Exception $e ) {
                echo esc_html__( 'Error', 'gold-silver-price-sync' );
            }
            ?>
                        </span>
                    </div>
                <?php 
        } else {
            ?>
                    <div class="gspsync-price-placeholder" style="color: #666; font-style: italic;">
                        <?php 
            esc_html_e( 'Enter a weight to see the estimated price', 'gold-silver-price-sync' );
            ?>
                    </div>
                <?php 
        }
        ?>
                <div class="gspsync-price-breakdown" style="margin-top: 5px; font-size: 0.85em; color: #666; display: none;"></div>
            </div>
        </div>
<?php 
    }

    /**
     * Check if product is a metal product (internal helper)
     */
    private function is_metal_product( $product ) {
        $updater = new GSPSYNC_Metal_Price_Updater();
        return $updater->is_metal_product( $product );
    }

}
