<?php
/**
 * Fetch and display latest weather data.
 *
 * @param array $atts Attributes passed to the shortcode.
 * @return string HTML output of weather data or error message.
 */
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

// Enqueue CSS for the frontend and admin
function wtdp_enqueue_latest_2_css() {
    // Latest-2 CSS
    // Register the CSS file with cache-busting using filemtime
    $css_latest_2_path = plugin_dir_path(__FILE__) . 'includes/latest-2.css';
    $timestamp_latest_2 = file_exists($css_latest_2_path) ? filemtime($css_latest_2_path) : time();
    $css_latest_2_url = plugin_dir_url(__FILE__) . 'includes/latest-2.css';

    wp_enqueue_style('wtdp-latest-2-css', $css_latest_2_url, [], $timestamp_latest_2);

    // Get JSON string from the option for dynamic styles
    $json_string_latest_2 = get_option('wtdp_latest_2_css', '{}');
    $latest_2_options = json_decode($json_string_latest_2, true);

    // Set default values if the JSON option is not present
    $default_values = array(
        'wtdp-latest-2-container-bg-gradient-start' => '#ffffff',
        'wtdp-latest-2-container-bg-gradient-end'   => '#ededed',
        'wtdp-latest-2-description-text-color'      => '#000000',
        'wtdp-latest-2-items-text-color'            => '#000000',
        'wtdp-latest-2-temp-text-color'             => '#dd3333',
        'wtdp-latest-2-temp-font-size'              => '20px',
        'wtdp-latest-2-unit-font-size'              => '14px',
        'wtdp-latest-2-description-font-size'       => '10px',
        'wtdp-latest-2-items-font-size'             => '10px',
        'wtdp-latest-2-icon-size'                   => '40px',
        'wtdp-latest-2-container-width'             => '230px',
        'wtdp-latest-2-container-padding'           => '3px',
        'wtdp-latest-2-show-icon'                   => 1,
        'wtdp-latest-2-show-temperature'            => 1,
        'wtdp-latest-2-show-description'            => 1,
        'wtdp-latest-2-show-city'                   => 1,
        'wtdp-latest-2-show-sunrise-sunset'         => 1,
    );

    // Merge user options with default values
    $merged_options = array_merge($default_values, $latest_2_options);

    // Generate dynamic CSS with inline variables
    $custom_css = "
        :root {
            --wtdp-latest-2-bg-gradient-start: {$merged_options['wtdp-latest-2-container-bg-gradient-start']};
            --wtdp-latest-2-bg-gradient-end: {$merged_options['wtdp-latest-2-container-bg-gradient-end']};
            --wtdp-latest-2-description-text-color: {$merged_options['wtdp-latest-2-description-text-color']};
            --wtdp-latest-2-items-text-color: {$merged_options['wtdp-latest-2-description-text-color']};
            --wtdp-latest-2-temp-text-color: {$merged_options['wtdp-latest-2-temp-text-color']};
            --wtdp-latest-2-temp-font-size: {$merged_options['wtdp-latest-2-temp-font-size']};
            --wtdp-latest-2-unit-font-size: {$merged_options['wtdp-latest-2-unit-font-size']};
            --wtdp-latest-2-description-font-size: {$merged_options['wtdp-latest-2-description-font-size']};
            --wtdp-latest-2-items-font-size: {$merged_options['wtdp-latest-2-description-font-size']};
            --wtdp-latest-2-icon-size: {$merged_options['wtdp-latest-2-icon-size']};
            --wtdp-latest-2-container-width: {$merged_options['wtdp-latest-2-container-width']};
            --wtdp-latest-2-container-padding: {$merged_options['wtdp-latest-2-container-padding']};
        }
        
        .wtdp-latest-2-icon { display: " . ($merged_options['wtdp-latest-2-show-icon'] ? 'block' : 'none') . "; }
        .wtdp-latest-2-temperature { display: " . ($merged_options['wtdp-latest-2-show-temperature'] ? 'block' : 'none') . "; }
        .wtdp-latest-2-description { display: " . ($merged_options['wtdp-latest-2-show-description'] ? 'block' : 'none') . "; }
        .wtdp-latest-2-city { display: " . ($merged_options['wtdp-latest-2-show-city'] ? 'block' : 'none') . "; }
        .wtdp-latest-2-sunrise-sunset { display: " . ($merged_options['wtdp-latest-2-show-sunrise-sunset'] ? 'block' : 'none') . "; }
    ";

    // Inject inline CSS
    wp_add_inline_style('wtdp-latest-2-css', esc_attr($custom_css));
}

// Use wp_enqueue for both frontend and admin
add_action('wp_head', 'wtdp_enqueue_latest_2_css');
add_action('admin_enqueue_scripts', 'wtdp_enqueue_latest_2_css');
















// Shortcode function to display weather data
function wtdp_weather_latest_2($atts) {
    $weather_data = wtdp_fetch_weather_by_lat_lon();
    $labels = array(
        'header' => esc_html(get_option('wtdp_latest_2_header_text', 'Latest Data')),
        'city' => esc_html(get_option('wtdp_column_city', 'City')),
        'temperature' => esc_html(get_option('wtdp_column_temperature', 'Temperature')),
        'humidity' => esc_html(get_option('wtdp_column_humidity', 'Humidity')),
        'wind_speed' => esc_html(get_option('wtdp_column_wind_speed', 'Wind Speed')),
        'pressure' => esc_html(get_option('wtdp_column_pressure', 'Pressure')),
        'local_time' => esc_html(get_option('wtdp_column_local_time', 'Local Time')),
        'sunrise' => esc_html(get_option('wtdp_column_sunrise', 'Sunrise')),
        'sunset' => esc_html(get_option('wtdp_column_sunset', 'Sunset')),
        'description' => esc_html(get_option('wtdp_column_description', 'Description'))
    );

    // Get unit system
    $unit_system = sanitize_text_field(get_option('wtdp_unit_system', 'metric'));
    // Determine temperature unit
    $temperature_unit = ($unit_system === 'metric') ? '°C' : '°F';


    // Output buffering for HTML content
    ob_start();

    if (isset($weather_data['error'])) {
        echo "<div class='error-message'>" . esc_html($weather_data['error']) . "</div>";
    } else {
        // Check if required fields exist in the API response
        if (!empty($weather_data['weather'][0]['description']) && 
            !empty($weather_data['main']['temp']) && 
            !empty($weather_data['weather'][0]['icon']) && 
            !empty($weather_data['sys']['country']) && 
            !empty($weather_data['name'])) {
            
            // Extract relevant data
            $wtdp_latest_weather_description = esc_html($weather_data['weather'][0]['description']);
            $wtdp_latest_weather_icon_code = esc_html($weather_data['weather'][0]['icon']);
            $wtdp_latest_weather_icon_url = esc_url(wtdp_get_custom_weather_icon($wtdp_latest_weather_icon_code));

            $wtdp_latest_temperature = number_format(floatval($weather_data['main']['temp']), 1);
            $wtdp_latest_humidity = esc_html($weather_data['main']['humidity']);
            $wtdp_latest_pressure = esc_html($weather_data['main']['pressure']);
            $wtdp_latest_wind_speed = esc_html($weather_data['wind']['speed']);
            $wtdp_latest_country = esc_html($weather_data['sys']['country']);
            $general_settings = json_decode(get_option('wtdp_general', '{}'), true);
            $wtdp_latest_city_name = esc_html($general_settings['wtdp_default_city'] ?? 'Default City');
            $wtdp_latest_timestamp = intval($weather_data['dt']);
            $wtdp_latest_sunrise = intval($weather_data['sys']['sunrise']);
            $wtdp_latest_sunset = intval($weather_data['sys']['sunset']);

            $time_difference = intval(get_option('wtdp_time_difference', 0));
            $wtdp_latest_local_timestamp = gmdate('Y-m-d H:i', $wtdp_latest_timestamp + ($time_difference * 3600));
            $wtdp_latest_local_sunrise = gmdate('H:i', $wtdp_latest_sunrise + ($time_difference * 3600));
            $wtdp_latest_local_sunset = gmdate('H:i', $wtdp_latest_sunset + ($time_difference * 3600));

            // Correct the weather description if needed
            if ($wtdp_latest_weather_description === "Rošenje") {
                $wtdp_latest_weather_description = "Rosenje";
            }

            // Check if valid weather data exists
            if ($weather_data) {
                // Display output
                echo "<div class='wtdp-latest-2-container'>";
                
                    echo "<div class='wtdp-latest-2-info'>";
                        echo "<div class='wtdp-latest-2-icon'>
                                <img src='" . esc_url($wtdp_latest_weather_icon_url) . "' alt='" . esc_attr($wtdp_latest_weather_description) . "' title='" . esc_attr($wtdp_latest_weather_description) . "' />
                            </div>";
                        echo "<div class='wtdp-latest-2-temperature'>" . esc_html($wtdp_latest_temperature) . "<sup class='wtdp-latest-2-unit-temperature'> " . esc_html($temperature_unit) . "</sup></div>";
                        echo "<div class='wtdp-latest-2-description'>" . esc_html($wtdp_latest_weather_description) . "</div>";
                    echo "</div>"; // Close info div

                    echo "<div class='wtdp-latest-2-row-2'>";
                        echo "<div class='wtdp-latest-2-city' style='text-align: left;'>" . esc_html($wtdp_latest_city_name) . ", " . esc_html($wtdp_latest_country) . "</div>";
                        echo "<div class='wtdp-latest-2-sunrise-sunset'>
                                <span style='font-size: 1.2em; font-weight: normal;'>&uarr;</span> 
                                " . esc_html($wtdp_latest_local_sunrise) . " 
                                <span style='font-size: 1.2em; font-weight: normal;'>&darr;</span> 
                                " . esc_html($wtdp_latest_local_sunset) . "
                            </div>";
                    echo "</div>"; // Close row-2 div
           
                echo "</div>"; // Close container div
            } else {
                echo "<div class='error-message'>" . esc_html__('Weather data is not available.', 'extended-weather') . "</div>";
            }
        }
    }


    return ob_get_clean();
}

add_shortcode('wtdp_display_latest_2', 'wtdp_weather_latest_2');