<?php

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

/** Register Widget 3 Shortcode */

/*function pmrcgold_widget3_shortcode($atts) {
    $metals = (array) get_option('widget3_metals', ['platinum']);
    $currencies = (array) get_option('widget3_currencies', ['USD']);

    if (empty($metals) || empty($currencies)) {
        return '';
    }

    $logs = get_option('pmrcgold_price_logs', []);
    $latest_response = [];

    if (!empty($logs)) {
        $today = date('Y-m-d');
        $today_logs = array_filter($logs, function($log) use ($today) {
            return isset($log['date']) && strpos($log['date'], $today) === 0;
        });

        if (!empty($today_logs)) {
            $latest_today_log = reset($today_logs);
            $latest_response = $latest_today_log['response'] ?? [];
        } else {
            $latest_log = reset($logs);
            $latest_response = $latest_log['response'] ?? [];
        }
    }

    $rates = isset($latest_response['rates']) && is_array($latest_response['rates']) ? $latest_response['rates'] : [];
    $base = isset($latest_response['base']) ? $latest_response['base'] : 'USD';

    if (empty($rates)) {
        return '';
    }

    $metal_codes = [
        'gold' => 'XAU',
        'silver' => 'XAG',
        'platinum' => 'XPT',
        'palladium' => 'XPD',
    ];

    $metals = array_values(array_filter($metals, function($m) use ($metal_codes) {
        return isset($metal_codes[$m]);
    }));

    if (empty($metals)) {
        return '';
    }

    $allowed_currencies = array_values(array_filter($currencies, function($c) use ($rates, $base) {
        return $c === $base || isset($rates[$c]);
    }));

    if (empty($allowed_currencies)) {
        $allowed_currencies = [$base];
    }

    $label_map = [
        'gold' => 'Gold',
        'silver' => 'Silver',
        'platinum' => 'Platinum',
        'palladium' => 'Palladium',
    ];

    $instance_id = 'pmrcgold-widget3-' . substr(md5(uniqid('', true)), 0, 12);

    wp_enqueue_style(
        'pmrcgold-widget3',
        PMRCGOLD_ASSETS_URL . 'css/widget3.css',
        array(),
        '1.0.0'
    );
    wp_enqueue_script(
        'pmrcgold-widget3',
        PMRCGOLD_ASSETS_URL . 'js/widget3.js',
        array(),
        '1.0.0',
        true
    );

    $widget3_data = [
        'base' => $base,
        'latest_rates' => $rates,
        'logs' => $logs,
        'currencies' => $allowed_currencies,
        'metals' => $metals,
    ];

    ob_start();
    ?>
    <div class="pmrcgold-widget3" id="<?php echo esc_attr($instance_id); ?>">
        <div class="pmrcgold-widget3__header">
            <h3 class="pmrcgold-widget3__title"><?php echo esc_html__('Charts', 'preciousuite-metal-rate-charts'); ?></h3>
            <div class="pmrcgold-widget3__currency">
                <div class="pmrcgold-widget3__currency-wrap">
                    <select>
                        <?php foreach ($allowed_currencies as $c) : ?>
                            <option value="<?php echo esc_attr($c); ?>"><?php echo esc_html($c); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>

        <ul class="pmrcgold-widget3__list">
            <?php foreach ($metals as $metal) : ?>
                <li class="pmrcgold-widget3__row" data-metal="<?php echo esc_attr($metal); ?>">
                    <button type="button" class="pmrcgold-widget3__row-btn">
                        <span class="pmrcgold-widget3__chev"></span>
                        <span class="pmrcgold-widget3__metal"><?php echo esc_html($label_map[$metal] ?? ucfirst($metal)); ?></span>
                        <span class="pmrcgold-widget3__price">--</span>
                        <span class="pmrcgold-widget3__change down">
                            <span class="pmrcgold-widget3__arrow"></span>
                            <span class="pmrcgold-widget3__change-val">--</span>
                        </span>
                    </button>

                    <div class="pmrcgold-widget3__panel">
                        <div class="pmrcgold-widget3__chart">
                            <canvas></canvas>
                        </div>

                        <div class="pmrcgold-widget3__ranges">
                            <button type="button" class="pmrcgold-widget3__range-btn" data-days="1">1 day</button>
                            <button type="button" class="pmrcgold-widget3__range-btn" data-days="30">30 day</button>
                            <button type="button" class="pmrcgold-widget3__range-btn" data-days="90">90 day</button>
                            <button type="button" class="pmrcgold-widget3__range-btn" data-days="365">1 year</button>
                            <button type="button" class="pmrcgold-widget3__range-btn" data-days="1825">5 year</button>
                        </div>
                    </div>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>

    <script>
        window.pmrcgold_widget3_data = window.pmrcgold_widget3_data || {};
        window.pmrcgold_widget3_data[<?php echo wp_json_encode($instance_id); ?>] = <?php echo wp_json_encode($widget3_data); ?>;
    </script>
    <?php
    return ob_get_clean();
}*/

add_shortcode('pmrcgold_widget3', 'pmrcgold_widget3_shortcode');

function pmrcgold_widget3_shortcode($atts)
{
    $metals = (array) get_option('widget3_metals', ['platinum']);
    $currencies = (array) get_option('widget3_currencies', ['USD']);

    if (empty($metals) || empty($currencies)) {
        return '';
    }

    // Build rates_by_date from daily price logs instead of timeframe response
    $logs = get_option('pmrcgold_price_logs', []);
    $rates_by_date = [];
    $base = $currencies[0];
    $latest_rates = [];

    if (!empty($logs)) {
        foreach ($logs as $log) {
            if (isset($log['date'], $log['response']['rates']) && is_array($log['response']['rates'])) {
                $date_str = gmdate('Y-m-d', strtotime($log['date']));
                // Keep the most recent record for each date
                if (!isset($rates_by_date[$date_str])) {
                    $rates_by_date[$date_str] = $log['response']['rates'];
                }
            }
        }

        $base = $logs[0]['response']['base'] ?? 'USD';

        if (!empty($rates_by_date)) {
            $sorted_dates = array_keys($rates_by_date);
            sort($sorted_dates);
            $last_date = end($sorted_dates);
            $latest_rates = $rates_by_date[$last_date];
        }
    }

    if (empty($latest_rates)) {
        return '';
    }

    $metal_codes = [
        'gold' => 'XAU',
        'silver' => 'XAG',
        'platinum' => 'XPT',
        'palladium' => 'XPD',
    ];

    $metals = array_values(array_filter($metals, function ($m) use ($metal_codes) {
        return isset($metal_codes[$m]);
    }));

    if (empty($metals)) {
        return '';
    }

    // $allowed_currencies = array_values(array_filter($currencies, function ($c) use ($latest_rates, $base) {
    //     return $c === $base || isset($latest_rates[$c]);
    // }));


    $allowed_currencies = $currencies;

    if (empty($allowed_currencies)) {
        $allowed_currencies = [$base];
    }

    $label_map = [
        'gold' => 'Gold',
        'silver' => 'Silver',
        'platinum' => 'Platinum',
        'palladium' => 'Palladium',
    ];

    $instance_id = 'pmrcgold-widget3-' . substr(md5(uniqid('', true)), 0, 12);

    wp_enqueue_script(
        'chartjs',
        PMRCGOLD_ASSETS_URL . 'js/chart.min.js',
        array(),
        '4.4.1',
        true
    );

    wp_enqueue_script(
        'pmrcgold-widget3',
        PMRCGOLD_ASSETS_URL . 'js/widget3.js',
        array('chartjs'),
        '1.0.0',
        true
    );

    wp_enqueue_style(
        'pmrcgold-widget3',
        PMRCGOLD_ASSETS_URL . 'css/widget3.css',
        array(),
        '1.0.0'
    );
    // wp_enqueue_script(
    //     'pmrcgold-widget3',
    //     PMRCGOLD_ASSETS_URL . 'js/widget3.js',
    //     array(),
    //     '1.0.0',
    //     true
    // );

    $widget3_data = [
        'base' => $base,
        'latest_rates' => $latest_rates,
        'rates_by_date' => $rates_by_date,
        'logs' => [],
        'currencies' => $allowed_currencies,
        'metals' => $metals,
    ];

    ob_start();
    ?>
    <div class="pmrcgold-widget3" id="<?php echo esc_attr($instance_id); ?>">
        <div class="pmrcgold-widget3__header">
            <h3 class="pmrcgold-widget3__title"><?php echo esc_html__('Charts', 'preciousuite-metal-rate-charts'); ?></h3>
            <div class="pmrcgold-widget3__currency">
                <div class="pmrcgold-widget3__currency-wrap">
                    <select>
                        <?php foreach ($allowed_currencies as $c): ?>
                            <option value="<?php echo esc_attr($c); ?>"><?php echo esc_html($c); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>

        <ul class="pmrcgold-widget3__list">
            <?php foreach ($metals as $metal): ?>
                <li class="pmrcgold-widget3__row" data-metal="<?php echo esc_attr($metal); ?>">
                    <button type="button" class="pmrcgold-widget3__row-btn">
                        <span class="pmrcgold-widget3__chev"></span>
                        <span
                            class="pmrcgold-widget3__metal"><?php echo esc_html($label_map[$metal] ?? ucfirst($metal)); ?></span>
                        <span class="pmrcgold-widget3__price">--</span>
                        <span class="pmrcgold-widget3__change down">
                            <span class="pmrcgold-widget3__arrow"></span>
                            <span class="pmrcgold-widget3__change-val">--</span>
                        </span>
                    </button>

                    <div class="pmrcgold-widget3__panel">
                        <div class="pmrcgold-widget3__chart">
                            <canvas></canvas>
                        </div>

                        <div class="pmrcgold-widget3__ranges">
                            <button type="button" class="pmrcgold-widget3__range-btn" data-days="1">Today</button>
                            <button type="button" class="pmrcgold-widget3__range-btn" data-days="2">Yesterday</button>
                            <button type="button" class="pmrcgold-widget3__range-btn" data-days="5">5 Days</button>
                        </div>
                    </div>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>

    <script>
        window.pmrcgold_widget3_data = window.pmrcgold_widget3_data || {};
        window.pmrcgold_widget3_data[<?php echo wp_json_encode($instance_id); ?>] = <?php echo wp_json_encode($widget3_data); ?>;
    </script>
    <?php
    return ob_get_clean();
}

/** Register Widget 4 Shortcode */
add_shortcode('pmrcgold_widget4', 'pmrcgold_widget4_shortcode');

function pmrcgold_widget4_shortcode($atts)
{
    $metals = (array) get_option('widget4_metals', ['gold']);
    $currencies = (array) get_option('widget4_currencies', ['USD']);

    if (empty($metals) || empty($currencies)) {
        return '';
    }

    $logs = get_option('pmrcgold_price_logs', []);
    $api_response = [];

    if (!empty($logs)) {
        $today = gmdate('Y-m-d');
        $today_logs = array_filter($logs, function ($log) use ($today) {
            return isset($log['date']) && strpos($log['date'], $today) === 0;
        });

        if (!empty($today_logs)) {
            $latest_today_log = reset($today_logs);
            $api_response = $latest_today_log['response'] ?? [];
        } else {
            $latest_log = reset($logs);
            $api_response = $latest_log['response'] ?? [];
        }
    }

    $rates = isset($api_response['rates']) && is_array($api_response['rates']) ? $api_response['rates'] : [];
    $base = isset($api_response['base']) ? $api_response['base'] : 'USD';

    if (empty($rates)) {
        return '';
    }

    $metal_codes = [
        'gold' => 'XAU',
        'silver' => 'XAG',
        'platinum' => 'XPT',
        'palladium' => 'XPD',
    ];

    $metals = array_values(array_filter($metals, function ($m) use ($metal_codes) {
        return isset($metal_codes[$m]);
    }));

    if (empty($metals)) {
        return '';
    }

    $allowed_currencies = array_values(array_filter($currencies, function ($c) use ($rates, $base) {
        return $c === $base || isset($rates[$c]);
    }));

    if (empty($allowed_currencies)) {
        $allowed_currencies = [$base];
    }

    $symbols = [
        'USD' => '$',
        'EUR' => '€',
        'GBP' => '£',
        'JPY' => '¥',
        'INR' => '₹',
        'AUD' => 'A$',
        'CAD' => 'C$',
        'CHF' => 'Fr',
        'CNY' => '¥',
        'AED' => 'د.إ',
    ];

    $purities = [
        'gold' => [
            '24K' => ['purity' => 999.9],
            '22K' => ['purity' => 916],
            '21K' => ['purity' => 875],
            '18K' => ['purity' => 750],
            '14K' => ['purity' => 585],
            '9K' => ['purity' => 375],
            '8K' => ['purity' => 333],
        ],
        'silver' => [
            '999.9' => ['purity' => 999.9],
            '999' => ['purity' => 999],
            '958' => ['purity' => 958],
            '950' => ['purity' => 950],
            '935' => ['purity' => 935],
            '925' => ['purity' => 925],
            '900' => ['purity' => 900],
            '835' => ['purity' => 835],
            '800' => ['purity' => 800],
        ],
        'platinum' => [
            '999.5' => ['purity' => 999.5],
            '950' => ['purity' => 950],
            '900' => ['purity' => 900],
            '850' => ['purity' => 850],
            '750' => ['purity' => 750],
        ],
    ];

    $units = [
        'ounces' => ['label' => 'Ounces', 'multiplier' => 1],
        'grams' => ['label' => 'Grams', 'multiplier' => 1 / 31.1034768],
        'kilograms' => ['label' => 'Kilograms', 'multiplier' => 1000 / 31.1034768],
    ];

    wp_enqueue_style('pmrcgold-widget4', PMRCGOLD_ASSETS_URL . 'css/widget4.css', array(), '1.0.0');
    wp_enqueue_script('pmrcgold-widget4', PMRCGOLD_ASSETS_URL . 'js/widget4.js', array('jquery'), '1.0.0', true);

    $instance_id = 'pmrcgold-widget4-' . substr(md5(uniqid('', true)), 0, 12);

    ob_start();
    ?>
    <div class="pmrcgold-widget4 pmrcgold-metal-price-tabs" id="<?php echo esc_attr($instance_id); ?>">
        <div class="pmrcgold-metal-price-tabs__nav">
            <?php foreach ($units as $unit_key => $unit_conf): ?>
                <button type="button"
                    class="pmrcgold-metal-price-tabs__btn<?php echo $unit_key === 'ounces' ? ' active' : ''; ?>"
                    data-tab="<?php echo esc_attr($unit_key); ?>"><?php echo esc_html($unit_conf['label']); ?></button>
            <?php endforeach; ?>
        </div>

        <div class="pmrcgold-metal-price-tabs__panes">
            <?php foreach ($units as $unit_key => $unit_conf): ?>
                <div class="pmrcgold-metal-price-tabs__pane<?php echo $unit_key === 'ounces' ? ' active' : ''; ?>"
                    data-pane="<?php echo esc_attr($unit_key); ?>">
                    <?php foreach ($metals as $metal): ?>
                        <?php
                        $code = $metal_codes[$metal];
                        $usd_key = 'USD' . $code;
                        $price_usd_per_oz = null;

                        if (isset($rates[$usd_key])) {
                            $price_usd_per_oz = (float) $rates[$usd_key];
                        } elseif (isset($rates[$code]) && (float) $rates[$code] > 0) {
                            $price_usd_per_oz = (float) $rates[$code];
                        }
                        ?>

                        <?php if ($price_usd_per_oz !== null && isset($purities[$metal])): ?>
                            <div class="pmrcgold-metal-section">
                                <h4><?php echo esc_html(ucfirst($metal)); ?> Purity Prices</h4>
                                <table class="pmrcgold-metal-price-tabs__table">
                                    <thead>
                                        <tr>
                                            <th>Purity</th>
                                            <?php foreach ($allowed_currencies as $currency): ?>
                                                <th><?php echo esc_html($currency); ?></th>
                                            <?php endforeach; ?>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($purities[$metal] as $purity_key => $purity_info): ?>
                                            <tr>
                                                <td><strong><?php echo esc_html($purity_key); ?></strong></td>
                                                <?php foreach ($allowed_currencies as $currency): ?>
                                                    <?php
                                                    $price = '';
                                                    $adjusted_price_usd_per_oz = $price_usd_per_oz * ($purity_info['purity'] / 1000);
                                                    $price_in_usd = $adjusted_price_usd_per_oz * (float) $unit_conf['multiplier'];

                                                    if ($currency === 'USD') {
                                                        $price_val = $price_in_usd;
                                                    } elseif ($base === 'USD' && isset($rates[$currency])) {
                                                        $price_val = $price_in_usd * (float) $rates[$currency];
                                                    } elseif ($currency === $base) {
                                                        $price_val = $price_in_usd;
                                                    } elseif ($base !== 'USD' && isset($rates[$currency]) && isset($rates[$base]) && (float) $rates[$base] > 0) {
                                                        $price_val = ($price_in_usd / (float) $rates[$base]) * (float) $rates[$currency];
                                                    } else {
                                                        $price_val = $price_in_usd;
                                                    }

                                                    $sym = $symbols[$currency] ?? '';
                                                    $price = $sym . number_format_i18n($price_val, ($currency === 'JPY' || $currency === 'INR') ? 0 : 2);
                                                    ?>
                                                    <td><?php echo esc_html($price); ?></td>
                                                <?php endforeach; ?>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

add_shortcode('pmrcgold_widget2', 'pmrcgold_widget2_shortcode');

function pmrcgold_widget2_shortcode($atts)
{
    $metals = (array) get_option('widget2_metals', ['silver']);
    $currencies = (array) get_option('widget2_currencies', ['USD']);

    if (empty($metals) || empty($currencies)) {
        return '';
    }

    $logs = get_option('pmrcgold_price_logs', []);
    $api_response = [];

    if (!empty($logs)) {
        $today = gmdate('Y-m-d');
        $today_logs = array_filter($logs, function ($log) use ($today) {
            return isset($log['date']) && strpos($log['date'], $today) === 0;
        });

        if (!empty($today_logs)) {
            $latest_today_log = reset($today_logs);
            $api_response = $latest_today_log['response'] ?? [];
        } else {
            $latest_log = reset($logs);
            $api_response = $latest_log['response'] ?? [];
        }
    }

    $rates = isset($api_response['rates']) && is_array($api_response['rates']) ? $api_response['rates'] : [];
    $base = isset($api_response['base']) ? $api_response['base'] : 'USD';
    $timestamp = isset($api_response['timestamp']) ? (int) $api_response['timestamp'] : 0;

    if (empty($rates)) {
        return '';
    }

    $metal_codes = [
        'gold' => 'XAU',
        'silver' => 'XAG',
        'platinum' => 'XPT',
        'palladium' => 'XPD',
    ];

    $metals = array_values(array_filter($metals, function ($m) use ($metal_codes) {
        return isset($metal_codes[$m]);
    }));

    if (empty($metals)) {
        return '';
    }

    $allowed_currencies = array_values(array_filter($currencies, function ($c) use ($rates, $base) {
        return $c === $base || isset($rates[$c]);
    }));

    if (empty($allowed_currencies)) {
        $allowed_currencies = [$base];
    }

    $symbols = [
        'USD' => '$',
        'EUR' => '€',
        'GBP' => '£',
        'JPY' => '¥',
        'INR' => '₹',
        'AUD' => 'A$',
        'CAD' => 'C$',
        'CHF' => 'Fr',
        'CNY' => '¥',
        'AED' => 'د.إ',
    ];

    $units = [
        'ounces' => [
            'label' => 'Ounces',
            'multiplier' => 1,
        ],
        'grams' => [
            'label' => 'Grams',
            'multiplier' => 1 / 31.1034768,
        ],
        'kilograms' => [
            'label' => 'Kilograms',
            'multiplier' => 1000 / 31.1034768,
        ],
    ];

    $instance_id = 'pmrcgold-widget2';

    wp_enqueue_style(
        'pmrcgold-widget2',
        PMRCGOLD_ASSETS_URL . 'css/widget2.css',
        array(),
        '1.0.0'
    );

    $updated_text = '';
    if ($timestamp > 0) {
        $updated_text = wp_date('H:i d/m/y', $timestamp);
    }

    $label_map = [
        'gold' => 'Spot Gold Price',
        'silver' => 'Spot Silver Price',
        'platinum' => 'Spot Platinum Price',
        'palladium' => 'Spot Palladium Price',
    ];

    ob_start();
    ?>
    <div class="pmrcgold-metal-price-tabs" id="<?php echo esc_attr($instance_id); ?>">
        <div class="pmrcgold-metal-price-tabs__nav">
            <?php foreach ($units as $unit_key => $unit_conf): ?>
                <button type="button"
                    class="pmrcgold-metal-price-tabs__btn<?php echo $unit_key === 'ounces' ? ' active' : ''; ?>"
                    data-tab="<?php echo esc_attr($unit_key); ?>"><?php echo esc_html($unit_conf['label']); ?></button>
            <?php endforeach; ?>
        </div>

        <div class="pmrcgold-metal-price-tabs__panes">
            <?php foreach ($units as $unit_key => $unit_conf): ?>
                <div class="pmrcgold-metal-price-tabs__pane<?php echo $unit_key === 'ounces' ? ' active' : ''; ?>"
                    data-pane="<?php echo esc_attr($unit_key); ?>">
                    <table class="pmrcgold-metal-price-tabs__table">
                        <thead>
                            <tr>
                                <th></th>
                                <?php foreach ($allowed_currencies as $currency): ?>
                                    <th><?php echo esc_html($currency); ?></th>
                                <?php endforeach; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($metals as $metal): ?>
                                <?php
                                $code = $metal_codes[$metal];
                                $usd_key = 'USD' . $code;
                                $price_usd_per_oz = null;

                                if (isset($rates[$usd_key])) {
                                    $price_usd_per_oz = (float) $rates[$usd_key];
                                } elseif (isset($rates[$code]) && (float) $rates[$code] > 0) {
                                    $price_usd_per_oz = 1 / (float) $rates[$code];
                                }
                                ?>
                                <tr>
                                    <td><strong><?php echo esc_html($label_map[$metal] ?? ucfirst($metal)); ?></strong></td>
                                    <?php foreach ($allowed_currencies as $currency): ?>
                                        <?php
                                        $price = '';
                                        if ($price_usd_per_oz !== null) {
                                            $price_in_usd = $price_usd_per_oz * (float) $unit_conf['multiplier'];

                                            if ($currency === 'USD') {
                                                $price_val = $price_in_usd;
                                            } elseif ($base === 'USD' && isset($rates[$currency])) {
                                                $price_val = $price_in_usd * (float) $rates[$currency];
                                            } elseif ($currency === $base) {
                                                $price_val = $price_in_usd;
                                            } elseif ($base !== 'USD' && isset($rates[$currency]) && isset($rates[$base]) && (float) $rates[$base] > 0) {
                                                $price_val = ($price_in_usd / (float) $rates[$base]) * (float) $rates[$currency];
                                            } else {
                                                $price_val = $price_in_usd;
                                            }

                                            $sym = $symbols[$currency] ?? '';
                                            $price = $sym . number_format_i18n($price_val, 2);
                                        }
                                        ?>
                                        <td><?php echo esc_html($price); ?></td>
                                    <?php endforeach; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endforeach; ?>
        </div>

        <div class="pmrcgold-metal-price-tabs__footer">
            <div class="pmrcgold-metal-price-tabs__updated">
                <?php echo esc_html__('Last Price Updated: ', 'preciousuite-metal-rate-charts') . esc_html(gmdate('d-m-Y')); ?>
            </div>
        </div>
    </div>

    <script>
        (function () {
            var root = document.getElementById(<?php echo wp_json_encode($instance_id); ?>);
            if (!root) return;
            var btns = root.querySelectorAll('.pmrcgold-metal-price-tabs__btn');
            var panes = root.querySelectorAll('.pmrcgold-metal-price-tabs__pane');
            function activate(tab) {
                btns.forEach(function (b) { b.classList.toggle('active', b.getAttribute('data-tab') === tab); });
                panes.forEach(function (p) { p.classList.toggle('active', p.getAttribute('data-pane') === tab); });
            }
            btns.forEach(function (btn) {
                btn.addEventListener('click', function () { activate(btn.getAttribute('data-tab')); });
            });
            activate('ounces');
        })();
    </script>
    <?php
    return ob_get_clean();
}

/** Register Widget 1 Shortcode */
add_shortcode('pmrcgold_widget1', 'pmrcgold_widget1_shortcode');

function pmrcgold_widget1_shortcode($atts)
{
    // Get saved settings for Widget 1
    $title = get_option('widget1_title', 'Gold Price Widget');
    $metals = (array) get_option('widget1_metals', ['gold']);
    $currencies = (array) get_option('widget1_currencies', ['USD']);
    $enabled_options = (array) get_option('widget1_enabled', ['header', 'footer']);

    if (empty($metals) || empty($currencies)) {
        return '';
    }

    // Get today's latest price log, fallback to most recent if no today's log
    $logs = get_option('pmrcgold_price_logs', []);
    $api_response = [];
    $yesterday_response = [];

    if (!empty($logs)) {
        // First try to get today's logs
        $today = gmdate('Y-m-d');
        $today_logs = array_filter($logs, function ($log) use ($today) {
            return strpos($log['date'], $today) === 0;
        });

        if (!empty($today_logs)) {
            $latest_today_log = reset($today_logs);
            $api_response = $latest_today_log['response'];

            // Get yesterday's log for comparison
            $yesterday = gmdate('Y-m-d', strtotime('-1 day'));
            $yesterday_logs = array_filter($logs, function ($log) use ($yesterday) {
                return strpos($log['date'], $yesterday) === 0;
            });

            if (!empty($yesterday_logs)) {
                $latest_yesterday_log = reset($yesterday_logs);
                $yesterday_response = $latest_yesterday_log['response'];
            }
        } else {
            // If no today's log, use the most recent log as today
            $latest_log = reset($logs);
            $api_response = $latest_log['response'];

            // Use the second most recent as yesterday
            $logs_array = array_values($logs);
            if (isset($logs_array[1])) {
                $yesterday_response = $logs_array[1]['response'];
            }
        }
    }

    // Enqueue assets
    wp_enqueue_style('pmrcgold-widget-settings');
    wp_enqueue_script('pmrcgold-frontend', PMRCGOLD_ASSETS_URL . 'js/frontend.js', array('jquery'), '1.0.8', true);

    ob_start();
    ?>
    <style>
        <?php include PRECIOUSUITE_MRC_PATH . 'public/css/widget1.css'; ?>
    </style>
    <div class="pmrcgold-shortcode-widget-1">
        <div class="pmrcgold-widget-container">
            <div class="pmrcgold-widget-main">
                <div class="pmrcgold-currency-selector">
                    <select class="pmrcgold-currency-dropdown">
                        <?php foreach ($currencies as $currency): ?>
                            <option value="<?php echo esc_attr($currency); ?>"><?php echo esc_html($currency); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="pmrcgold-metals-display">
                    <?php foreach ($metals as $metal): ?>
                        <div class="pmrcgold-metal-badge" data-metal="<?php echo esc_attr($metal); ?>">
                            <span class="metal-name"><?php echo esc_html(ucfirst($metal)); ?> :</span>
                            <span class="metal-price">--</span>
                            <span class="metal-change">--</span>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Pass API data to JavaScript
        var pmrcgold_api_data = <?php echo wp_json_encode($api_response); ?>;
        var pmrcgold_yesterday_data = <?php echo wp_json_encode($yesterday_response); ?>;
        var pmrcgold_selected_metals = <?php echo wp_json_encode($metals); ?>;
        var pmrcgold_selected_currencies = <?php echo wp_json_encode($currencies); ?>;
    </script>
    <?php
    return ob_get_clean();
}

/** Auto-display Widget 1 in Header/Footer based on settings */
add_action('wp_head', 'pmrcgold_auto_display_widget1_header');

function pmrcgold_auto_display_widget1_header()
{
    $enabled_options = (array) get_option('widget1_enabled', []);
    if (in_array('header', $enabled_options)) {
        echo do_shortcode('[pmrcgold_widget1]');
    }
}

add_action('wp_footer', 'pmrcgold_auto_display_widget1_footer');

function pmrcgold_auto_display_widget1_footer()
{
    $enabled_options = (array) get_option('widget1_enabled', []);
    if (in_array('footer', $enabled_options)) {
        echo do_shortcode('[pmrcgold_widget1]');
    }
}

/** AJAX handler for Widget 1 Preview */
add_action('wp_ajax_pmrcgold_widget1_preview', 'pmrcgold_widget1_preview_handler');

function pmrcgold_widget1_preview_handler()
{
    // Get current form values from POST data, fallback to saved options
    // Verify nonce for security
    if (!check_ajax_referer('pmrcgold_widget1_nonce', 'nonce', false)) {
        wp_send_json_error('Invalid nonce');
        wp_die();
    }
    $metals = isset($_POST['metals']) ? array_map('sanitize_text_field', wp_unslash((array) $_POST['metals'])) : (array) get_option('widget1_metals', ['gold']);
    $currencies = isset($_POST['currencies']) ? array_map('sanitize_text_field', wp_unslash((array) $_POST['currencies'])) : (array) get_option('widget1_currencies', ['USD']);
    $enabled_options = isset($_POST['enabled']) ? array_map('sanitize_text_field', wp_unslash((array) $_POST['enabled'])) : (array) get_option('widget1_enabled', ['header', 'footer']);

    // Temporarily override the options for this preview using pre_option_ to bypass DB
    if (isset($_POST['metals'])) {
        add_filter('pre_option_widget1_metals', function () use ($metals) {
            return $metals;
        });
    }
    if (isset($_POST['currencies'])) {
        add_filter('pre_option_widget1_currencies', function () use ($currencies) {
            return $currencies;
        });
    }
    if (isset($_POST['enabled'])) {
        add_filter('pre_option_widget1_enabled', function () use ($enabled_options) {
            return $enabled_options;
        });
    }

    echo do_shortcode('[pmrcgold_widget1]');
    wp_die();
}

/** AJAX handler for Widget 2 Preview */
add_action('wp_ajax_pmrcgold_widget2_preview', 'pmrcgold_widget2_preview_handler');

function pmrcgold_widget2_preview_handler()
{
    // Get current form values from POST data, fallback to saved options
    // Verify nonce for security
    if (!check_ajax_referer('pmrcgold_widget2_nonce', 'nonce', false)) {
        wp_send_json_error('Invalid nonce');
        wp_die();
    }
    $metals = isset($_POST['metals']) ? array_map('sanitize_text_field', wp_unslash((array) $_POST['metals'])) : (array) get_option('widget2_metals', ['silver']);
    $currencies = isset($_POST['currencies']) ? array_map('sanitize_text_field', wp_unslash((array) $_POST['currencies'])) : (array) get_option('widget2_currencies', ['USD']);

    // Temporarily override the options for this preview using pre_option_ to bypass DB
    if (isset($_POST['metals'])) {
        add_filter('pre_option_widget2_metals', function () use ($metals) {
            return $metals;
        });
    }
    if (isset($_POST['currencies'])) {
        add_filter('pre_option_widget2_currencies', function () use ($currencies) {
            return $currencies;
        });
    }

    echo do_shortcode('[pmrcgold_widget2]');
    wp_die();
}

add_action('wp_ajax_pmrcgold_widget3_preview', 'pmrcgold_widget3_preview_handler');

function pmrcgold_widget3_preview_handler()
{
    // Get current form values from POST data, fallback to saved options
    // Verify nonce for security
    if (!check_ajax_referer('pmrcgold_widget3_nonce', 'nonce', false)) {
        wp_send_json_error('Invalid nonce');
        wp_die();
    }
    $metals = isset($_POST['metals']) ? array_map('sanitize_text_field', wp_unslash((array) $_POST['metals'])) : (array) get_option('widget3_metals', ['platinum']);
    $currencies = isset($_POST['currencies']) ? array_map('sanitize_text_field', wp_unslash((array) $_POST['currencies'])) : (array) get_option('widget3_currencies', ['USD']);

    // Temporarily override the options for this preview using pre_option_ to bypass DB
    if (isset($_POST['metals'])) {
        add_filter('pre_option_widget3_metals', function () use ($metals) {
            return $metals;
        });
    }
    if (isset($_POST['currencies'])) {
        add_filter('pre_option_widget3_currencies', function () use ($currencies) {
            return $currencies;
        });
    }

    echo do_shortcode('[pmrcgold_widget3]');
    wp_die();
}

add_action('wp_ajax_pmrcgold_widget4_preview', 'pmrcgold_widget4_preview_handler');

function pmrcgold_widget4_preview_handler()
{
    // Get current form values from POST data, fallback to saved options
    // Verify nonce for security
    if (!check_ajax_referer('pmrcgold_widget4_nonce', 'nonce', false)) {
        wp_send_json_error('Invalid nonce');
        wp_die();
    }
    $metals = isset($_POST['metals']) ? array_map('sanitize_text_field', wp_unslash((array) $_POST['metals'])) : (array) get_option('widget4_metals', ['gold']);
    $currencies = isset($_POST['currencies']) ? array_map('sanitize_text_field', wp_unslash((array) $_POST['currencies'])) : (array) get_option('widget4_currencies', ['USD']);

    // Temporarily override the options for this preview using pre_option_ to bypass DB
    if (isset($_POST['metals'])) {
        add_filter('pre_option_widget4_metals', function () use ($metals) {
            return $metals;
        });
    }
    if (isset($_POST['currencies'])) {
        add_filter('pre_option_widget4_currencies', function () use ($currencies) {
            return $currencies;
        });
    }

    echo do_shortcode('[pmrcgold_widget4]');
    wp_die();
}
