<?php

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

// Hardcoded common API key for all users.
define('PMRCGOLD_API_KEY', 'ff84a4ed8dfbf88224b777d554fed2de');
define('PMRCGOLD_API_URL', 'https://portal.preciousuite.com/api/metal-rate');

function pmrcgold_ApiSettingsPageMenu($hook)
{
    // Ensure the key is always saved in DB.
    $stored_key = get_option('pmrcgold_api_key', '');
    if ($stored_key !== PMRCGOLD_API_KEY) {
        update_option('pmrcgold_api_key', PMRCGOLD_API_KEY);
    }

    $masked_key = substr(PMRCGOLD_API_KEY, 0, 6)
        . str_repeat('*', max(0, strlen(PMRCGOLD_API_KEY) - 10))
        . substr(PMRCGOLD_API_KEY, -4);
    ?>
    <div class="wrap preciousuite-wrap preciousuite-dashboard preciousuite-gold-price">
        <div class="preciousuite-dashboard-shell">
            <?php pmrcgold_render_dashboard_nav('gold-price-api-settings'); ?>
            <main class="preciousuite-dashboard-main preciousuite-setting-page" id="metal-rate-chart-api-settings">
                <section class="preciousuite-dashboard-hero">
                    <h1><?php esc_html_e('API Settings', 'preciousuite-metal-rate-charts'); ?></h1>
                    <p><?php esc_html_e('Your plugin is connected to the Preciousuite Metal Rate API. The API key is pre-configured and cannot be changed.', 'preciousuite-metal-rate-charts'); ?>
                    </p>
                </section>

                <div class="preciousuite form-wrap metal-rate-chart-api" id="preciousuite-container">
                    <div class="preciousuite-fields-wrapper api-settings-fields-wrapper">
                        <div class="preciousuite-field">
                            <label class="preciousuite-label" for="pmrcgold_api_key">
                                <?php echo wp_kses_post(__('API Key', 'preciousuite-metal-rate-charts')); ?>
                            </label>
                            <input type="text" id="pmrcgold_api_key" value="<?php echo esc_attr($masked_key); ?>"
                                class="preciousuite-input" readonly="readonly" disabled="disabled"
                                style="background: #f0f0f1; cursor: not-allowed; opacity: 0.7; user-select: none; pointer-events: none;">
                            <small class="preciousuite-widget-hint">
                                <?php esc_html_e('This API key is pre-configured by Preciousuite.', 'preciousuite-metal-rate-charts'); ?>
                            </small>
                        </div>
                    </div>
                </div>
            </main>
            <?php pmrcgold_render_dashboard_sidebar(); ?>
        </div>
    </div>
    <script>
        (function () {
            var inp = document.getElementById('pmrcgold_api_key');
            if (inp) {
                inp.setAttribute('readonly', 'readonly');
                inp.setAttribute('disabled', 'disabled');
                inp.addEventListener('focus', function (e) { e.target.blur(); });
                inp.addEventListener('keydown', function (e) { e.preventDefault(); });
                inp.addEventListener('paste', function (e) { e.preventDefault(); });
                inp.addEventListener('cut', function (e) { e.preventDefault(); });
                inp.addEventListener('contextmenu', function (e) { e.preventDefault(); });
            }
        })();
    </script>
    <?php
}

// ── Cron setup ────────────────────────────────────────────────

function pmrcgold_setup_daily_cron()
{
    if (!wp_next_scheduled('pmrcgold_daily_price_fetch')) {
        $time = strtotime('tomorrow 01:00:00');
        wp_schedule_event($time, 'daily', 'pmrcgold_daily_price_fetch');
    }
}

function pmrcgold_clear_daily_cron()
{
    $timestamp = wp_next_scheduled('pmrcgold_daily_price_fetch');
    if ($timestamp) {
        wp_unschedule_event($timestamp, 'pmrcgold_daily_price_fetch');
    }

    // Also clear old timeframe cron if it still exists.
    $tf_timestamp = wp_next_scheduled('pmrcgold_timeframe_price_fetch');
    if ($tf_timestamp) {
        wp_unschedule_event($tf_timestamp, 'pmrcgold_timeframe_price_fetch');
    }

    // Delete all plugin options for a fresh start on next activation
    delete_option('pmrcgold_api_key');
    delete_option('pmrcgold_last_api_response');
    delete_option('pmrcgold_price_logs');
    delete_option('pmrcgold_timeframe_logs');
    delete_option('pmrcgold_last_timeframe_response');

    // Delete widget settings
    delete_option('widget1_metals');
    delete_option('widget1_currencies');
    delete_option('widget1_enabled');

    delete_option('widget2_metals');
    delete_option('widget2_currencies');

    delete_option('widget3_metals');
    delete_option('widget3_currencies');

    delete_option('widget4_metals');
    delete_option('widget4_currencies');
}

add_action('pmrcgold_daily_price_fetch', 'pmrcgold_fetch_metal_prices');

// ── Main API fetch ────────────────────────────────────────────

function pmrcgold_fetch_metal_prices()
{
    $api_key = PMRCGOLD_API_KEY;

    // Ensure key is stored in DB for task-list checks.
    if (get_option('pmrcgold_api_key', '') !== $api_key) {
        update_option('pmrcgold_api_key', $api_key);
    }

    $body_payload = wp_json_encode(array(
        'x-api-key' => $api_key,
        'metals' => 'XAU,XAG,XPT',
        'weight_unit' => 'gram',
        'base' => 'USD',
        'currencies' => 'EUR,GBP,JPY,AUD,CAD,CHF,CNY,INR,AED',
        'interval' => 1440,
    ));

    $response = wp_remote_post(PMRCGOLD_API_URL, array(
        'headers' => array(
            'Content-Type' => 'application/json',
        ),
        'body' => $body_payload,
        'timeout' => 30,
    ));

    if (is_wp_error($response)) {
        return false;
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        return false;
    }

    // Transform response to include 'rates' object for backwards compatibility with widgets
    if (isset($data['success']) && $data['success']) {
        $rates = array();

        // Add currencies to rates
        if (!empty($data['currencies']) && is_array($data['currencies'])) {
            foreach ($data['currencies'] as $c) {
                if (isset($c['short_name'], $c['price'])) {
                    $rates[$c['short_name']] = (float) $c['price'];
                }
            }
        }

        // Add metals to rates
        if (!empty($data['data']) && is_array($data['data'])) {
            foreach ($data['data'] as $m) {
                if (isset($m['short_name'], $m['price']) && (float) $m['price'] > 0) {
                    $price = (float) $m['price'];
                    $rates['USD' . $m['short_name']] = $price;
                    $rates[$m['short_name']] = $price;
                }
            }
        }

        $data['rates'] = $rates;
    }

    update_option('pmrcgold_last_api_response', $data);

    // Save to daily price logs.
    $logs = get_option('pmrcgold_price_logs', array());

    $new_log = array(
        'timestamp' => current_time('mysql'),
        'date' => gmdate('Y-m-d H:i:s'),
        'response' => $data,
    );

    array_unshift($logs, $new_log);
    $logs = array_slice($logs, 0, 50);

    update_option('pmrcgold_price_logs', $logs);

    return $data;
}

// ── First-time fetch on plugin activation ─────────────────────

function pmrcgold_activation_fetch()
{
    // Save the API key to DB on activation.
    update_option('pmrcgold_api_key', PMRCGOLD_API_KEY);

    // Only fetch if we don't already have data.
    $existing = get_option('pmrcgold_last_api_response', false);
    if (empty($existing)) {
        pmrcgold_fetch_metal_prices();
    }
}