<?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 dashbord 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 accessable 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('cmb2_save_options-page_fields', array($this, 'cmb2_Settings_callback'));
            

            add_action('ccpwp_get_extra_info', array($this, 'ccpwp_get_extra_info'));
            add_action('cmb2_save_options-page_fields', array($this, 'ccpwp_handle_unchecked_checkbox'), 10, 3);



        }

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

            // Security checks: Verify user capabilities and nonce
            if (!current_user_can('manage_options')) {
                return;
            }

            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['ccpw_extra_info'])) {

                        $options['ccpw_extra_info'] = false;
                    
                       
                        // Clear scheduled hook if it exists
                        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');
                        }
                        // Only check for CELP if the class exists and the option isn't set
                        if (method_exists('CELP_cron', 'celp_send_data') && !isset($_POST['celp_extra_info'])) {
                        

                            $options['celp_extra_info'] = false;
                            wp_clear_scheduled_hook('celp_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 {

                        // Only schedule the cron job if it's not already scheduled
                        if (!wp_next_scheduled('ccpw_extra_data_update')) {

                            CCPWP_cronjob::ccpw_send_data(); // Trigger immediate data send
                            wp_schedule_event(time(), 'every_30_days', 'ccpw_extra_data_update');
                        }

                        if (method_exists('CELP_cron', 'celp_send_data') && !isset($_POST['celp_extra_info'])) {
                        if (!wp_next_scheduled('celp_extra_data_update')) {
                              $options['celp_extra_info'] = true;
                              CELP_cron::celp_send_data(); // Trigger immediate data send
                              wp_schedule_event(time(), 'every_30_days', 'celp_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')) {

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

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

                }
            }
        }

        /**
         * Callback function for Settings options
         */
        public function cmb2_Settings_callback()
        {
            global $wpdb;

            $old_api = get_option('ccpwp_old_api');
            $api = get_option('openexchange-api-settings');
            $api = (isset($api['select_api'])) ? $api['select_api'] : "coingecko";

            if ($api != $old_api) {

                // remove database if CMC is not installed
                $option_table = $wpdb->base_prefix . 'options';
                $db = new ccpwp_database();
                $db->drop_table();
                $this->ccpwp_update_ua_coins_option();
                // delete transient related to coin data
                $wpdb->query("DELETE FROM $option_table WHERE option_name LIKE '%_cmc-saved-coindata%' ");
                $db->create_table();
                wp_schedule_single_event(strtotime("+2 seconds"), 'ccpwp_coins_autosave');
                wp_schedule_single_event(strtotime("+5 seconds"), 'ccpw_coins_autosave_over250');
                update_option('ccpwp_old_api', $api);
            }
        }
        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(CCPWP_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()
        {
            $cmc_nonce = wp_create_nonce('cmc-purge-nonce');
            $ajax_url = admin_url('admin-ajax.php');
            $api_option = get_option("openexchange-api-settings");
            $api_type = (isset($api_option['select_api'])) ? $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'),

                /*
                 * The following parameters are specific to the options-page box
                 * Several of these parameters are passed along to add_menu_page()/add_submenu_page().
                 */

                'option_key' => 'openexchange-api-settings', // The option key and admin menu page slug.
                // 'icon_url'        => 'dashicons-palmtree', // Menu icon. Only applicable if 'parent_slug' is left empty.
                '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.
                // 'admin_menu_hook' => 'network_admin_menu', // 'network_admin_menu' to add network-level options page.
                // 'display_cb'      => false, // Override the options-page form output (CMB2_Hookup::options_page_output()).
                // 'save_button'     => esc_html__( 'Save Settings', 'celp1' ), // The text for the options-page save button. Defaults to 'Save'.
            ));

            /*
             * 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' => 'Both With Coingecko First Pref.',
                    'both_coinmarketcap' => 'Both With CoinMarketcap First Pref.',
                ),
                '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?utm_source=cryptocurrency-widget-pro&utm_medium=inside&utm_campaign=get_pro&utm_content=api-settings" 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.',
                )
            );


            $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'])) ? $api_option['select_api'] : "coingecko";
            $active_api = ($api_type == "coingecko" || $api_type == "both_coingecko") ? "https://www.coingecko.com/en/developers/dashboard?utm_source=cryptocurrency-widget-pro&utm_medium=inside&utm_campaign=get_pro&utm_content=api-settings" : "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>',

            ));
            $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 Widgets Even Better', 'ccpw1'),
                        'id' => 'ccpw_extra_info_title',
                        'type' => 'title',
                    
                    )
                );
                do_action('ccpwp_get_extra_info', $cool_options);
            }
            

            $cool_options->add_field(
                array(
                    'name' => 'Purge API Data Cache',
                    'id' => 'purge_cache',
                    'type' => 'title',
                    'desc' => '<button class="button button-secondary" data-cmc-nonce="' . esc_attr($cmc_nonce) . '" data-ajax-url="' . esc_url($ajax_url) . '" id="cmc_delete_cache">' . __('Purge Cache', 'ccpw') . '</button>',
                )
            );

        }

        public function ccpwp_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['ccpw_extra_info'])) {

                $choice = $api_option['ccpw_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'        => 'ccpw_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'])) ? $api_option['openexchangerate_api'] : "";
            $coin_gecko_api = (!empty($api_option['coingecko_api'])) ? $api_option['coingecko_api'] : "";
            $api_type = (isset($api_option['select_api'])) ? $api_option['select_api'] : "coingecko";
            $cmc_api_key = (isset($api_option['coinmarketcap_api']) && !empty($api_option['coinmarketcap_api'])) ? $api_option['coinmarketcap_api'] : '';

            if (!current_user_can('delete_posts')) {
                return;
            }
            $current_user = wp_get_current_user();
            $user_name = $current_user->display_name;
            $ajax_url = admin_url('admin-ajax.php');
            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 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 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 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 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();

}
