<?php
if (!defined('ABSPATH')) {
    exit;
}

// Do not use namespace to keep this on global space to keep the singleton initialization working
if (!class_exists('Openexchange_api_settings')) {

/**
 *
 * This is the main class for creating dashboard addon page and all submenu items
 *
 * Do not call or initialize this class directly, instead use the function mentioned at the bottom of this file
 */
    class Openexchange_api_settings
    {

        /**
         * None of these variables should be accessible from the outside of the class
         */
        private static $instance;

        /**
         * initialize the class and create dashboard page only one time
         */
        public static function init()
        {
            if (empty(self::$instance)) {
                return self::$instance = new self;
            }
            return self::$instance;
        }

        /**
         * Initialize the dashboard with specific plugins as per plugin tag
         *
         */
        public function cool_init_hooks()
        {
            add_action('admin_notices', array($this, 'Openexchange_api_key_notice'));
            add_action('admin_menu', array($this, 'Openexchange_add_submenu'), 100);
            add_action('cmb2_admin_init', array($this, 'Openexchange_settings_callback'));
            add_action('admin_head', array($this, 'Openexchange_custom_javascript_for_cmb2'));
            add_action('celp_get_extra_info', array($this, 'celp_get_extra_info'));
            add_action('cmb2_save_options-page_fields', array($this, 'celp_handle_unchecked_checkbox'), 10, 3);


        }

            function celp_handle_unchecked_checkbox($object_id, $updated, $cmb) {

            if ($object_id === 'openexchange-api-settings') {

                $choice = get_option('cpfm_opt_in_choice_crypto');
                $options = get_option($object_id, array());

                if (!empty($choice)) {
                    
                    if (!isset($_POST['celp_extra_info'])) {

                        $options['celp_extra_info'] = false;

                       
                        // Clear scheduled hook if it exists
                        wp_clear_scheduled_hook('celp_extra_data_update');
                        
                        // Only check for CCPW if the class exists
                        if (!isset($_POST['ccpw_extra_info']) && (method_exists('CCPW_cronjob', 'ccpw_send_data') || method_exists('CCPWP_cronjob', 'ccpw_send_data'))) {

                        $options['ccpw_extra_info'] = false;
                        wp_clear_scheduled_hook('ccpw_extra_data_update');
                        }

                        // Only check for CMC if the class exists and the option isn't set
                        if ( method_exists('CMC_cronjob', 'cmc_send_data')  && !isset($_POST['cmc_extra_info'])) {
                            

                            $options['cmc_extra_info'] = false;
                            wp_clear_scheduled_hook('cmc_extra_data_update');
                        }
                        if ( method_exists('CCEW_cronjob', 'ccew_send_data') &&  !isset($_POST['ccew_extra_info'])) {

                            $options['ccew_extra_info'] = false;
                            wp_clear_scheduled_hook('ccew_extra_data_update');
                        }
                        
                        update_option($object_id, $options);

                    } else {
                        if (!wp_next_scheduled('celp_extra_data_update')) {
                            
                            CELP_cron::celp_send_data();
                            wp_schedule_event(time(), 'every_30_days', 'celp_extra_data_update');
                        }

                        if (!isset($_POST['ccpw_extra_info']) && ($class = (method_exists('CCPW_cronjob', 'ccpw_send_data') ? 'CCPW_cronjob' : (method_exists('CCPWP_cronjob', 'ccpw_send_data') ? 'CCPWP_cronjob' : null)))) {
                           
                            $options['ccpw_extra_info'] = true;
                            $class::ccpw_send_data();

                            if (!wp_next_scheduled('ccpw_extra_data_update')) {
                                wp_schedule_event(time(), 'every_30_days', 'ccpw_extra_data_update');
                            }
                        }

                        if ( method_exists('CMC_cronjob', 'cmc_send_data') && !isset($_POST['cmc_extra_info'])) {
               
                            if (!wp_next_scheduled('cmc_extra_data_update')) {

                            CMC_cronjob::cmc_send_data(); // Trigger immediate data send
                            wp_schedule_event(time(), 'every_30_days', 'cmc_extra_data_update');
                            $options['cmc_extra_info'] = true;
                            }
                        }
                        

                        if (  method_exists('CCEW_cronjob', 'ccew_send_data') && !isset($_POST['ccew_extra_info'])) {

                            if (!wp_next_scheduled('ccew_extra_data_update')) {
                                
                                $options['ccew_extra_info'] = true;
                                CCEW_cronjob::ccew_send_data(); // Trigger immediate data send
                                wp_schedule_event(time(), 'every_30_days', 'ccew_extra_data_update');
                            }
                        }

                        // Optionally set the flag to true for clarity
                        $options['ccpw_extra_info'] = true;
                        update_option($object_id, $options);
                    }

                }
            }
        }

        public function ccpwp_update_ua_coins_option()
        {
            $api_option = get_option("openexchange-api-settings");
            $api_type = (isset($api_option['select_api'])) ? $api_option['select_api'] : "coingecko";
            // Read the JSON file
            $json_data = file_get_contents(CMC_PATH . 'assets/cmc-coins-ids.json');

            // Decode the JSON data into an associative array
            $coin_list = json_decode($json_data, true);
            $saved_ua_coins = get_option('ccpwp-unavailable-coins', []);
            $saved_ua_coinsc = get_option('ccpwp-unavailable-coins-cmc', []);

            if ($api_type == "both_coinmarketcap" || $api_type == "coinmarketcap") {
                // Flip the array if required
                if (!empty($saved_ua_coins)) {
                    $coin_list = array_flip($coin_list);
                    $found = [];
                    foreach ($saved_ua_coins as $key) {
                        if (array_key_exists($key, $coin_list)) {
                            $found[] = $coin_list[$key]; // Add the found key to the list
                        }
                    }
                    $merged_list = array_unique(array_merge($found, $saved_ua_coinsc));
                    update_option('ccpwp-unavailable-coins-cmc', $merged_list, true);
                }
            } else {
                if (!empty($saved_ua_coinsc)) {
                    $found = [];
                    foreach ($saved_ua_coinsc as $key) {
                        if (array_key_exists($key, $coin_list)) {
                            $found[] = $coin_list[$key]; // Add the found key to the list
                        }
                    }
                    $merged_list = array_unique(array_merge($found, $saved_ua_coins));
                    update_option('ccpwp-unavailable-coins', $merged_list, true);
                }
            }
        }

        public function Openexchange_custom_javascript_for_cmb2()
        {
            // Enqueue jQuery if not already enqueued
            if (!wp_script_is('jquery', 'enqueued')) {
                wp_enqueue_script('jquery');
            }

            $script = <<<EOT
    <script>
        jQuery(document).ready(function($) {
            var url = window.location.href;
            var isSettingsPage = url.indexOf('?page=openexchange-api-settings') > 0;

            if (isSettingsPage) {
               $('.cmb2-id-select-api #select_api').change(function() {
                $('.cmb2-id-coinmarketcap-api').hide();
                $('.cmb2-id-api-end-point').hide();
                $('.cmb2-id-coingecko-api').hide();
                    // Retrieve the selected value
                    const selectedValue = this.value;
                    if(selectedValue =="coingecko"){
                        $('.cmb2-id-api-end-point').show();
                        $('.cmb2-id-coingecko-api').show();
                    }
                    else if (selectedValue == "coinmarketcap") {
                         $('.cmb2-id-coinmarketcap-api').show();
                    }
                    else if (selectedValue == "both_coingecko"|| selectedValue == "both_coinmarketcap") {
                         $('.cmb2-id-coinmarketcap-api').show();
                         $('.cmb2-id-api-end-point').show();
                         $('.cmb2-id-coingecko-api').show();
                    }
                })
                $('.cmb2-id-select-api #select_api').change();

                $('[href="admin.php?page=openexchange-api-settings"]').parent('li').addClass('current');
            }

            var data = $('#adminmenu #toplevel_page_cool-crypto-plugins ul li a[href="admin.php?page=openexchange-api-settings"]');
            data.each(function() {
                if ($(this).is(':empty')) {
                    $(this).hide();
                }
            });
        });
    </script>
EOT;

            echo $script;
        }

        /**
         * This function will initialize the main dashboard menu for all plugins
         */
        public function Openexchange_add_submenu()
        {
            add_submenu_page('cool-crypto-plugins', 'API Settings', 'API Settings', 'manage_options', 'admin.php?page=openexchange-api-settings', false, 100);
        }

        /**
         * This function will render and create the HTML display of dashboard page.
         * All the HTML can be located in other template files.
         * Avoid using any HTML here or use nominal HTML tags inside this function.
         */
        public function Openexchange_settings_callback()
        {
            $api_option = get_option("openexchange-api-settings");
            $api_type = (isset($api_option['select_api'])) ? sanitize_text_field($api_option['select_api']) : "coingecko";

            /**
             * Registers options page menu item and form.
             */
            $cool_options = new_cmb2_box(array(
                'id' => 'ccpw_settings_page',
                'title' => esc_html__('API Settings', 'celp1'),
                'object_types' => array('options-page'),
                'option_key' => 'openexchange-api-settings', // The option key and admin menu page slug.
                'menu_title' => false, // Falls back to 'title' (above).
                'parent_slug' => 'cool-crypto-plugins', // Make options page a submenu item of the themes menu.
                'capability' => 'manage_options', // Cap required to view options-page.
                'position' => 44, // Menu position. Only applicable if 'parent_slug' is left empty.
            ));

            /*
             * Options fields ids only need
             * to be unique within this box.
             * Prefix is not needed.
             */
            $cool_options->add_field(array(
                'name' => __('ENTER OPENEXCHANGERATES.ORG API KEY', 'ccpw1'),
                'id' => 'ccpw_openexchangerate_api_title',
                'type' => 'title',
            ));

            $cool_options->add_field(array(
                'name' => __('Enter API Key', 'ccpw1'),
                'desc' => __('Click Here To <a href="https://openexchangerates.org/signup/free" target="_blank">Get Openexchangerates Free API Key</a>', 'ccpw1'),
                'id' => 'openexchangerate_api',
                'type' => 'text',
            ));

            $cool_options->add_field(array(
                'name' => __('Api Settings', 'ccpw1'),
                'id' => 'ccpw_coingecko_api_title',
                'type' => 'title',
            ));
            $cool_options->add_field(array(
                'name' => __('Select API Type', 'cmc2'),
                'desc' => '',
                'id' => 'select_api',
                'type' => 'select',
                'options' => array(
                    'coingecko' => 'CoinGecko',
                    'coinmarketcap' => 'CoinMarketCap',
                    'both_coingecko' => 'CoinGecko + CoinMarketCap ',
                    'both_coinmarketcap' => 'CoinMarketCap + CoinGecko',
                ),
                'desc' => (class_exists('Crypto_Currency_Exchanges_List') && $api_type == "coinmarketcap") ? '<span style="color:red">Please choose either CoinGecko or both API option, as the Cryptoexchanges plugin utilizes the CoinGecko API.</span>' : 'Please select the API option that best aligns with your data source needs. If you choose the "CoinGecko + CoinMarketCap" option, the CoinGecko API will be used as the primary source. Conversely, if you select the "CoinMarketCap + CoinGecko" option, the CoinMarketCap API will be prioritized.',
                'default' => 'coingecko',
            ));

            $cool_options->add_field(array(
                'name' => __('Select Coingecko API Type', 'cmc2'),
                'desc' => '',
                'id' => 'api_end_point',
                'type' => 'select',
                'options' => array(
                    'free' => 'FREE',
                    'pro' => 'PRO',
                ),
                'default' => 'free',
            ));

            $cool_options->add_field(array(
                'name' => __('Enter CoinGecko API Key', 'ccpw1'),
                'desc' => __('Check <a href="https://support.coingecko.com/hc/en-us/articles/21880397454233-User-Guide-How-to-use-Demo-plan-API-key-" target="_blank">-How to retrieve Coingecko Free API Key ?</a>', 'ccpw1'),
                'id' => 'coingecko_api',
                'type' => 'text',
            ));
            $cool_options->add_field(array(
                'name' => __('Enter CoinMarketCap API Key', 'ccpw1'),
                'desc' => __('Check <a href="https://coinmarketcap.com/api/" target="_blank">-How to retrieve CoinMarketCap API Key ?</a>', 'ccpw1'),
                'id' => 'coinmarketcap_api',
                'type' => 'text',
            ));

            $cool_options->add_field(
                array(
                    'name' => 'Select API Cache Time',
                    'id' => 'select_cache_time',
                    'desc' => 'Trigger the API after that interval to load the most recent prices.',
                    'type' => 'select',
                    'default' => '10',
                    'options' => array(
                        '5' => __('5 Minutes', 'cmb2'),
                        '10' => __('10 Minutes', 'cmb2'),
                        '15' => __('15 Minutes', 'cmb2'),
                    ),
                    'desc' => 'Approximately 18,000 monthly API calls can be handled with a 5-minute API cache.<br>
                    Approximately 9,000 API calls per month can be managed with a 10-minute API cache.<br>
                    With a 15-minute API cache, you can support approximately 6,000 monthly API calls.',
                )
            );

            $cpfm_opt_in    = get_option('cpfm_opt_in_choice_crypto');
            $notice_check   = isset($cpfm_opt_in) ? $cpfm_opt_in : '';

            if($notice_check)   {

                $cool_options->add_field(
                    array(
                        'name' => __('Make Cryptocurrency Exchanges List Pro Even Better', 'ccpw1'),
                        'id' => 'celp_extra_info_title',
                        'type' => 'title',
                    
                    )
                );
                do_action('celp_get_extra_info', $cool_options);
            }
            

            $total_hits = (get_option('cmc_coingecko_api_hits')) ? get_option('cmc_coingecko_api_hits') : 0;
            $api_option = get_option("openexchange-api-settings");
            $api_type = (isset($api_option['select_api'])) ? sanitize_text_field($api_option['select_api']) : "coingecko";
            $active_api = ($api_type == "coingecko" || $api_type == "both_coingecko") ? "https://www.coingecko.com/en/developers/dashboard" : "https://pro.coinmarketcap.com/account";
            $cool_options->add_field(array(
                'name' => 'API Usage Report',
                'id' => 'ccpw_api_hit_title',
                'type' => 'title',
                // 'desc' => '<div class="cmb-th"></div><div class="cmb-td"><table><tr><td>Total Monthly API Calls:-</td><td> <b>10000</b></td></tr><tr><td>Used API Calls:- </td><td><b>' . ($total_hits ? $total_hits : '') . '</b></td><tr><tr><td>Remaining monthly API Calls:- </td><td><b>' . (($total_hits <= 10000) ? (10000 - $total_hits) : 0) . '</b></td><tr><td><a href="' . $active_api . ' " target="blank">Click here to view API usage details</a></td><td></td></tr></table></div>',
                'desc' => '<div class="cmb-th"></div><div class="cmb-td"><table><tr><td><a href="' . $active_api . ' " target="blank">Click here to view API usage details</a></td><td></td></tr></table></div>',

            ));

        }

        public function celp_get_extra_info($cool_options_setting) {

            $choice     = get_option('cpfm_opt_in_choice_crypto');
        
            $api_option = get_option("openexchange-api-settings");
           
            if (!empty($api_option) && isset($api_option['celp_extra_info'])) {

                $choice = $api_option['celp_extra_info'];

            }

            $choice = (!empty($choice) && $choice === 'yes') ? 'on' : '';

            $terms_html = '
                Help us make this plugin more compatible with your site by sharing non-sensitive site data. 
                <a href="#" class="cpfm-see-terms">[See terms]</a>
                <div id="termsBox" style="display: none;padding-left: 20px; margin-top: 10px; font-size: 12px; color: #999;">
                 <p>'. esc_html__('Opt in to receive email updates about security improvements, new features, helpful tutorials, and occasional special offers. We\'ll collect:', 'ccpw') . ' <a href="https://my.coolplugins.net/terms/usage-tracking/?utm_source=atfpp_plugin&utm_medium=inside&utm_campaign=terms&utm_content=dashboard" target="_blank" rel="noopener noreferrer">
                          '. esc_html__('Click here', 'ccpw') . '
                          </a></p>
                    <ul style="list-style-type:auto;">
                        <li>'. esc_html__('Your website home URL and WordPress admin email.', 'ccpw') . '</li>
                        <li>' . esc_html__('To check plugin compatibility, we will collect the following: list of active plugins and themes, server type, MySQL version, WordPress version, memory limit, site language and database prefix.', 'ccpw') . '</li>
                    </ul>
                </div>';

            $cool_options_setting->add_field(array(
                'name'      => __('Usage Data Sharing ', 'ccpw1'),
                'id'        => 'celp_extra_info',
                'type'      => 'checkbox',
                'default'   => $choice,
                'desc'      => $terms_html,
              
            ));
       
        }

        /*
        |----------------------------------------------------------------
        |   Admin notice for API Key registration admin users only
        |----------------------------------------------------------------
         */
        public function Openexchange_api_key_notice()
        {
            $api_option = get_option("openexchange-api-settings");
            $api = (!empty($api_option['openexchangerate_api'])) ? sanitize_text_field($api_option['openexchangerate_api']) : "";
            $coin_gecko_api = (!empty($api_option['coingecko_api'])) ? sanitize_text_field($api_option['coingecko_api']) : "";
            $api_type = (isset($api_option['select_api'])) ? sanitize_text_field($api_option['select_api']) : "coingecko";
            $cmc_api_key = (isset($api_option['coinmarketcap_api']) && !empty($api_option['coinmarketcap_api'])) ? sanitize_text_field($api_option['coinmarketcap_api']) : '';

            if (!current_user_can('delete_posts')) {
                return;
            }
            $current_user = wp_get_current_user();
            $user_name = $current_user->display_name;

            if (empty($api)) {
                ?>
                <div class="license-warning notice notice-error is-dismissible">
                    <p>Hi, <strong><?php echo esc_html(ucwords($user_name)); ?></strong>! Please <strong><a href="<?php echo esc_url(get_admin_url(null, 'admin.php?page=openexchange-api-settings')); ?>">enter</a></strong> Openexchangerates.org free API key for crypto to fiat price conversions.</p>
                </div>
                <?php
            }
            if (($api_type == "coingecko") && empty($coin_gecko_api)) {
                ?>
                <div class="license-warning notice notice-error is-dismissible">
                    <p>Hi, <strong><?php echo esc_html(ucwords($user_name)); ?></strong>! Please <strong><a href="<?php echo esc_url(get_admin_url(null, 'admin.php?page=openexchange-api-settings')); ?>">enter</a></strong> Coingecko free API key to work this plugin.</p>
                </div>
                <?php
            } else if (($api_type == "coinmarketcap") && empty($cmc_api_key)) {
                ?>
                <div class="license-warning notice notice-error is-dismissible">
                    <p>Hi, <strong><?php echo esc_html(ucwords($user_name)); ?></strong>! Please <strong><a href="<?php echo esc_url(get_admin_url(null, 'admin.php?page=openexchange-api-settings')); ?>">enter</a></strong> Coinmarketcap API key to work this plugin.</p>
                </div>
                <?php
            } else if ($api_type == "both_coinmarketcap" || $api_type == "both_coingecko") {
                if (empty($coin_gecko_api)) {
                    ?>
                    <div class="license-warning notice notice-error is-dismissible">
                        <p>Hi, <strong><?php echo esc_html(ucwords($user_name)); ?></strong>! Please <strong><a href="<?php echo esc_url(get_admin_url(null, 'admin.php?page=openexchange-api-settings')); ?>">enter</a></strong> Coingecko free API key to work this plugin.</p>
                    </div>
                    <?php
                }
                if (empty($cmc_api_key)) {
                    ?>
                    <div class="license-warning notice notice-error is-dismissible">
                        <p>Hi, <strong><?php echo esc_html(ucwords($user_name)); ?></strong>! Please <strong><a href="<?php echo esc_url(get_admin_url(null, 'admin.php?page=openexchange-api-settings')); ?>">enter</a></strong> Coinmarketcap API key to work this plugin.</p>
                    </div>
                    <?php
                }
            }
        }
    }

    /**
     *
     * initialize the main dashboard class with all required parameters
     */
    $Openexchange = Openexchange_api_settings::init();
    $Openexchange->cool_init_hooks();

}
