<?php

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

$provider = esc_attr(get_post_meta($post_id, 'fng_provider', true));
$fng_style = esc_attr(get_post_meta($post_id, 'fear-greed-style', true));
$last_update = esc_attr(get_post_meta($post_id, 'last-update', true));
$market_sentiment = esc_attr(get_post_meta($post_id, 'market-sentiment', true));
$background_color = esc_attr(get_post_meta($post_id, 'fng_back_color', true));
$arrow_color = esc_attr(get_post_meta($post_id, 'arrow_color', true));
$font_color = esc_attr(get_post_meta($post_id, 'fng_font_color', true));

// Fetch CoinMarketCap API data
if (!function_exists('fetch_data_from_cmc')) {
    function fetch_data_from_cmc() {
        $api_option = get_option("openexchange-api-settings");
        $api_key = $api_option['coinmarketcap_api'];

        if (empty($api_key)) {
            add_action('admin_notices', function () {
                echo '<div class="notice notice-error is-dismissible">
                        <p><strong>Error:</strong> Please add the CoinMarketCap API key in the plugin API settings.</p>
                      </div>';
            });
            return ;
        }
    
        $cached_data = get_transient('cmc_fng_data');
        if ($cached_data) {
            return $cached_data; 
        }
    
        $api_url = "https://pro-api.coinmarketcap.com/v3/fear-and-greed/historical?CMC_PRO_API_KEY={$api_key}";
    
        $response = wp_remote_get($api_url, [
            'headers' => ['User-Agent' => 'Mozilla/5.0 (compatible; WordPress Widget/1.0)'],
        ]);
    
        if (is_wp_error($response)) {
            error_log('API error: ' . $response->get_error_message());
            return ['error' => 'Unable to fetch data from API.'];
        }
    
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
    
        if (empty($data['data'])) {
            error_log('Invalid API response: ' . $body);
            return ['error' => 'Invalid API response.'];
        }
    
        set_transient('cmc_fng_data', $data['data'], 15 * MINUTE_IN_SECONDS); 
    
        return $data['data'];
    }
    
}

// Display CoinStats widget
if ($provider === 'coinstats') {
    $output = '<div id="fear-greed-widget-' . esc_attr($post_id) . '"  
                class="fear-greed-widget"
                data-fng-style="' . esc_attr($fng_style) . '" 
                data-background-color="' . esc_attr($background_color) . '" 
                data-arrow-color="' . esc_attr($arrow_color) . '" 
                data-font-color="' . esc_attr($font_color) . '" 
                data-market-sentiment="' . esc_attr($market_sentiment) . '" 
                data-last-update="' . esc_attr($last_update) . '">
          </div>';
    return $output;
}

// Display CMC Widget
elseif ($provider === 'cmc') {
    if (!function_exists('display_cmc_widget')) {
        function display_cmc_widget($data, $fng_style, $background_color, $font_color, $arrow_color, $market_sentiment, $post_id) {
            $data = is_string($data) ? unserialize($data) : $data;

               if (!is_array($data) || empty($data)) {
                  return 'Please enter the CoinMarketCap API key to run the Fear and Greed widget.';
               }
               
               $current = $data[0];

            $fear_and_greed_value = (int)$current['value'];
            $classification = $current['value_classification'];

            
            $centerX = 75;
            $centerY = 75            ;
            $radius = 66;
            
            if ($fear_and_greed_value >= 85) {
                $centerY = 68; 
                $radius = 55; 
            }
            elseif ($fear_and_greed_value >= 65) {
                $centerY = 71;
                            $radius = 59; 
            }

            
            $angle = 180 - ($fear_and_greed_value / 100) * 170; 
            $angle_rad = deg2rad($angle); 
            $cx = $centerX + $radius * cos($angle_rad);
            $cy = $centerY - $radius * sin($angle_rad); 
            ob_start();
            $output = '';
            $output .= '<div id="main-div-fng-' . esc_attr($post_id) . '" class="main-div-fng">'; // Main Wrapper Div
            $output .= '<div class="fng-meter" style="background: ' . esc_attr($background_color) . ';">'; // Meter Div
            $output .= '<div class="fng-svg-container-' . esc_attr($fng_style) . '">'; // SVG Container Div
            
            
            $output .= '<div class="fng-content-div-' . esc_attr($fng_style) . '">'; // Content Wrapper Div
            $output .= '<div class="fng-box-' . esc_attr($fng_style) . '">'; // Box Wrapper Div
            
            // SVG Content
            $output .= '<svg class="' . esc_attr($fng_style) . '" width="200" height="150" viewBox="0 0 150 50" xmlns="http://www.w3.org/2000/svg">';
            $output .= '<path d="M 13 68 A 59 59 0 0 1 20.7 38.86" stroke="#EA3943" stroke-width="6" stroke-linecap="round" fill="none"></path>';
            $output .= '<path d="M 25.25 32 A 59 59 0 0 1 49.14 13.61" stroke="#EA8C00" stroke-width="6" stroke-linecap="round" fill="none"></path>';
            $output .= '<path d="M 56.93 10.96 A 59 59 0 0 1 87.07 10.96" stroke="#F3D42F" stroke-width="6" stroke-linecap="round" fill="none"></path>';
            $output .= '<path d="M 94.86 13.61 A 59 59 0 0 1 118.75 32" stroke="#93D900" stroke-width="6" stroke-linecap="round" fill="none"></path>';
            $output .= '<path d="M 123.3 38.86 A 59 59 0 0 1 131 68" stroke="#16C784" stroke-width="6" stroke-linecap="round" fill="none"></path>';
            $output .= '<line x1="' . esc_attr($centerX) . '" y1="' . esc_attr($centerY) . '" x2="' . esc_attr($cx) . '" y2="' . esc_attr($cy) . '" stroke="#000" stroke-width="2" stroke-linecap="round" style="display:none;"></line>';
            $output .= '<circle cx="' . esc_attr($cx) . '" cy="' . esc_attr($cy) . '" r="7" fill="'.esc_attr($arrow_color) .'" stroke="'.esc_attr($background_color) .'" stroke-width="2"></circle>';
            $output .= '</svg>';
            
            // Values Display
            $output .= '<div class="fng-value-container-' . esc_attr($fng_style) . '">'; // Values Container
            $output .= '<h3 style="color:#34B349;">' . esc_html($fear_and_greed_value) . '</h3>';
            $output .= '<h3 style="color:#34B349;">' . esc_html($classification) . '</h3>';
            $output .= '</div>'; // End Values Container
            
            $output .= '</div>'; // End Box Wrapper Div
            
            // Market Sentiment Section
            if ($market_sentiment === 'true' && count($data) > 1) {
                $output .= '<div class="fng-market-sentiment-' . esc_attr($fng_style) . '">'; // Market Sentiment Div
                $output .= '<h2 style="color: ' . esc_attr($font_color) . ';">Historical Values</h2>';
                $output .= '<ul style="color: ' . esc_attr($font_color) . ';">';
                $output .= '<li>Yesterday: ' . esc_html($data[1]['value']) . '</li>';
                $output .= '<li>Last Week: ' . esc_html($data[7]['value']) . '</li>';
                $output .= '<li>Last Month: ' . esc_html($data[30]['value']) . '</li>';
                $output .= '</ul>';
                $output .= '</div>'; // End Market Sentiment Div
            }
            
            $output .= '</div>'; // End Content Wrapper Div
            $output .= '</div>'; // End SVG Container Div
            $output .= '</div>'; // End Meter Div
            $output .= '</div>'; // End Main Wrapper Div
            
            return $output;
        }
    }
    $cmc_data = fetch_data_from_cmc();
    if (isset($cmc_data['error'])) {
        echo '<div>' . esc_html($cmc_data['error']) . '</div>';
        return;
    }
    $output = display_cmc_widget($cmc_data, $fng_style, $background_color, $font_color, $arrow_color, $market_sentiment, $post_id);
    return $output;
} else {
    echo '<div>Please select a valid provider.</div>';
}
