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

        /**
         * CMC_USD_CONVERSION used for coins fiat conversion transient name.
         */
        const CMC_USD_CONVERSION = 'cmc_usd_conversions';
        const CMC_USD_CONVERSION_TRANSIENT = 12 * HOUR_IN_SECONDS;

        /**
         * CELP_BTC_PRICE Transient used for save btc price.
         */
        const CELP_BTC_PRICE = 'celp_btc_Price';
        const CELP_BTC_PRICE_TIME = MINUTE_IN_SECONDS * 5;

        /**
         * CELP_SINGLE_PAGE used for exchange single page data.
         */
        const CELP_SINGLE_PAGE = 12 * MINUTE_IN_SECONDS;

        /**
         * CELP_VOL_CHART used for chart data.
         */
        const CELP_VOL_CHART = DAY_IN_SECONDS;

        /**
         * CMC_API_ENDPOINT
         *
         * Holds the URL of the coins data API.
         *
         * @access public
         *
         */
        const CELP_API_ENDPOINT = 'https://apiv3.coinexchangeprice.com/v3/exchange-rates';

        /**
         * COINGECKO_API_ENDPOINT
         *
         * Holds the URL of the coingecko API.
         *
         * @access public
         *
         */
        const COINGECKO_API_ENDPOINT = 'https://api.coingecko.com/api/v3/';
        
        /**
         * COINPAPRIKA_API_ENDPOINT
         *
         * Holds the URL of the Coinpaprika API.
         *
         * @access public
         *
         */
        const COINPAPRIKA_API_ENDPOINT= 'https://api.coinpaprika.com/v1/';

        /**
         * OPENEXCHANGERATE_API_ENDPOINT
         *
         * Holds the URL of the openexchangerates API.
         *
         * @access public
         *
         */
        const OPENEXCHANGERATE_API_ENDPOINT = 'https://openexchangerates.org/api/latest.json?app_id=';

        public function __construct()
        {
            // self::CMC_API_ENDPOINT = 'https://apiv3.coinexchangeprice.com/v3/';
        }

        // Function to get the CoinGecko API key
        public static function get_coingecko_api_key_celp() {
            $api_option = get_option("openexchange-api-settings");
            $api_key = isset($api_option['coingecko_api']) ? sanitize_text_field($api_option['coingecko_api']) : ""; // Default API key
            // Apply filter to allow changing the API key
            $api_key = apply_filters('coingecko_api_key', $api_key);
            return $api_key;
        }

        public static function celp_save_ex_data()
        {
            // Do not proceed further if
            if (!celp_check_required_settings()) {
                return;
            }
        
            if (false != get_transient('celp-saved-ex')) {
                return;
            }
            $api_option = get_option("openexchange-api-settings");
            $coingecko_api_key = self::get_coingecko_api_key_celp();
            $coingecko_api_cache_time = isset($api_option['select_cache_time']) ? (int)$api_option['select_cache_time'] : 10;
            $celpEx = new CELP_Exchanges;
            $firstinitialized = get_option('celp-exchangeTable-initialized', false);
            $api_url[] = celp_get_api_end_point() . "exchanges?per_page=250";
            $api_url[] = celp_get_api_end_point() . "exchanges?per_page=250&page=2";
            $ex_data = null;
            foreach ($api_url as $url) {
                $headers = array(
                    'timeout' => 300,
                    'sslverify' => true,
                    'headers' => array(
                        celp_get_api_key_end_point() => $coingecko_api_key
                    )
                );
                $request = wp_remote_get($url, $headers);
                if (is_wp_error($request)) {
                    return false;
                }
                if (celp_check_api_errors($request)) {
                    return self::celp_save_ex_data_backup();   
                }
                $body = wp_remote_retrieve_body($request);
                $data = json_decode($body);
                
                if (isset($data) && !empty($data)) {
                    if ($ex_data == null) {
                        $ex_data = celpobjectToArray($data);
                    } else {
                        $ex_data = array_merge($ex_data, celpobjectToArray($data));
                    }
                }
            }           

            $btc_price = self::celp_get_btcprice();

            $all_ex_data = array();
            $time = current_time('mysql');
            $save_it = array();
            if (is_array($ex_data)) {
                celp_track_coingecko_api_hit();
                foreach ($ex_data as $index => $exchange) {
                    $exchange = celpobjectToArray($exchange);
                    $save_it['ex_id'] = $exchange['id'];
                    $save_it['name'] = $exchange['name'];
                    $save_it['trust_score'] = $exchange['trust_score'];
                    $save_it['volume_24h'] = $exchange['trade_volume_24h_btc'] * $btc_price;
                    $save_it['established'] = $exchange['year_established'];
                    $save_it['btc_volume'] = $exchange['trade_volume_24h_btc'];
                    $save_it['country'] = $exchange['country'];
                    $save_it['updated'] = time();
                    if ($firstinitialized == false) {
                        $save_it['extra_data'] = json_encode(array(
                            'website' => wp_http_validate_url(esc_url_raw($exchange['url'])) ? esc_url_raw($exchange['url']) : '',
                            'logo' => wp_http_validate_url(esc_url_raw($exchange['image'])) ? esc_url_raw($exchange['image']) : '',
                        ), JSON_UNESCAPED_SLASHES);
                    }
                    $save_it['about'] = sanitize_textarea_field($exchange['description']);
                    $all_ex_data[] = $save_it;
                }
                if (is_array($all_ex_data) && count($all_ex_data) > 0) {
                    if ($firstinitialized == false) {
                        update_option('celp-exchangeTable-initialized', date('Y-M-d H:I:s'));
                    }
                    set_transient('celp-saved-ex', date('H:s:i'), $coingecko_api_cache_time * MINUTE_IN_SECONDS);
                    return $rs = $celpEx->celp_ex_insert($all_ex_data);
                }
            }

        }
        public static function celp_save_ex_data_backup()
        {
            if (false != get_transient('celp-saved-ex')) {
                return;
            }
            $api_option = get_option("openexchange-api-settings");
            $coingecko_api_key = self::get_coingecko_api_key_celp();
            $coingecko_api_cache_time = isset($api_option['select_cache_time']) ? (int)$api_option['select_cache_time'] : 10;
            $celpEx = new CELP_Exchanges;
          
            //    $api_url ="https://api.coinexchangeprice.com/v1/exchanges/info";
            $url = self::COINPAPRIKA_API_ENDPOINT."exchanges?quotes=USD,BTC";     
            $ex_data = null;

            $request = wp_remote_get($url, array('timeout' => 300, 'sslverify' => true));
            if (is_wp_error($request)) {
                return false;
            }
            $body = wp_remote_retrieve_body($request);
            $ex_data = json_decode($body, true);           

            $btc_price = self::celp_get_btcprice();

            $all_ex_data = array();
            $time = current_time('mysql');
            $save_it = array();
            if (is_array($ex_data)) {
                foreach ($ex_data as $index => $exchange) {         
                    if (celp_exchange_array($exchange['id'], true)) {      
                        $save_it['ex_id'] = sanitize_text_field( celp_exchange_array( isset($exchange['id']) ? $exchange['id'] : '' ) );     
                        $save_it['name'] = isset($exchange['name']) ? sanitize_text_field($exchange['name']) : '';
                        $save_it['volume_24h'] = ( isset($exchange['quotes']['USD']['reported_volume_24h']) && is_numeric($exchange['quotes']['USD']['reported_volume_24h']) ) ? floatval($exchange['quotes']['USD']['reported_volume_24h']) : 0;
                        $save_it['btc_volume'] = ( isset($exchange['quotes']['BTC']['reported_volume_24h']) && is_numeric($exchange['quotes']['BTC']['reported_volume_24h']) ) ? floatval($exchange['quotes']['BTC']['reported_volume_24h']) : 0;
                             
                        $save_it['updated'] = time();                  
                        $save_it['extra_data'] = json_encode(array(
                            'website' => esc_url($exchange['links']['website'][0]),
                            'twitter' => isset($exchange['links']['twitter'][0]) ? str_replace("https://twitter.com/", "", esc_url($exchange['links']['twitter'][0])) : "",
                            'logo' => esc_url('https://static.coinpaprika.com/exchanges/' . $exchange['id'] . '/logo.png'),
                        ), JSON_UNESCAPED_SLASHES);
                        $save_it['about'] = sanitize_textarea_field($exchange['description']);
                        $all_ex_data[] = $save_it;
                    }
                }
                if (is_array($all_ex_data) && count($all_ex_data) > 0) {                    
                    set_transient('celp-saved-ex', date('H:s:i'), $coingecko_api_cache_time * MINUTE_IN_SECONDS);
                    return $rs = $celpEx->celp_ex_insert($all_ex_data);
                }
            }
        }

        public static function celp_save_ex_pairs_data($ex_id, $page = 2)
        {
            // Do not proceed further if
            if (!celp_check_required_settings()) {
                return;
            }            

            if (get_transient('celp-nopairs-for-' . sanitize_text_field($ex_id))) {
                return false;
            }
            $api_option = get_option("openexchange-api-settings");
            $coingecko_api_key = self::get_coingecko_api_key_celp();
          
            $celpExPairs = new CELP_Exchanges_Pairs;
            //$api_url ="https://api.coinexchangeprice.com/v1/markets/".$ex_id."/all";
            $api_url = celp_get_api_end_point() . "exchanges/" . $ex_id . "/tickers?page=" . $page;
            $headers = array(
                'timeout' => 120,
                'sslverify' => true,
                'headers' => array(
                    celp_get_api_key_end_point() => $coingecko_api_key
                )
            );
            $request = wp_remote_get($api_url, $headers);
            if (is_wp_error($request)) {
                return false; // Bail early
            }          
            $body = wp_remote_retrieve_body($request);
            $ex_data = json_decode($body);           
          
            if ($ex_data) {
                celp_track_coingecko_api_hit();
                $ex_data = celpobjectToArray($ex_data);
                $save_it['ex_id'] = $ex_id;
                $save_it['name'] = isset($ex_data['name'])?$ex_data['name']:"";
                $all_ex_data = array();
                  if (isset($ex_data['tickers']) && is_array($ex_data['tickers'])) {
                    foreach ($ex_data['tickers'] as $index => $pair) {
                        $save_it['pair'] = $pair['base'] . '/' . $pair['target'];
                        $save_it['coin_id'] = $pair['coin_id'];
                        $save_it['base_symbol'] = $pair['base'];
                        $save_it['target_symbol'] = $pair['target'];
                        $save_it['coin_name'] = ucfirst(str_replace('-', ' ', $pair['coin_id']));
                        $save_it['price_target'] = $pair['last'];
                        $save_it['price_usd'] = $pair['converted_last']['usd'];
                        $save_it['price_btc'] = $pair['converted_last']['btc'];
                        $save_it['volume_usd'] = $pair['converted_volume']['usd'];
                        $save_it['volume_btc'] = $pair['converted_volume']['btc'];
                        $save_it['volume_base'] = $pair['volume'];
                        $save_it['updated'] = strtotime($pair['timestamp']);
                        $save_it['type'] = 'on-exchange';
                        $save_it['trust_score'] = $pair['trust_score'];

                        $all_ex_data[] = $save_it;
                    }
                    if (count($all_ex_data) > 0) {
                        return $rs = $celpExPairs->celp_ex_insert($all_ex_data);
                    }
                }
            } else {
                return false;
            }
        }

        /**
         * This function is used to save coin exchange pair for table used in CMC single page
         *
         * @param string $coin_id Coin id in a string. ex: bitcoin
         *
         * @param int $page_no Each page saves 100 coin pairs. passing 2 as an args will save from 101 to 200
         */
        public static function celp_save_coins_ex_pairs($coin_id, $page_no = 1)
        {
             // Do not proceed further if
             if (!celp_check_required_settings()||(false!=get_transient($coin_id.'-all-markets-saved-bacup'))) {
                return;
            }  
          
            $api_option = get_option("openexchange-api-settings");
            $coingecko_api_key = self::get_coingecko_api_key_celp();
            $coingecko_api_cache_time = isset($api_option['select_cache_time']) ? (int)$api_option['select_cache_time'] : 10;
            $celpExPairs = new CELP_Exchanges_Pairs;
//     $api_url ="https://api.coinexchangeprice.com/v1/markets/all/".$coin_id;
            $api_url = celp_get_api_end_point() . "coins/" . $coin_id . "/tickers?page=" . $page_no;
            $headers = array(
                'timeout' => 120,
                'sslverify' => true,
                'headers' => array(
                    celp_get_api_key_end_point() => $coingecko_api_key
                )
            );
            $request = wp_remote_get($api_url, $headers);
            if (is_wp_error($request)) {
                error_log('failed to save coin ex');
                return false; // Bail early
            }
            if (celp_check_api_errors($request)) {
                if (false == get_transient(sanitize_text_field($coin_id) . '-all-markets-saved-bacup')) {
                    self::celp_save_coins_ex_pairs_bacup($coin_id);                    
                    $timing = $coingecko_api_cache_time * MINUTE_IN_SECONDS;
                    set_transient(sanitize_text_field($coin_id) . '-all-markets-saved-bacup', date('H:s:i'), $timing);                    	
                    return;                        
                }
            }
            $body = wp_remote_retrieve_body($request);
            $ex_data = json_decode($body);
        
            if ($ex_data) {
                celp_track_coingecko_api_hit();
                $all_ex_data = array();
                $ex_data = celpobjectToArray($ex_data);            
                 
                if (isset($ex_data['tickers']) && is_array($ex_data['tickers'])) {
                    foreach ($ex_data['tickers'] as $index => $pair) {
                        $save_it['ex_id']         = sanitize_text_field( $pair['market']['identifier'] );
                        $save_it['name']          = sanitize_text_field( $pair['market']['name'] );
                        $save_it['coin_id']       = sanitize_key( $coin_id );
                        $save_it['pair']          = sanitize_text_field( $pair['base'] . '/' . $pair['target'] );
                        $save_it['base_symbol']   = sanitize_key( $pair['base'] );
                        $save_it['target_symbol'] = sanitize_key( $pair['target'] );
                        $save_it['coin_name']     = sanitize_text_field( ucfirst( str_replace( '-', ' ', $coin_id ) ) );
                        
                        $save_it['price_target']  = isset($pair['last']) && is_numeric($pair['last']) ? floatval($pair['last']) : 0;
                        $save_it['price_usd']     = isset($pair['converted_last']['usd']) && is_numeric($pair['converted_last']['usd']) ? floatval($pair['converted_last']['usd']) : 0;
                        $save_it['price_btc']     = isset($pair['converted_last']['btc']) && is_numeric($pair['converted_last']['btc']) ? floatval($pair['converted_last']['btc']) : 0;
                    
                        $save_it['volume_usd']    = isset($pair['converted_volume']['usd']) && is_numeric($pair['converted_volume']['usd']) ? floatval($pair['converted_volume']['usd']) : 0;
                        $save_it['volume_btc']    = isset($pair['converted_volume']['btc']) && is_numeric($pair['converted_volume']['btc']) ? floatval($pair['converted_volume']['btc']) : 0;
                        $save_it['volume_base']   = isset($pair['volume']) && is_numeric($pair['volume']) ? floatval($pair['volume']) : 0;
                    
                        $save_it['updated'] = strtotime($pair['timestamp']);
                        $save_it['type']          = 'on-coin';
                        $save_it['trust_score']   = sanitize_key( $pair['trust_score'] ?? 'unknown' );
                        $all_ex_data[] = $save_it;
                    }
                }
                if (count($all_ex_data) > 0) {
                    return $rs = $celpExPairs->celp_ex_insert($all_ex_data, false);
                }
            }
        }

        /**
         * This function is used to save coin exchange pair for table used in CMC single page if coingecko api limit reach
         *
         * @param string $coin_id Coin id in a string. ex: bitcoin
         *
         * @param int $page_no Each page saves 100 coin pairs. passing 2 as an args will save from 101 to 200
         */
        public static function celp_save_coins_ex_pairs_bacup($coin_id)
        {
            if (!celp_coin_array($coin_id, true)) {
                return;
            }
            $celpExPairs = new CELP_Exchanges_Pairs;         
            $api_url = self::COINPAPRIKA_API_ENDPOINT . "coins/" . celp_coin_array($coin_id, true) . "/markets?quotes=USD,BTC";
            $request = wp_remote_get($api_url, array('timeout' => 120, 'sslverify' => true));
            if (is_wp_error($request)) {
                error_log('failed to save coin ex');
                return false; // Bail early
            }
            $body = wp_remote_retrieve_body($request);
            $ex_data = json_decode($body, true);         
            $ex_data = array_slice($ex_data, 0, 500);
            if (isset($ex_data['error'])) {
                return;            
            }
            if ($ex_data) {
                $all_ex_data = array();               
                if (is_array($ex_data)) {
                    foreach ($ex_data as $index => $pair) {             
                      
                        $symbols=explode("/",$pair['pair']);
                        $save_it['ex_id'] = $pair['exchange_id'];
                        $save_it['name'] =$pair['exchange_name'];;                    
                        $save_it['pair'] = $pair['pair'];     
                        $save_it['coin_id'] = $coin_id;                
                        $save_it['base_symbol'] = $symbols[0];
                        $save_it['target_symbol'] = $symbols[1];
                        $save_it['coin_name'] = $pair['base_currency_name'];
                        $save_it['price_target'] = $pair['quotes']['USD']['price'];
                        $save_it['price_usd'] = $pair['quotes']['USD']['price'];
                        $save_it['price_btc'] =$pair['quotes']['BTC']['price'];
                        $save_it['volume_usd'] = $pair['quotes']['USD']['volume_24h'];
                        $save_it['volume_btc'] = $pair['quotes']['BTC']['volume_24h'];
                        $save_it['volume_base'] = $pair['quotes']['USD']['volume_24h'];
                        $save_it['updated'] = strtotime($pair['last_updated']);
                        $save_it['type'] ='on-coin';
                        $save_it['trust_score'] = ($pair['trust_score']=="high")?"green":"red";
                        $all_ex_data[] = $save_it;
                    }
                }
              
                if (count($all_ex_data) > 0) {
                    return $rs = $celpExPairs->celp_ex_insert($all_ex_data, false);
                }
            }
        }

        /**
         * This function is used to save coin exchange pair 
         *
         * @param string $coin_id Coin id in a string. ex: binance
         *
         * @param int $page_no Each page saves 100 coin pairs. passing 2 as an args will save from 101 to 200
         */
        public static function celp_save_ex_pairs_bacup($coin_id)
        {
            if (!celp_exchange_array($coin_id)) {
                return;
            }
            $celpExPairs = new CELP_Exchanges_Pairs;         
            $api_url = self::COINPAPRIKA_API_ENDPOINT . "exchanges/" . celp_exchange_array($coin_id) . "/markets?quotes=USD,BTC";
            $request = wp_remote_get($api_url, array('timeout' => 120, 'sslverify' => true));
            if (is_wp_error($request)) {
                error_log('failed to save coin ex');
                return false; // Bail early
            }
            $body = wp_remote_retrieve_body($request);
            $ex_data = json_decode($body, true);
            if ($ex_data) {
                $all_ex_data = array();               
                if (is_array($ex_data)) {
                    foreach ($ex_data as $index => $pair) {
                        $symbols = explode("/", $pair['pair']);
                        $save_it['ex_id'] = sanitize_text_field($coin_id);
                        $save_it['name'] = ucfirst(str_replace('-', ' ', sanitize_text_field($coin_id)));                    
                        $save_it['pair'] = sanitize_text_field($pair['pair']);                     
                        $save_it['base_symbol'] = sanitize_text_field($symbols[0]);
                        $save_it['target_symbol'] = sanitize_text_field($symbols[1]);
                        $save_it['coin_id'] = celp_coin_array($pair['base_currency_id']);
                        $save_it['coin_name'] = sanitize_text_field($pair['base_currency_name']);
                        $save_it['price_target'] = floatval($pair['quotes']['USD']['price']);
                        $save_it['price_usd'] = floatval($pair['quotes']['USD']['price']);
                        $save_it['price_btc'] = floatval($pair['quotes']['BTC']['price']);
                        $save_it['volume_usd'] = floatval($pair['quotes']['USD']['volume_24h']);
                        $save_it['volume_btc'] = floatval($pair['quotes']['BTC']['volume_24h']);
                        $save_it['volume_base'] = floatval($pair['quotes']['USD']['volume_24h']);
                        $save_it['updated'] = strtotime($pair['last_updated']);
                        $save_it['type'] = 'on-exchange';
                        $save_it['trust_score'] = ($pair['trust_score'] == "high") ? "green" : "red";
                        $all_ex_data[] = $save_it;
                    }
                }
              
                if (count($all_ex_data) > 0) {
                    return $rs = $celpExPairs->celp_ex_insert($all_ex_data, false);
                }
            }
        }

        /* USD conversions */

        public static function celp_usd_conversions($currency)
        {
            // use common transient between cmc and ccpw
            $conversions = get_transient(self::CMC_USD_CONVERSION);
            $conversions_option = get_option(self::CMC_USD_CONVERSION);
            if (empty($conversions) || $conversions === "" || empty($conversions_option)) {
                $request = "";
                $api_option = get_option("openexchange-api-settings");
                $api = (isset($api_option['openexchangerate_api'])&&!empty($api_option['openexchangerate_api'])) ? $api_option['openexchangerate_api'] : "";
                if (!empty($api)) {
                    $request = wp_remote_get(self::OPENEXCHANGERATE_API_ENDPOINT . $api . '', array('timeout' => 120, 'sslverify' => true));

                } else {
                    $conversions_option = array('USD' => 1);  
                }
                if (is_wp_error($request)) {
                    return false;
                }

                $currency_ids = array("USD", "AUD", "BRL", "CAD", "CZK", "DKK", "EUR", "HKD", "HUF", "ILS", "INR", "JPY", "MYR", "MXN", "NOK", "NZD", "PHP", "PLN", "GBP", "SEK", "CHF", "TWD", "THB",
                    "TRY", "CNY", "KRW", "RUB", "SGD", "CLP", "IDR", "PKR", "ZAR", "NGN", "JMD");
                $body = wp_remote_retrieve_body($request);
                $conversion_data = json_decode($body);

                if (isset($conversion_data->rates)) {
                    $conversion_data = (array) $conversion_data->rates;
                } else {
                    $conversion_data = array();
                    if (!empty($conversions_option)) {
                        if ($currency == "all") {
                            return $conversions_option;
                        } else {
                            if (isset($conversions_option[$currency])) {
                                return $conversions_option[$currency];
                            }
                        }
                    }
                }

                if (is_array($conversion_data) && count($conversion_data) > 0) {
                    foreach ($conversion_data as $key => $currency_price) {
                        if (in_array($key, $currency_ids)) {
                            $conversions_option[$key] = $currency_price;
                        }
                    }

                    uksort($conversions_option, function ($key1, $key2) use ($currency_ids) {
                        return (array_search($key1, $currency_ids) > array_search($key2, $currency_ids)) ? 1 : -1;
                    });
                    update_option(self::CMC_USD_CONVERSION, $conversions_option);
                    set_transient(self::CMC_USD_CONVERSION, $conversions_option, 12 * HOUR_IN_SECONDS);
                }
            }

            if ($currency == "all") {
                return $conversions_option;
            } else {
                if (isset($conversions_option[$currency])) {
                    return $conversions_option[$currency];
                }
            }
        }

        /**
         * Fetch bitcoin price
         */
        public static function celp_get_btcprice()
        {
            // Do not proceed further if
            if (!celp_check_required_settings()) {
                return;
            }  
            $api_option = get_option("openexchange-api-settings");
            $coingecko_api_key = self::get_coingecko_api_key_celp();
            $coingecko_api_cache_time = isset($api_option['select_cache_time']) ? (int)$api_option['select_cache_time'] : 10;
            $btc_price = get_transient(self::CELP_BTC_PRICE);

            if ($btc_price == false || $btc_price == "") {
                $url = celp_get_api_end_point() . "simple/price?ids=bitcoin&vs_currencies=usd";
                $headers = array(
                    'timeout' => 300,
                    'sslverify' => true,
                    'headers' => array(
                        celp_get_api_key_end_point() => $coingecko_api_key
                    )
                );
                $request = wp_remote_get($url, $headers);
                if (is_wp_error($request)) {
                    return false; // Bail early
                }
                if (celp_check_api_errors($request)) {
                    return self::celp_get_btcprice_bacup();
                }
                $body = wp_remote_retrieve_body($request);
                $response = json_decode($body);
              
                if (!empty($response)) {
                    celp_track_coingecko_api_hit();
                    $btc_price = $response->bitcoin->usd;
                    set_transient(self::CELP_BTC_PRICE, $btc_price, MINUTE_IN_SECONDS * $coingecko_api_cache_time);
                }
            }

            return $btc_price;

        }

        /**
         * Backup API for fetch bitcoin price
         */
        public static function celp_get_btcprice_bacup()
        {
            $btc_price = get_transient(self::CELP_BTC_PRICE);

            if ($btc_price == false || $btc_price == "") {
                $url = self::COINPAPRIKA_API_ENDPOINT . "tickers/btc-bitcoin";
                $request = wp_remote_get($url, array('timeout' => 300, 'sslverify' => true));
                if (is_wp_error($request)) {
                    return false; // Bail early
                }
                $body = wp_remote_retrieve_body($request);
                $response = json_decode($body, true);
               
                if (!empty($response)) {
                    $api_option = get_option("openexchange-api-settings");                  
                    $coingecko_api_cache_time=isset($api_option['select_cache_time']) ?(int)$api_option['select_cache_time'] : 10;
                    $btc_price = $response['quotes']['USD']['price'];

                   set_transient(self::CELP_BTC_PRICE, $btc_price, MINUTE_IN_SECONDS * $coingecko_api_cache_time);
                }
            }
            return $btc_price;
        }

        /**
         * Save data for exchange single page details data
         */
        public static function celp_get_data($ex_id)
        {
            if (empty($ex_id)) {
                return;
            }
            // Do not proceed further if
            if (!celp_check_required_settings()) {
                return;
            }  
            $api_option = get_option("openexchange-api-settings");
            $coingecko_api_key = self::get_coingecko_api_key_celp();
            $coingecko_api_cache_time=isset($api_option['select_cache_time']) ?(int)$api_option['select_cache_time'] : 10;
            $cache_name = 'celp-cached-' . $ex_id . '-exchange';
            $url = celp_get_api_end_point() . "exchanges/" . $ex_id;
            $cache = get_transient($cache_name);
            $exchange_data = null;

            if ($cache == false || $cache == '') {
                $headers = array(
                    'timeout' => 120,
                    'sslverify' => true,
                    'headers' => array(
                        celp_get_api_key_end_point() => $coingecko_api_key
                    )
                );
                $request = wp_remote_get($url, $headers);
                if (is_wp_error($request)) {
                    return false; // Bail early
                }                        
              
                if (celp_check_api_errors($request)) {                    
                    return self::celp_get_data_bacup($ex_id);                   
                }  
                $btc_price = self::celp_get_btcprice();   
                $body = wp_remote_retrieve_body($request);  
                
                $exchange_data = json_decode($body);        
               
                if ($exchange_data != null) {
                    celp_track_coingecko_api_hit();
                    $ex_data = celpobjectToArray($exchange_data);
                 
                    $exchange_data = array();
                    $coin_pairs = array();
                    if (!isset($ex_data['name'])) {
                        return false;
                    }
                    $exchange_data['ex_id'] = $ex_id;
                    $exchange_data['name'] = $ex_data['name'];
                    $exchange_data['logo'] = $ex_data['image'];
                    $exchange_data['country'] = $ex_data['country'];
                    $exchange_data['established'] = $ex_data['year_established'];
                    $exchange_data['volume_24h'] = $ex_data['trade_volume_24h_btc'] * $btc_price;
                    $exchange_data['btc_volume'] = $ex_data['trade_volume_24h_btc'];
                    $exchange_data['facebook'] = $ex_data['facebook_url'];
                    $exchange_data['reddit'] = $ex_data['reddit_url'];
                    $exchange_data['website'] = $ex_data['url'];
                    $exchange_data['telegram'] = $ex_data['telegram_url'];
                    $exchange_data['slack'] = $ex_data['slack_url'];
                    $exchange_data['twitter'] = $ex_data['twitter_handle'];
                    $exchange_data['about'] = $ex_data['description'];

                    $save = array('ex_id' => $ex_id,
                        'about' => $exchange_data['about'],
                        'volume_24h' => $exchange_data['volume_24h'],
                        'btc_volume' => $exchange_data['btc_volume'],
                        'extra_data' => json_encode(array(
                            'facebook' => $ex_data['facebook_url'],
                            'twitter' => $ex_data['twitter_handle'],
                            'reddit' => $ex_data['reddit_url'],
                            'telegram' => $ex_data['telegram_url'],
                            'website' => $ex_data['url'],
                            'slack' => $ex_data['slack_url'],
                            'logo' => $ex_data['image'],
                        ), JSON_UNESCAPED_SLASHES),
                    );
                    $celpEx = new CELP_Exchanges;
                    $query = $celpEx->celp_ex_insert(array($save));

                    $tickers = $ex_data['tickers'];
                    $coin_pair = array();
                    $coin_pairs = array();
                    $coin_pair['ex_id'] = $ex_id;
                    $coin_pair['name'] = $ex_data['name'];
                    if (!empty($tickers)) {
                        foreach ($tickers as $ticker) {
                            // skip the loop if required* values are missing
                            if (!isset($ticker['base']) || !isset($ticker['target']) || !isset($ticker['coin_id']) ||
                                !isset($ticker['converted_last']['usd']) || !isset($ticker['converted_last']['btc'])) {
                                continue;
                            }
                            $coin_pair['pair'] = $ticker['base'] . '/' . $ticker['target'];
                            $coin_pair['coin_id'] = $ticker['coin_id'];
                            $coin_pair['base_symbol'] = $ticker['base'];
                            $coin_pair['target_symbol'] = $ticker['target'];
                            $coin_pair['coin_name'] = ucfirst(str_replace('-', ' ', $ticker['coin_id']));
                            $coin_pair['price_usd'] = $ticker['converted_last']['usd'];
                            $coin_pair['price_btc'] = $ticker['converted_last']['btc'];
                            $coin_pair['volume_usd'] = $ticker['converted_volume']['usd'];
                            $coin_pair['volume_btc'] = $ticker['converted_volume']['btc'];
                            $coin_pair['price_target'] = !isset($ticker['last']) ? '0.0' : $ticker['last'];
                            $coin_pair['updated'] = strtotime($ticker['timestamp']);
                            $coin_pair['type'] = 'on-exchange';
                            $coin_pair['trust_score'] = $ticker['trust_score'];

                            $coin_pairs[] = $coin_pair;
                        }

                        // make sure there is data to add/update in mysql
                        $celpExPairs = new CELP_Exchanges_Pairs;
                        $celpExPairs->celp_ex_insert($coin_pairs);
                    } else {
                        //make sure we don't call coin pair API for this exchange
                        set_transient('celp-nopairs-for-' . $ex_id, date("Y-M-D H:I"), self::CELP_SINGLE_PAGE);
                    }

                    if (!empty($save)) {
                        set_transient($cache_name, current_time('mysql'), self::CELP_SINGLE_PAGE);
                    }
                }
            }

            if ($cache != false || $cache != '' || empty($exchange_data)) {
                $ex_response = array();
                $celpEx = new CELP_Exchanges;
                $i = 1;
                $ex_response = $celpEx->get_exchanges(array("number" => 1, 'ex_id' => $ex_id,
                ));

                if (is_array($ex_response) && isset($ex_response[0])) {
                    $exchange = celpobjectToArray($ex_response[0]);
                    $extra_data = celpobjectToArray(json_decode($exchange['extra_data']));
                    $exchange_data = array_merge($exchange, $extra_data);
                }

            }
            return $exchange_data;
        }

        /**
         * Bacup API for exchanges single page details & pair data
         */
        public static function celp_get_data_bacup($ex_id)
        {
            if (empty($ex_id)) {
                return;
            }
            
            $cache_name = 'celp-cached-' . sanitize_text_field($ex_id) . '-exchange';
            $url = self::COINPAPRIKA_API_ENDPOINT . "exchanges/" . celp_exchange_array($ex_id) . "?quotes=USD,BTC";
            
            $cache = get_transient($cache_name);
            $exchange_data = null;          
            if ($cache == false || $cache == '') {
                $request = wp_remote_get($url, array('timeout' => 120, 'sslverify' => true));
                if (is_wp_error($request)) {
                    return false; // Bail early
                }
                $btc_price = self::celp_get_btcprice();
                $body = wp_remote_retrieve_body($request);
                $exchange_data = json_decode($body, true);
                if (isset($exchange_data['error'])) {
                    return;
                }
                if ($exchange_data != null) {
                    $ex_data = $exchange_data;
                    $exchange_data = array();
                    $coin_pairs = array();
                    if (!isset($ex_data['name'])) {
                        return false;
                    }
                    $save = array('ex_id' => $ex_id,
                        'about' => $ex_data ['description'],
                        'volume_24h' => $ex_data['quotes']['USD']['reported_volume_24h'],
                        'btc_volume' => $ex_data['quotes']['BTC']['reported_volume_24h'],
                        'extra_data' => json_encode(array(                            
                            'twitter' => isset($ex_data['links']['twitter'][0])?str_replace("https://twitter.com/","",$ex_data['links']['twitter'][0]):"",
                            'website' =>$ex_data['links']['website'][0],                           
                            'logo' => "https://static.coinpaprika.com/exchanges/".celp_exchange_array($ex_id)."/logo.png",
                        ), JSON_UNESCAPED_SLASHES),
                    );
                    $celpEx = new CELP_Exchanges;
                    $query = $celpEx->celp_ex_insert(array($save));

                    if (!empty($save)) {
                        set_transient($cache_name, current_time('mysql'), self::CELP_SINGLE_PAGE);
                    }
                    return self::celp_save_ex_pairs_bacup($ex_id);
                    
                }
            }
            if ($cache != false || $cache != '' || empty($exchange_data)) {
                $ex_response = array();
                $celpEx = new CELP_Exchanges;
                $i = 1;
                $ex_response = $celpEx->get_exchanges(array("number" => 1, 'ex_id' => sanitize_text_field($ex_id)));

                if (is_array($ex_response) && isset($ex_response[0])) {
                    $exchange = celpobjectToArray($ex_response[0]);
                    $extra_data = celpobjectToArray(json_decode($exchange['extra_data']));
                    $exchange_data = array_merge($exchange, $extra_data);
                }

            }
            return $exchange_data;
         
        }



    }
}
