<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

// Enqueue scripts and styles for the Weather Plugin
function wtdp_weather_plugin_enqueue_scripts($hook) {
    // Only run on the specific settings page
    if ($hook != 'settings_page_wtdp-settings') {
        return;
    }

    // =========================
    // Main Weather Plugin Script
    // =========================
    wp_enqueue_script(
        'wtdp-weather-scripts', 
        plugin_dir_url(__FILE__) . 'includes/admin.js', 
        array('jquery'), 
        filemtime(plugin_dir_path(__FILE__) . 'includes/admin.js'), 
        true
    );

    // =========================
    // AJAX Script
    // =========================
    wp_enqueue_script(
        'my-ajax-script', 
        plugin_dir_url(__FILE__) . 'includes/my-ajax.js', 
        array('jquery'), 
        filemtime(plugin_dir_path(__FILE__) . 'includes/my-ajax.js'), 
        true
    );

    // =========================
    // Localize AJAX URL for use in JS
    // =========================
    // Get JSON options
    $general_settings = json_decode(get_option('wtdp_general', '{}'), true);

    wp_localize_script('my-ajax-script', 'wtdp_PluginData', array(
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'apiKey' => sanitize_text_field(isset($general_settings['wtdp_api_key']) ? $general_settings['wtdp_api_key'] : ''),
        'latitude' => (float) (isset($general_settings['wtdp_latitude']) ? $general_settings['wtdp_latitude'] : '51.5085'),
        'longitude' => (float) (isset($general_settings['wtdp_longitude']) ? $general_settings['wtdp_longitude'] : '-0.1257'),
        'pluginPath' => plugin_dir_url(__FILE__)
    ));

    // =========================
    // WordPress Color Picker Styles
    // =========================
    wp_enqueue_style('wp-color-picker');

    // =========================
    // Alpha Color Picker Script
    // =========================
    $script_version = '3.0.4'; // Change this to your actual version number
    $url_to_script = plugins_url('/includes/wp-color-picker-alpha/dist/wp-color-picker-alpha.min.js', __FILE__);
    
    wp_register_script('wp-color-picker-alpha', $url_to_script, array('wp-color-picker'), $script_version, true);
    
    // Add inline script to initialize the color picker with alpha support
    wp_add_inline_script('wp-color-picker-alpha', 'jQuery(function() { jQuery(".color-picker").wpColorPicker({ alpha: true }); });');
    
    // Enqueue the alpha color picker script
    wp_enqueue_script('wp-color-picker-alpha');

    // =========================
    // Leaflet CSS
    // =========================
    wp_enqueue_style(
        'leaflet-css',
        plugin_dir_url(__FILE__) . 'includes/leaflet/leaflet.css', // Path to local Leaflet CSS
        array(), // No dependencies
        filemtime(plugin_dir_path(__FILE__) . 'includes/leaflet/leaflet.css') // Cache-busting based on file modification time
    );

    // =========================
    // Leaflet JS
    // =========================
    wp_enqueue_script(
        'leaflet-js',
        plugin_dir_url(__FILE__) . 'includes/leaflet/leaflet.js', // Path to local Leaflet JS
        array(), // No dependencies
        filemtime(plugin_dir_path(__FILE__) . 'includes/leaflet/leaflet.js'), // Cache-busting based on file modification time
        true // Load in footer for performance (set to false to load in the header)
    );

}
add_action('admin_enqueue_scripts', 'wtdp_weather_plugin_enqueue_scripts');



// Add the settings page
function wtdp_add_settings_page() {
    add_options_page(
        __('Extended Weather Settings', 'extended-weather'),
        __('Extended Weather', 'extended-weather'),
        'manage_options',
        'wtdp-settings',
        'wtdp_settings_page_html'
    );
}
add_action('admin_menu', 'wtdp_add_settings_page');



// Enqueue CSS without cache
function wtdp_weather_plugin_enqueue_styles($hook) {
    if ($hook != 'settings_page_wtdp-settings') {
        return;
    }
    
    // Get the file modification time to prevent caching
    $css_file = plugin_dir_path(__FILE__) . 'includes/admin.css';
    $version = file_exists($css_file) ? filemtime($css_file) : '1.0.0';

    wp_enqueue_style('wtdp-weather-admin-style', plugin_dir_url(__FILE__) . 'includes/admin.css', array(), $version, 'all');
}
add_action('admin_enqueue_scripts', 'wtdp_weather_plugin_enqueue_styles');



// Display the settings page
function wtdp_settings_page_html() {
    if (!current_user_can('manage_options')) {
        return;
    }

    // Handle form submission
    if (isset($_POST['wtdp_save_settings'])) {
        // Verify nonce
        check_admin_referer('wtdp_save_settings_nonce');

        // GENERAL SETTINGS
        // Define settings
        $settings = [
            'wtdp_api_key',
            'wtdp_time_difference',
            'wtdp_default_city',
            'wtdp_unit_system',
            'wtdp_language',
            'wtdp_latitude',
            'wtdp_longitude',
            'wtdp_column_temperature',
            'wtdp_column_humidity',
            'wtdp_column_wind_speed',
            'wtdp_column_pressure',
            'wtdp_column_sunrise',
            'wtdp_column_sunset',
        ];

        // Loop through settings and update options if present in POST
        $settings_data = array();
        foreach ($settings as $option) {
            if (isset($_POST[$option])) {
                // Sanitize input based on the option type
                if ($option === 'wtdp_time_difference') {
                    $sanitized_value = absint(wp_unslash($_POST[$option]));
                } else {
                    $sanitized_value = sanitize_text_field(wp_unslash($_POST[$option]));
                }

                // Store the sanitized value in the settings data array
                $settings_data[$option] = $sanitized_value;
            } else {
                // If the option is not present in the POST data, use the existing value
                $settings_data[$option] = get_option($option, '');
            }
        }

        // Save the settings data as JSON
        $settings_json = wp_json_encode($settings_data);
        update_option('wtdp_general', $settings_json);


        // LATEST SETTINGS
        $settings = [
            'wtdp-latest-container-bg-gradient-start' => 'sanitize_text_field',
            'wtdp-latest-container-bg-gradient-end'   => 'sanitize_text_field',
            'wtdp-latest-items-bg-gradient-start'     => 'sanitize_text_field',
            'wtdp-latest-items-bg-gradient-end'       => 'sanitize_text_field',
            'wtdp-latest-timestamp-text-color'        => 'sanitize_text_field',
            'wtdp-latest-location-text-color'         => 'sanitize_text_field',
            'wtdp-latest-description-text-color'      => 'sanitize_text_field',
            'wtdp-latest-temp-text-color'             => 'sanitize_text_field',
            'wtdp-latest-items-text-color'            => 'sanitize_text_field',

            // Size Settings with Unit Selection
            'wtdp-latest-timestamp-font-size'         => 'sanitize_text_field',
            'wtdp-latest-timestamp-font-size-unit'    => 'sanitize_select', 
            'wtdp-latest-location-font-size'          => 'sanitize_text_field',
            'wtdp-latest-location-font-size-unit'     => 'sanitize_select', 
            'wtdp-latest-temp-font-size'              => 'sanitize_text_field',
            'wtdp-latest-temp-font-size-unit'         => 'sanitize_select', 
            'wtdp-latest-unit-font-size'              => 'sanitize_text_field',
            'wtdp-latest-unit-font-size-unit'         => 'sanitize_select', 
            'wtdp-latest-description-font-size'       => 'sanitize_text_field',
            'wtdp-latest-description-font-size-unit'  => 'sanitize_select', 
            'wtdp-latest-items-font-size'             => 'sanitize_text_field',
            'wtdp-latest-items-font-size-unit'        => 'sanitize_select', 
            'wtdp-latest-icon-size'                   => 'sanitize_text_field',
            'wtdp-latest-icon-size-unit'              => 'sanitize_select', 
            'wtdp-latest-container-width'             => 'sanitize_text_field',
            'wtdp-latest-container-width-unit'        => 'sanitize_select', 
            'wtdp-latest-container-margin'            => 'sanitize_text_field',
            'wtdp-latest-container-padding'           => 'sanitize_text_field',
            'wtdp-latest-container-padding-unit'      => 'sanitize_select', 
            'wtdp-latest-items-padding'               => 'sanitize_text_field',
            'wtdp-latest-items-padding-unit'          => 'sanitize_select', 

            // Show/Hide Options (checkboxes)
            'wtdp-latest-show-location'               => 'sanitize_checkbox',
            'wtdp-latest-show-timestamp'              => 'sanitize_checkbox',
            'wtdp-latest-show-temperature'            => 'sanitize_checkbox',
            'wtdp-latest-show-icon'                   => 'sanitize_checkbox',
            'wtdp-latest-show-description'            => 'sanitize_checkbox',
            'wtdp-latest-show-humidity'               => 'sanitize_checkbox',
            'wtdp-latest-show-wind-speed'             => 'sanitize_checkbox',
            'wtdp-latest-show-pressure'               => 'sanitize_checkbox',
            'wtdp-latest-show-sunrise-sunset'         => 'sanitize_checkbox',
        ];

        // Custom function to sanitize checkbox input (returns 1 for checked, 0 for unchecked)
        function sanitize_checkbox($value) {
            return isset($value) && $value == '1' ? '1' : '0';
        }

        // Custom function to sanitize select input (ensures value is one of the allowed options)
        function sanitize_select($value, $allowed_values = null) {
            $allowed_values = $allowed_values ?: ['px', '%'];
            return in_array($value, $allowed_values, true) ? $value : 'px';
        }


        // Initialize an array to hold sanitized settings
        $sanitized_settings = [];

        // Loop through settings and update the sanitized settings array
        foreach ($settings as $option => $sanitize_callback) {
            if (isset($_POST[$option])) {
                // Sanitize the input by first unslashing and then using the sanitizer function
                $input_value = sanitize_text_field(wp_unslash($_POST[$option]));
                $sanitized_value = call_user_func($sanitize_callback, $input_value);
                $sanitized_settings[$option] = $sanitized_value; // Add to the array
            } else {
                // For checkboxes, if not set in POST, set them to '0' (unchecked)
                if ($sanitize_callback === 'sanitize_checkbox') {
                    $sanitized_settings[$option] = '0'; // Set to '0' if unchecked
                }
            }
        }

        // Append unit values to their corresponding size settings
        foreach ($sanitized_settings as $option => $value) {
            if (strpos($option, '-unit') !== false) {
                // Get the corresponding size option by removing '-unit' from the name
                $size_option = str_replace('-unit', '', $option);
                
                if (isset($sanitized_settings[$size_option])) {
                    // Append the unit to the size value
                    $sanitized_settings[$size_option] .= $sanitized_settings[$option];
                }
            }
        }

        // Convert the sanitized settings array to a JSON string
        $settings_json = wp_json_encode($sanitized_settings);

        // Update the single option with the JSON string
        update_option('wtdp_latest_css', $settings_json);



        // LATEST 3 SETTINGS
        // Define individual settings for sanitization
        $background_gradients = [
            'wtdp-latest-2-container-bg-gradient-start' => 'sanitize_text_field',
            'wtdp-latest-2-container-bg-gradient-end'   => 'sanitize_text_field',
        ];

        $text_colors = [
            'wtdp-latest-2-description-text-color'      => 'sanitize_text_field',
            'wtdp-latest-2-items-text-color'            => 'sanitize_text_field',
            'wtdp-latest-2-temp-text-color'             => 'sanitize_text_field',
        ];

        $font_sizes = [
            'wtdp-latest-2-temp-font-size'              => 'sanitize_text_field',
            'wtdp-latest-2-temp-font-size-unit'         => 'sanitize_select',
            'wtdp-latest-2-unit-font-size'              => 'sanitize_text_field',
            'wtdp-latest-2-unit-font-size-unit'         => 'sanitize_select',
            'wtdp-latest-2-description-font-size'       => 'sanitize_text_field',
            'wtdp-latest-2-description-font-size-unit'  => 'sanitize_select',
            'wtdp-latest-2-items-font-size'             => 'sanitize_text_field',
            'wtdp-latest-2-items-font-size-unit'        => 'sanitize_select',            
            'wtdp-latest-2-icon-size'                   => 'sanitize_text_field',
            'wtdp-latest-2-icon-size-unit'              => 'sanitize_select',
            'wtdp-latest-2-container-width'             => 'sanitize_text_field',
            'wtdp-latest-2-container-width-unit'        => 'sanitize_select',
            'wtdp-latest-2-container-padding'           => 'sanitize_text_field',
            'wtdp-latest-2-container-padding-unit'      => 'sanitize_select',
        ];

        $show_hide_options = [
            'wtdp-latest-2-show-icon'                   => 'sanitize_checkbox',
            'wtdp-latest-2-show-temperature'            => 'sanitize_checkbox',
            'wtdp-latest-2-show-description'            => 'sanitize_checkbox',
            'wtdp-latest-2-show-city'                   => 'sanitize_checkbox',
            'wtdp-latest-2-show-sunrise-sunset'         => 'sanitize_checkbox',
        ];

        // Combine all settings for processing
        $settings = array_merge($background_gradients, $text_colors, $font_sizes, $show_hide_options);

        // Initialize an array to hold the sanitized values
        $sanitized_values = [];

        // Loop through settings and update options if present in POST
        foreach ($settings as $option => $sanitize_callback) {
            if (isset($_POST[$option])) {
                // Unslash the input first
                $input_value = sanitize_text_field(wp_unslash($_POST[$option]));

                // Sanitize the input directly based on the option type
                switch ($sanitize_callback) {
                    case 'sanitize_text_field':
                        $sanitized_values[$option] = sanitize_text_field($input_value);
                        break;
                    case 'sanitize_select':
                        $sanitized_values[$option] = sanitize_key($input_value); // Ensure valid option key
                        break;
                    case 'sanitize_checkbox':
                        $sanitized_values[$option] = isset($_POST[$option]) ? '1' : '0';
                        break;
                    default:
                        // Handle any additional sanitization if needed
                        break;
                }
            } else {
                // For checkboxes, if not set in POST, set them to '0' (unchecked)
                if ($sanitize_callback === 'sanitize_checkbox') {
                    $sanitized_values[$option] = '0';
                }
            }
        }

        // Append unit values to their corresponding size settings
        foreach ($settings as $option => $sanitize_callback) {
            if (strpos($option, '-unit') !== false) {
                // Get the corresponding size option by removing '-unit' from the name
                $size_option = str_replace('-unit', '', $option);
                
                if (isset($sanitized_values[$size_option])) {
                    // Append the unit to the size value
                    $sanitized_values[$size_option] .= $sanitized_values[$option];
                }
            }
        }

        // Convert the sanitized values array to a JSON string
        $sanitized_values_string = wp_json_encode($sanitized_values);

        // Update the option with the concatenated string
        update_option('wtdp_latest_2_css', $sanitized_values_string);



        // Output the message div only once
        $message = 'Settings saved.';
        if ($message) {
            echo '<div class="wtdp_messages" id="messageDiv">' .  esc_html($message) . '</div>';
        }

    } 
    // ******************** END SAVE ***********************
?>


    <div class="wrap">
        <form method="post" action="">

            <?php wp_nonce_field('wtdp_save_settings_nonce'); ?>
            <?php wp_nonce_field('wtdp_save_settings_nonce', 'wtdp_save_settings_nonce'); ?>

            <div class="header-container">
                <img src="<?php echo esc_url(plugin_dir_url(__FILE__) . 'includes/icon-256.png'); ?>" alt="<?php esc_attr_e('Weather Icon', 'extended-weather'); ?>" class="weather-icon">
                <h1><?php esc_html_e('Extended Weather Plugin Settings', 'extended-weather'); ?></h1>
            </div><br>

            <!-- Tab Navigation -->
            <?php $current_tab = 'general-settings-tab';?>
            <h2 class="nav-tab-wrapper">
                <a href="#general-settings-tab" class="nav-tab <?php echo esc_attr($current_tab == 'general-settings-tab' ? 'nav-tab-active' : ''); ?>"><?php esc_html_e('General', 'extended-weather'); ?></a>
                <a href="#weather-latest-big-tab" class="nav-tab <?php echo esc_attr($current_tab == 'weather-latest-big-tab' ? 'nav-tab-active' : ''); ?>"><?php esc_html_e('Latest weather - Big', 'extended-weather'); ?></a>
                <a href="#weather-latest-small-tab" class="nav-tab <?php echo esc_attr($current_tab == 'weather-latest-small-tab' ? 'nav-tab-active' : ''); ?>"><?php esc_html_e('Latest weather - Small', 'extended-weather'); ?></a>
            </h2>

            <!-- ************************** GENERAL ************************** -->
            <?php include plugin_dir_path(__FILE__) . 'includes/settings-general.php';?>
            

            <!-- ************************** LATEST BIG ************************** -->
            <div id="weather-latest-big-tab" class="tab-content <?php echo esc_attr($current_tab == 'weather-latest-big-tab' ? '' : 'hidden'); ?>">
                <div class="settings-h2"><?php esc_html_e('LATEST WEATHER BIG', 'extended-weather'); ?></div>
                
                <input type="submit" name="wtdp_save_settings" class="button-primary-save" value="<?php esc_attr_e('Save Settings', 'extended-weather'); ?>">
                <p> <?php esc_html_e(' Shortcode: ', 'extended-weather'); ?> <strong>[wtdp_display_latest]</strong></p>
                
                <div id="latest_style_1">
                    <div class="wtdp-admin-settings-container" style="display: flex; flex-wrap: wrap; gap: 20px;">
                        <?php include plugin_dir_path(__FILE__) . 'includes/settings-latest.php';?>
                    </div>
                </div>
            </div>

            <!-- ************************** LATEST SMALL ************************** -->
            <div id="weather-latest-small-tab" class="tab-content <?php echo esc_attr($current_tab == 'weather-latest-small-tab' ? '' : 'hidden'); ?>">
                <div class="settings-h2"><?php esc_html_e('LATEST WEATHER SMALL', 'extended-weather'); ?></div>
                
                <input type="submit" name="wtdp_save_settings" class="button-primary-save" value="<?php esc_attr_e('Save Settings', 'extended-weather'); ?>">
                <p> <?php esc_html_e(' Shortcode: ', 'extended-weather'); ?> <strong>[wtdp_display_latest_2]</strong></p>

                <div id="latest_style_2">
                    <div class="wtdp-admin-settings-container" style="display: flex; flex-wrap: wrap; gap: 20px;">
                        <?php include plugin_dir_path(__FILE__) . 'includes/settings-latest-2.php';?>
                    </div>
                </div>
            </div>      

            <!-- **************************** HIDDEN *************************** -->
            <input type="hidden" name="current_tab" value="<?php echo esc_attr($current_tab); ?>">
            <!-- *************************************************************** -->

        </form>

    </div>

    <div id = "wtdp_paypal">
        <!-- PayPal Donate Button -->
        <a href="https://www.paypal.com/donate/?hosted_button_id=MKCAWBHQELYEQ" target="_blank">
            <button style="
                background-color: #FFDD57; 
                color: #333; 
                border: none; 
                padding: 5px 10px; 
                font-size: 12px; 
                border-radius: 5px; 
                cursor: pointer; 
                font-weight: bold;
                margin-top: 30px;
                box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
                text-transform: uppercase;">
                PayPal Donate
            </button>
        </a>
    </div>

    <?php
}
