<?php
/**
 * Plugin Name:Cryptocurrency Exchanges List PRO
 * Description:Cryptocurrency Exchanges List Pro WordPress plugin displays a list of 250+ best cryptocurrency exchanges trading volume and market pairs using best crypto API.
 * Author:Cool Plugins
 * Author URI:https://coolplugins.net/?utm_source=celp_plugin&utm_medium=inside&utm_campaign=author_page&utm_content=plugins_list
 * Version: 2.9.2
 * License: GPL2
 * Text Domain:celp
 * Domain Path: languages
 *
 * @package Cryptocurrency Exchanges List PRO
 */

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

if (defined('CELP_VERSION')) {
    return;
}
/*
Defined constant for later use
 */
define('CELP_VERSION', '2.9.2');
define('CELP_FILE', __FILE__);
define('CELP_PATH', plugin_dir_path(CELP_FILE));
define('CELP_URL', plugin_dir_url(CELP_FILE));
define('CELP_FEEDBACK_API',"https://feedback.coolplugins.net/");

if (!defined('CELP_DEMO_URL')) {
    define('CELP_DEMO_URL', "?utm_source=celp_plugin&utm_medium=inside&utm_campaign=demo&utm_content=dashboard");
}
/**
 * Class CryptoCurrencyExchangesList
 */
final class Crypto_Currency_Exchanges_List
{

    /**
     * Plugin instance.
     *
     * @var CryptoCurrencyExchangesList
     * @access private
     */
    private static $instance = null;

    /**
     * Get plugin instance.
     *
     * @return CryptoCurrencyExchangesList
     * @static
     */
    public static function get_instance()
    {
        if (!isset(self::$instance)) {
            self::$instance = new self;
        }
        return self::$instance;
    }

    /**
     * Constructor.
     *
     * @access private
     */
    private function __construct()
    {

        register_activation_hook(CELP_FILE, array($this, 'celp_activate'));
        register_deactivation_hook(CELP_FILE, array($this, 'celp_deactivate'));

        // including required files
        $this->includes();
        $this->installation_date();
        add_action('init', array($this, 'init'));
        add_action('init', array($this, 'celp_rewrite_rule'));
        add_filter('query_vars', array($this, 'celp_query_vars'));

        // run if plugin is just updated from previous version to new version
        add_action('init', array($this, 'celp_plugin_version_verify'));

        /*
        All Shortcodes
         */
        add_shortcode('celp', 'celp_shortcode');

        // exchange details handler class
        $celp_single = new Celp_Details_Shortcodes();

        // exchange prices for coin market cap single page.
        add_shortcode('celp-coin-exchanges', 'celp_coin_exchanges');

        //creating post type for plugin settings panel
        add_action('init', 'celp_post_type');

        add_action('admin_menu', array($this, 'create_admin_menu'), 42);

        add_action('admin_enqueue_scripts', array($this, 'celp_enqueue_admin_scripts'));
        // registering required script for plugin
        // check coin market cap plugin is activated.
        add_action('admin_init', array($this, 'check_cmc_activated'));
        add_filter('display_post_states', array($this, 'protected_post_states'));

        add_action('admin_init', array($this, 'celp_on_settings_save'));
        // rest api endpoint for sitemap generation
        add_action('rest_api_init', function () {
            register_rest_route('exchanges-lists/v1', 'generate-sitemap', array(
                'methods' => 'GET',
                'callback' => array($this, 'ex_generate_sitemap'),
                'permission_callback' => array($this, 'check_sitemap_permissions'),
            ));
        });

        if (is_admin()) {
            //add_action( 'admin_notices', array($this,'celp_admin_notice_for_major_update'));
            add_action('admin_init', array($this, 'celp_check_installation_time'));
            add_action('admin_init', array($this, 'celp_spare_me'), 5);
        } else {
            add_action('template_redirect', array($this, 'exchange_single_page_redirection'));
        }

        // Register functions with cron hooks
        add_action('celp_exchange_data_update', array('CELP_api_data', 'celp_save_ex_data'));

        add_action('wp_ajax_celp_remove_major_update_notice', array($this, 'celp_remove_major_update_notice'));
        add_action('wp_ajax_celp_handle_feedback', array($this, 'celp_handle_feedback'));

        add_action('wp_ajax_celp_get_ex_list', 'celp_get_ex_list_data');
        add_action('wp_ajax_nopriv_celp_get_ex_list', 'celp_get_ex_list_data');

        add_action('wp_ajax_celp_get_coin_exchanges', 'celp_get_coin_exchanges_handler');
        add_action('wp_ajax_nopriv_celp_get_coin_exchanges', 'celp_get_coin_exchanges_handler');
        add_action('init', array($this, 'celp_rtl_check'));
        add_action('init', array($this, 'reset_option_data_once_on_first_of_month'));

    }

    public function celp_rtl_check()
    {
        global $wp_locale;
        $check = $wp_locale->is_rtl();
        if ($check == true) {
            wp_enqueue_style('celp_rtl_css', CELP_URL . 'assets/css/celp-rtl.css', null, CELP_VERSION);
        }
    }
    
    public function check_sitemap_permissions() {
        if ( current_user_can( 'manage_options' ) ) {
            return true;
        }
        return new WP_Error(
            'rest_forbidden',
            __( 'You do not have permission to access this endpoint.', 'textdomain' ),
            array( 'status' => rest_authorization_required_code() )
        );
   }
    public function create_admin_menu()
    {
        add_submenu_page('cool-crypto-plugins', 'Exchanges Description', ' ↳ Custom Descriptions', 'manage_options', 'edit.php?post_type=celp', false, 42);
        add_submenu_page('cool-crypto-plugins', 'Add Description', ' ↳ Add Description', 'manage_options', 'post-new.php?post_type=celp', false, 43);
        add_submenu_page('cool-crypto-plugins', 'Exchange Settings', '↳ Exchange Settings', 'manage_options', 'admin.php?page=celp_options', false, 44);

    }

    //check coin market cap plugin is activated. then enable links
    public function check_cmc_activated()
    {
        if (is_plugin_active('coin-market-cap/coin-market-cap.php') || class_exists('CoinMarketCap')) {
            update_option('cmc-dynamic-links', true);
        } else {
            update_option('cmc-dynamic-links', false);
        }
    }

    /**
     * Load plugin function files here.
     */
    public function includes()
    {
        require_once CELP_PATH . '/includes/api/celp-api-data.php';
        if (is_admin()) {
            require_once CELP_PATH . '/admin/settings/registration-settings.php';
            require_once CELP_PATH . '/admin/addon-dashboard-page/addon-dashboard-page.php';
            cool_plugins_crypto_addon_settings_page('crypto', 'cool-crypto-plugins', 'Cryptocurrency plugins by CoolPlugins.net', 'Crypto Plugins', 'dashicons-chart-area');
            require_once CELP_PATH . '/admin/openexchange-api-settings.php';
        }

        require_once CELP_PATH . '/admin/settings/celp-post-types.php';
        require_once CELP_PATH . '/includes/db/celp-exchanges-db.php';
        require_once CELP_PATH . '/includes/db/celp-exchanges-pairs-db.php';
        require_once CELP_PATH . '/includes/celp-functions.php';
        require_once CELP_PATH . '/includes/shortcode/celp-shortcode.php';
        require_once CELP_PATH . '/includes/shortcode/celp-details-shortcodes.php';
        require_once CELP_PATH . '/includes/shortcode/celp-coin-exchanges.php';
        require_once CELP_PATH . '/admin/exchanges-disable-list/exchange-coins-list-class.php';

        /**
         * Get the bootstrap!
         */
        $post_array = ["celp", "celp_options", "openexchange-api-settings"];
        if (isset($_POST['submit-cmb']) || in_array($this->celp_get_post_type_page(), $post_array)) {
            require_once CELP_PATH . '/admin/cmb2/init.php';
            require_once CELP_PATH . '/admin/settings/celp-settings.php';
            require_once CELP_PATH . '/admin/settings/celp-meta-fields.php';
        }

        require_once CELP_PATH . '/includes/cron/celp-cron.php';
        if(!class_exists('CPFM_Feedback_Notice')){
            require_once CELP_PATH . 'admin/feedback/cpfm-feedback-notice.php';
        }
        
        if(is_admin()){
            require_once CELP_PATH . 'admin/feedback-notice/celp-feedback-notice.php';
            // Instantiate the review notice class
            if (class_exists('CELPReviewNotice')) {
                new CELPReviewNotice();
            }
        }

        
        add_action('cpfm_register_notice', function () {
            
            if (!class_exists('CPFM_Feedback_Notice') || !current_user_can('manage_options')) {
                return;
            }

            $notice = [

                'title' => __('Cryptocurrency Exchanges List Pro by Cool Plugins', 'ccpw'),
                'message' => __('Help us make this plugin more compatible with your site by sharing non-sensitive site data.', 'cool-plugins-feedback'),
                'pages' => ['cool-crypto-plugins', 'cool-crypto-registration','openexchange-api-settings'],
                'always_show_on' => ['cool-crypto-plugins','cool-crypto-registration','openexchange-api-settings'], // This enables auto-show
                'plugin_name'=>'celp'
            ];

            CPFM_Feedback_Notice::cpfm_register_notice('crypto', $notice);

                if (!isset($GLOBALS['cool_plugins_feedback'])) {
                    $GLOBALS['cool_plugins_feedback'] = [];
                }
            
                $GLOBALS['cool_plugins_feedback']['crypto'][] = $notice;
       
        });

        add_action('cpfm_after_opt_in_celp', function($category) {
            if ($category === 'crypto') {
                CELP_cron::celp_send_data();
            
                $options = get_option('openexchange-api-settings', []);
                $options['celp_extra_info'] = true;
                update_option('openexchange-api-settings', $options);
            }
        });
    }

    /**
     * Code you want to run when all other plugins loaded.
     */
    public function init()
    {
        load_plugin_textdomain('celp', false, basename(dirname(__FILE__)) . '/languages');
        
        if (is_admin()) {
            require_once CELP_PATH . '/admin/settings/init-api.php';
        }

        if (!get_option( 'celp_initial_save_version' ) ) {
            add_option( 'celp_initial_save_version', CELP_VERSION );
        }
    }

    /*
    |--------------------------------------------------------------------------
    |  Check if plugin is just updated from older version to new
    |--------------------------------------------------------------------------
     */
    public function celp_plugin_version_verify()
    {
        $CELP_VERSION = get_option('CELP_PRO_VERSION');
        if (!isset($CELP_VERSION) || version_compare($CELP_VERSION, CELP_VERSION, '<')) {
            // Let's make a plugin update log
            update_option('recent_celp_updated_v' . CELP_VERSION, date('Y-M-d H:I'));
            if (isset($CELP_VERSION) && version_compare($CELP_VERSION, '2.4', '<')) {
                // drop and create database table only if previous version is less than 2.0
                delete_transient('celp-saved-ex');
                $this->celp_delete_table();
                $this->celp_create_table();
            }

            $this->ex_detail_page();
            $this->celp_rewrite_rule();
            flush_rewrite_rules();
            update_option('CELP_PRO_VERSION', CELP_VERSION);
            delete_option('celpt-new-install');
            $conversions = get_transient('cmc_usd_conversions');
            if (!empty($conversions)) {
                update_option('cmc_usd_conversions', $conversions);
            }
        }
        if (celp_check_required_settings()) {
            if (!wp_next_scheduled('celp_exchange_data_update')) {
                wp_schedule_event(time(), 'celp-7-min', 'celp_exchange_data_update');
            }
        }
        $this->celp_update_exchange_status();

        $advance_tab = get_option('celp-advance-tabs-page-id');
        if (empty($advance_tab)) {
            $this->ex_detail_page();
        }
    } // end of celp_plugin_version_verify()

    public function celp_update_exchange_status()
    {
        $get_disabled_ex = get_option('celp_disabled_exchanges');
        $get_ex_status = get_option('celp_exchange_status_saved');
        $ex_status = 'disable';
        if ($get_disabled_ex != false) {
            global $wpdb;
            $exchange = get_option('celp_disabled_exchanges');
            $table_name = $wpdb->base_prefix . 'celp_exchanges';
            if ($get_ex_status == 'updated') {
                foreach ($exchange as $coin) {
                    $ex_id = sanitize_text_field($coin->ex_id); 
                    $execute = $wpdb->query($wpdb->prepare("UPDATE $table_name SET exchange_status = %s WHERE ex_id = %s", $ex_status, $ex_id));
                }
            }
            update_option('celp_exchange_status_saved', 'updated');
        }
    }

    /**
     * Run when activate plugin.
     */
    public function celp_activate()
    {
        update_option('celpt-new-install', 'fresh-install');
        $this->celp_create_table();
        $this->ex_detail_page();
        $this->celp_rewrite_rule();
        if (celp_check_required_settings()) {
            if (!wp_next_scheduled('celp_exchange_data_update')) {
                wp_schedule_event(time(), 'celp-7-min', 'celp_exchange_data_update');
            }
        }

        if (!get_option( 'celp_initial_save_version' ) ) {
            add_option( 'celp_initial_save_version', CELP_VERSION );
        }

        if(!get_option( 'celp-install-date' ) ) {
            add_option( 'celp-install-date', gmdate('Y-m-d h:i:s') );
        }
        $options        = get_option('openexchange-api-settings', []);
        if ( isset( $options['celp_extra_info'] ) && ( ! empty( $options['celp_extra_info'] ) || $options['celp_extra_info'] === 'on' ) ) {

            if (!wp_next_scheduled('celp_extra_data_update')) {
                
                wp_schedule_event(time(), 'every_30_days', 'celp_extra_data_update');
                    wp_schedule_event(time(), 'every_30_days', 'cmc_extra_data_update');

            }
        }
        flush_rewrite_rules();
    }

    /**
     * Run when deactivate plugin.
     */
    public function celp_deactivate()
    {
        // uninstall license before deactivating the plugin
        delete_option("celp-plugin-update");

        $this->uninstall_license();

        $this->celp_delete_table();
        global $wpdb;
        $options = $wpdb->base_prefix . 'options';
        $wpdb->query("DELETE FROM " . $options . " WHERE option_name LIKE '%all-markets-saved%' OR option_name LIKE '%all-pairs-saved%' OR option_name LIKE '%celp-cached%'");
        wp_clear_scheduled_hook('celp_exchange_data_update');
        delete_transient('celp-saved-ex');
        delete_option('celp-exchangeTable-initialized');
        flush_rewrite_rules();
        if (wp_next_scheduled('celp_extra_data_update')) {
            wp_clear_scheduled_hook('celp_extra_data_update');
        }
    }

    /*
    saving plugin installation date for later use
     */

    public function installation_date()
    {
        $get_installation_time = strtotime("now");
        add_option('celp_activation_time', $get_installation_time);
    }

    //check if review notice should be shown or not

    public function celp_check_installation_time()
    {

        $spare_me = get_option('celp_spare_me');
        if ($spare_me != 1) {
            $install_date = get_option('celp_activation_time');
            $past_date = strtotime('-1 days');

            if ($past_date >= $install_date) {
                add_action('admin_notices', array($this, 'celp_display_admin_notice'));

            }
        }
    }
    // remove the notice for the user if review already done or if the user does not want to
    public function celp_spare_me()
    {
        // Only process if this is not a redirect from our own function
        if (isset($_GET['celp_redirected'])) {
            return;
        }
        
        if (isset($_GET['ex_spare_me']) && !empty($_GET['ex_spare_me'])) {
            if (!current_user_can('manage_options')) {
                return;
            }
            $spare_me = sanitize_text_field($_GET['ex_spare_me']); 
            if ($spare_me == 1) {
                // Check if already set to prevent multiple updates
                $already_set = get_option('celp_spare_me');
                if ($already_set != 1) {
                    update_option('celp_spare_me', 1);
                }
                // Redirect to remove the URL parameter to prevent it from being set again on refresh
                $current_url = remove_query_arg('ex_spare_me');
                // Add cache-busting parameter to ensure fresh redirect
                $current_url = add_query_arg('celp_redirected', '1', $current_url);
                wp_redirect($current_url);
                exit;
            }
        }
    }

    /**
     * Display Admin Notice, asking for a review
     **/
    public function celp_display_admin_notice()
    {
        
        // Use the new feedback notice class
        if (class_exists('CELP_Feedback_Notice')) {
            $feedback_notice = new CELP_Feedback_Notice();
            $feedback_notice->display_admin_notice();
        }
    }

    /*
    check admin side post type page
     */
    public function celp_get_post_type_page()
    {
        global $post, $typenow, $current_screen;

        if ($post && $post->post_type) {
            return $post->post_type;
        } elseif ($typenow) {
            return $typenow;
        } elseif ($current_screen && $current_screen->post_type) {
            return $current_screen->post_type;
        } elseif (isset($_REQUEST['page'])) {
            return sanitize_key($_REQUEST['page']);
        } elseif (isset($_REQUEST['post_type'])) {
            return sanitize_key($_REQUEST['post_type']);
        } elseif (isset($_REQUEST['post'])) {
            return get_post_type($_REQUEST['post']);
        }
        return null;
    }

    /*-----------------------------------------------------------------------------------|
    |             The below function verify if the requested exchange is enabled             |
    |            If the exchange is disabled, single page only shows 404 error             |
    |        It will also return 404 error if exchange is not available in the database     |
    |------------------------------------------------------------------------------------|
     */
    public function exchange_single_page_redirection()
    {
        global $post;
        $page_id = celp_get_single_page_id();
        if (!isset($post->ID) || (isset($post->ID) && $post->ID != $page_id)) {
            return;
        }

        $ex_id = get_query_var('exchange-id');

        $db = new CELP_Exchanges();
        $new_ex_id = celp_get_new_exchange_id($ex_id);
        $exchange = !empty($ex_id) ? $db->get_exchanges(array('ex_id' => trim($new_ex_id))) : null;
        if ($exchange === false) {
            global $wp_query;
            $wp_query->set_404();
            status_header(404);
            include get_query_template('404');
            exit();
        } else {
            if ($new_ex_id != $ex_id) {
                $page_id = celp_get_single_page_id();
                $slug = celp_get_option('exchange-page-slug');
                $page_slug = !empty($slug) ? $slug : "exchange";
                $exchange_page = site_url($page_slug . '/' . $new_ex_id);
                wp_redirect($exchange_page, '301');
                exit; // Ensure to exit after redirect
            }
        }
    }

    public function celp_on_settings_save()
    {
        if (
            isset($_POST['submit-cmb']) && isset($_POST['action'])
        ) {
            $new = isset($_POST['exchange-page-slug']) ? sanitize_text_field($_POST['exchange-page-slug']) : ""; 
            $slug = celp_get_option('exchange-page-slug');
            if ($new != $slug) {
                add_filter('generate_rewrite_rules', array($this, 'celp_dynamic_rewrite_rules'));
                flush_rewrite_rules();
            }
            update_option("celp-data-updated", "saved");

        }

    }

    // adding rewrite rule
    public function celp_rewrite_rule()
    {

        $page_id = celp_get_single_page_id();
        $slug = celp_get_option('exchange-page-slug');
        $page_slug = !empty($slug) ? $slug : "exchange";
        add_rewrite_rule('^' . $page_slug . '/([^/]*)?$', 'index.php?page_id=' . $page_id . '&exchange-id=$matches[1]', 'top');

        $updated_page = get_option("celp-data-updated");
        if ($updated_page !== false) {
            flush_rewrite_rules();
            delete_option("celp-data-updated");
        }

        $on_update = get_option("celp-plugin-update");
        if ($on_update == false && CELP_VERSION > 2.2) {
            flush_rewrite_rules();
            update_option("celp-plugin-update", "plugin-update");
        }

    }

    // adding dyanmic rewrite rule after save changes in slug settings
    public function celp_dynamic_rewrite_rules($wp_rewrite)
    {
        $page_id = celp_get_single_page_id();
        $slug = celp_get_option('exchange-page-slug');
        $page_slug = !empty($slug) ? $slug : "exchange";
        $feed_rules = array(
            '^' . $page_slug . '/([^/]*)?$' => 'index.php?page_id=' . $page_id . '&exchange-id=$matches[1]',

        );
        $wp_rewrite->rules = $feed_rules + $wp_rewrite->rules;
        return $wp_rewrite->rules;
    }

    // create query var for url
    public function celp_query_vars($query_vars)
    {
        $query_vars[] = 'exchange-id';
        return $query_vars;
    }

    // generating dynamic page for exchange single page
    public function ex_detail_page()
    {

        $post_data = array(
            'post_title' => 'cmc exchange details',
            'post_type' => 'page',
            'post_content' => '
            [celp-detail][celp-dynamic-description][celp-description][celp-currencies-pairs][celp-twitter-feed]
            ',
            'post_status' => 'publish',
            'post_author' => get_current_user_id(),
        );

        $page_id = get_option('ex-single-page-id');

        if ('publish' === get_post_status($page_id)) {
            // Page already exists, no need to create it again
        } else {
            $post_id = wp_insert_post($post_data);
            update_option('ex-single-page-id', $post_id);
        }

        $post_data = array(
            'post_title' => 'celp exchange details(Advanced Design)',
            'post_type' => 'page',
            'post_content' => '[celp-single-details-advanced-design]',
            'post_status' => 'publish',
            'post_author' => get_current_user_id(),
        );
        $page_id = get_option('celp-advance-tabs-page-id');

        if ('publish' === get_post_status($page_id)) {
            // Page already exists, no need to create it again
        } else {
            $post_id = wp_insert_post($post_data);
            update_option('celp-advance-tabs-page-id', $post_id);
        }
    }

    public function protected_post_states($states)
    {
        global $post;

        $custom_state = __("Don't Delete", 'celp1');

        if (isset($post->ID) && $post->ID == get_option('ex-single-page-id') || isset($post->ID) && $post->ID == get_option('celp-advance-tabs-page-id')) {
            return $states[] = array($custom_state);
        }
        return $states;

    }

    //generating sitemap
    public function ex_generate_sitemap()
    {  
        /*---- Create cryptocurrency-exchanges-list-pro sitemap Upload  ----*/
        $upload = wp_upload_dir();
        $upload_dir = $upload['basedir'];
        $upload_dir = $upload_dir . '/cryptocurrency-exchanges-list-pro';

        $upload_dir = wp_normalize_path($upload_dir);
        $sitemap_dir = wp_normalize_path($upload_dir . '/sitemap');

        if (!is_dir($upload_dir)) {
            wp_mkdir_p($upload_dir);
        }
        if (!is_dir($sitemap_dir)) {
            wp_mkdir_p($sitemap_dir);
        }

        $response = array();
        $api_response = celp_get_all_exchanges();
        $sitemap_url = home_url('wp-content/uploads/cryptocurrency-exchanges-list-pro/sitemap/', '/');

        if (!empty($api_response) && (is_object($api_response) || gettype($api_response) == 'array')) {
            $all_exchanges = celpobjectToArray($api_response);
            $this->ex_create_sitemap($all_exchanges);

            $combine_sitemap = "<?xml version='1.0' encoding='UTF-8'?>";
            $combine_sitemap .= "<sitemapindex xmlns='http://www.sitemaps.org/schemas/sitemap/0.9'>";

            $combine_sitemap .= "<sitemap>";
            $combine_sitemap .= "<loc>" . esc_url($sitemap_url . 'sitemap.xml') . "</loc>"; 
            $combine_sitemap .= "</sitemap>";
            $combine_sitemap .= "</sitemapindex>";
            header('content-type: text/xml');
            echo $combine_sitemap;
            die();
        } else {
            $response[] = array(
                'status' => 'Error',
                'error' => 'API Request Timeout',
            );
            echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
            die();
        }

    }

    public function ex_create_sitemap($all_exchanges)
    {
        $coins_xml = '';
        $sitemap = '';
        $slug = !empty(celp_get_option('exchange-page-slug')) ? celp_get_option('exchange-page-slug') : "exchange";
        $detail_page_url = esc_url(home_url($slug, '/'));

        $upload = wp_upload_dir();
        $upload_dir = $upload['basedir'];
        $sitemap_dir = $upload_dir . '/cryptocurrency-exchanges-list-pro/sitemap';

        if (is_array($all_exchanges) && count($all_exchanges) > 0) {

            foreach ($all_exchanges as $key => $exchange) {
                $exchange_content = (array) $exchange;
                $e_id = sanitize_text_field($exchange_content['ex_id']);

                $ex_url = esc_url($detail_page_url . '/' . $e_id . '/');
                $coins_xml .= '<url>' .
                    '<loc>' . $ex_url . '</loc>' .
                    '<priority>1</priority>' .
                    '<changefreq>daily</changefreq>' .
                    '</url>';
            }
            $sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
            $sitemap .= '<?xml-stylesheet type="text/xsl" href="' . esc_url(CELP_URL . '/sitemap/sitemap-style.xsl') . '"?>'; 
            $sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
            $sitemap .= $coins_xml;
            $sitemap .= '</urlset>';

           global $wp_filesystem;
            if (empty($wp_filesystem)) {
                require_once(ABSPATH . '/wp-admin/includes/file.php');
                WP_Filesystem();
            }
            $sitemap_file = wp_normalize_path($sitemap_dir . '/sitemap.xml');
            $wp_filesystem->put_contents($sitemap_file, $sitemap, FS_CHMOD_FILE);
        }
    }

/*
|--------------------------------------------------------------------------
| generating coins tables
|--------------------------------------------------------------------------
 */
    public function celp_create_table()
    {
        $celp_ex_db = new CELP_Exchanges;
        $celp_ex_pair_db = new CELP_Exchanges_Pairs;
        $celp_ex_db->create_table();
        $celp_ex_pair_db->create_table();
    }
/*
|--------------------------------------------------------------------------
| deleting coins tables on plugin deactivation
|--------------------------------------------------------------------------
 */
    public function celp_delete_table()
    {
        global $wpdb;
        $ex_table = $wpdb->prefix . 'celp_exchanges';
        $ex_meta_table = $wpdb->prefix . 'celp_exchanges_pairs';
        $wpdb->query("DROP TABLE IF EXISTS " . $ex_table);
        $wpdb->query("DROP TABLE IF EXISTS " . $ex_meta_table);
    }

    /**
     * Show admin notice for major plugin update.
     */
    public function celp_admin_notice_for_major_update()
    {
        $plugin_info = get_plugin_data(__FILE__, true, true);
        $is_updated = get_option('recent_celp_updated_v' . CELP_VERSION, false);
        $isVisible = get_option('celp_remove_update_notice_v' . CELP_VERSION);
        if ($is_updated != false && $isVisible == false) {
            printf(__('<div class="celp-major-update notice notice-warning is-dismissible important"><h3><strong>%s</strong>: This is a major plugin update, You must follow these update guidelines - <a href="https://bit.ly/cryptocurrency-update" target="_blank">click here</a></h3></div>'), esc_html($plugin_info['Name'])); 
        }

    }

    public function celp_enqueue_admin_scripts()
    {

        
        if(!wp_script_is( 'cpfm-data-share-setting.js' )){
            $screen = get_current_screen();     
            if (strpos($screen->id, 'openexchange-api-settings') !== false) {
                wp_enqueue_script('cpfm-settings-data-share', CELP_URL . 'assets/js/cpfm-data-share-setting.js', array('jquery'), CELP_VERSION, true);
            }
        }
        
    }
    /**
     *
     * This function receives an ajax request to hide plugins update message box
     *
     */
    public function celp_remove_major_update_notice()
    {
        update_option('celp_remove_update_notice_v' . CELP_VERSION, date("Y-M-d H:I"));
        die(json_encode(array('response' => '200', 'message' => 'Update notice removed')));
    }

    /**
     * Handle feedback AJAX request
     */
    public function celp_handle_feedback()
    {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'celp_feedback_nonce')) {
            wp_die('Security check failed');
        }

        // Check user permissions
        if (!current_user_can('manage_options')) {
            wp_die('Insufficient permissions');
        }

        $action = sanitize_text_field($_POST['action_type']);
        
        if ($action === 'already_rated' || $action === 'not_interested') {
            // Set the spare_me option to hide the notice
            update_option('celp_spare_me', 1);
            wp_send_json_success('Feedback received');
        }
        
        wp_send_json_error('Invalid action');
    }

    /**
     * This function will uninstall the license without removing the license key from database
     */
    public function uninstall_license()
    {
        $options = get_option('celp_license_registration');
        if (!empty($options) && is_array($options) && isset($options['celp-purchase-code'])) {
            require_once CELP_PATH . '/admin/settings/CryptocurrencyExchangesListProBase.php';
            $message = "";
            $response = CryptocurrencyExchangesListProREG\CryptocurrencyExchangesListProBase::RemoveLicenseKey(CELP_FILE, $message);
        }
    }
    public function reset_option_data_once_on_first_of_month()
    {
        // Check if it's the 1st day of the month
        $current_date = date('j');

        if ($current_date === '1') {
            // Check if a flag or option indicating the reset has already been performed
            $reset_flag = get_option('ccpw_reset_flag');

            // If the reset has not been performed (reset_flag is not set), perform the reset
            if (empty($reset_flag)) {
                // Reset your option data
                update_option('cmc_coingecko_api_hits', 0);

                // Set a flag to indicate that the reset has been performed
                update_option('ccpw_reset_flag', '1');
            }
        } else {
            if (get_option('ccpw_reset_flag')) {
                delete_option('ccpw_reset_flag');
            }
        }
    }

} // class end

function Crypto_Currency_Exchanges_List()
{
    return Crypto_Currency_Exchanges_List::get_instance();
}

$GLOBALS['Crypto_Currency_Exchanges_List'] = Crypto_Currency_Exchanges_List();
