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

    public function __construct()
    {

        // exchange details shortcodes for single pages
        add_shortcode('celp-detail', array($this, 'celp_single_page_shortcode'));
        add_shortcode('celp-currencies-pairs', array($this, 'celp_single_currency_pairs'));
        add_shortcode('celp-dynamic-title', array($this, 'celp_dynamic_title'));
        add_shortcode('celp-dynamic-description', array($this, 'celp_dynamic_description'));
        add_shortcode('celp-description', array($this, 'celp_description'));
        add_shortcode('celp-exchange-name', array($this, 'celp_exchange_name'));
        add_shortcode('celp-affiliate-link', array($this, 'celp_affiliate_link'));
        add_shortcode('celp-twitter-feed', array($this, 'celp_twitter_feed'));

        add_shortcode('celp-comments', array($this, 'celp_comment_box'));
        add_shortcode('celp-single-details-advanced-design', array($this, 'celp_shortcode_advanced_details_page_design'));

        add_action('wp_ajax_celp_get_pairs_list', array($this, 'celp_get_ex_pairs_list'));
        add_action('wp_ajax_nopriv_celp_get_pairs_list', array($this, 'celp_get_ex_pairs_list'));

        if (!is_admin()) {
            add_filter('the_title', array($this, 'celp_custom_page_title'), 10, 2);
        }

        /* RankMath SEO Hooks */
        add_filter('rank_math/frontend/title', array($this, 'celp_ex_name_to_title'));
        add_filter('rank_math/frontend/description', array($this, 'celp_open_graph_desc'));
        add_filter('rank_math/frontend/canonical', array($this, 'rankmath_exchange_canonical'));

        // filters and hooks for SEO title and description
        add_filter('pre_get_document_title', array($this, 'celp_ex_name_to_title'), 10, 1);
        add_filter('wpseo_title', array($this, 'celp_ex_name_to_title'), 10, 1);
        add_action('wp_head', array($this, 'celp_generate_meta_desc'), 2);
        add_filter('wpseo_metadesc', array($this, 'celp_open_graph_desc'), 10, 1);
        add_filter('wpseo_opengraph_desc', array($this, 'celp_open_graph_desc'), 10, 1);
        add_action('wp', array($this, 'celp_remove_canonical'));

    }

    /*-------------------------------------------------------|
    |      Generate Canonical URL for RankMath SEO Plugin     |
    |--------------------------------------------------------|
     */
    public function rankmath_exchange_canonical()
    {

        $single_page_id = celp_get_single_page_id();
        if (!is_page($single_page_id)) {
            return;
        }

        $ex_id = (string) trim(get_query_var('exchange-id'));
        $slug = !empty(celp_get_option('exchange-page-slug')) ? celp_get_option('exchange-page-slug') : "exchange";
        $ex_url = esc_url(home_url($slug . '/' . $ex_id . '/', '/'));

        echo '<link rel="canonical" href="' . $ex_url . '" />';
    }
/*
Exchange single page shortcode for
representation all data
 */

    public function celp_single_page_shortcode($atts, $content = null)
    {
        $atts = shortcode_atts(array(
            'id' => '',
        ), $atts, 'celp-detail');
        $output = '';

        wp_enqueue_style('celp-styles');
        if (get_query_var('exchange-id')) {
            $ex_id = (string) trim(get_query_var('exchange-id'));
            $exchange_data = CELP_api_data::celp_get_data($ex_id);

            if ($exchange_data && is_array($exchange_data)) {
                $e_id = sanitize_text_field($exchange_data['ex_id']);
                $e_name = sanitize_text_field($exchange_data['name']);
                $e_country = !empty($exchange_data['country']) ? sanitize_text_field($exchange_data['country']) : 'N/A';
                $e_established_year = !empty($exchange_data['established']) ? sanitize_text_field($exchange_data['established']) : 'N/A';
                $e_exchange_volusd = !empty($exchange_data['volume_24h']) ? floatval($exchange_data['volume_24h']) : 0;
                $e_exchange_volbtc = !empty($exchange_data['btc_volume']) ? celp_format_number($exchange_data['btc_volume']) : 0;
                $local_logo = CELP_PATH . 'assets/logos/logo128/' . $e_id . '.png';

                if (file_exists($local_logo)) {
                    $e_logo = CELP_URL . 'assets/logos/logo128/' . $e_id . '.png';
                } else {
                    $e_logo = !empty($exchange_data['logo']) ? esc_url($exchange_data['logo']) : 'https://res.cloudinary.com/coolplugins/image/upload/exchanges-logo/128x128/' . $e_id . '.png';
                }

                $currency = celp_selected_currency();
                $selected_currency = sanitize_text_field($currency['c_name']);
                $currency_price = floatval($currency['c_price']);

                if ($selected_currency == "USD") {
                    $volume = celp_fiat_cur_symbol($selected_currency) . celp_format_number($e_exchange_volusd);
                } else {
                    $volusd = (float) $e_exchange_volusd;
                    $vol_conversion = $volusd * $currency_price;
                    $volume = celp_fiat_cur_symbol($selected_currency) . celp_format_number($vol_conversion);
                }

                $vol_html = sprintf("%s (%s %s)",
                    $volume,
                    esc_html($e_exchange_volbtc),
                    __('BTC', 'celp')
                );
                // $output.= '<div class="celp-exchange-details-container">';
                $output .= '<div class="ex_details">';
                $output .= '<div class="ex_logo_section"><div class="ex_logo_top"><img onerror=this.src="' . CELP_URL . 'assets/logos/logo128/exchange-logo.png" alt="' . esc_attr($e_name) . '" src="' . esc_url($e_logo) . '">
			<br/><span class="ex_name"> ' . esc_html($e_name) . '</span></div>';
                $affi_con = get_custom_content($e_id);

                if (isset($affi_con['affiliate_link']) && !empty($affi_con['affiliate_link'])) {
                    $e_website = esc_url($affi_con['affiliate_link']);
                    $e_website_linkname = !empty($exchange_data['website']) ? esc_url($exchange_data['website']) : $e_website;

                } else if (!empty($exchange_data['website'])) {
                    $e_website = esc_url($exchange_data['website']);
                    $e_website_linkname = $e_website;
                }
                $output .= '<a target="_blank" rel="nofollow" href="' . esc_url($e_website) . '" class="trading-button">' . __('Start Crypto Trading', 'celp') . '</a></div>';

                $output .= '<table><tbody>';
                $output .= '<tr><th><i class="cmc_icon-exchange"></i> ' . __('Exchange Name', 'celp') . '</th><td>' . esc_html($e_name) . '</td></tr>';
                $output .= '<tr>
				<th><i class="cmc_icon-volume"></i></i> ' . __('Volume (24H)', 'celp') . '</th>
				<td class="exchange-volume">' . esc_html($volume) . '<br>
				<span class="usd_btc">' . esc_html($e_exchange_volbtc) . __(' BTC', 'celp') . '</span></td>
				</tr>';
                $output .= '<tr><th><i class="cmc_icon-globe"></i> ' . __('Country', 'celp') . '</th><td>' . esc_html($e_country) . '</td></tr>';
                $output .= '<tr><th><i class="cmc_icon-calendar"></i> ' . __('Established Year', 'celp') . '</th><td>' . esc_html($e_established_year) . '</td></tr>';

                if (!empty($e_website)) {

                    $output .= '<tr><th><i class="cmc_icon-website"></i> ' . __('Website', 'celp') . '</th>
				<td><a target="_blank" rel="nofollow" title="' . esc_attr($e_name) . '" href="' . esc_url($e_website) . '">';
                    if (strlen($e_website_linkname) >= 32) {
                        $excerpt = substr($e_website_linkname, 0, 32);
                        $output .= esc_html($excerpt) . '...';
                    } else {
                        $output .= esc_html($e_website_linkname);
                    }

                    $output .= '</a></td></tr>';
                }

                if (!empty($exchange_data['twitter'])) {
                    $twitter_url = esc_url($exchange_data['twitter']);
                    if (strpos($twitter_url, 'http') === false) {
                        $twitter_url = "https://twitter.com/" . $twitter_url;
                    }
                    $output .= '<tr><th><i class="cmc_icon-twitter"></i> ' . __('Twitter', 'celp') . '</th><td><a target="_blank" rel="nofollow" title="' . esc_attr($e_name) . '" href="' . esc_url($twitter_url) . '">';
                    if (strlen($exchange_data['twitter']) >= 32) {
                        $excerpt = substr($exchange_data['twitter'], 0, 32);
                        $output .= esc_html($excerpt) . '...';
                    } else {
                        $output .= esc_html($twitter_url);
                    }
                    $output .= '</a></td></tr>';
                }
                if (!empty($exchange_data['telegram'])) {
                    $output .= '<tr><th><i class="cmc_icon-telegram"></i> ' . __('Telegram', 'celp') . '</th><td><a target="_blank" rel="nofollow" title="' . esc_attr($e_name) . '" href="' . esc_url($exchange_data['telegram']) . '">';
                    if (strlen($exchange_data['telegram']) >= 32) {
                        $excerpt = substr($exchange_data['telegram'], 0, 32);
                        $output .= esc_html($excerpt) . '...';
                    } else {
                        $output .= esc_html($exchange_data['telegram']);
                    }
                    $output .= '</a></td></tr>';
                }
                if (!empty($exchange_data['reddit'])) {
                    $output .= '<tr><th><i class="cmc_icon-reddit"></i> ' . __('Reddit', 'celp') . '</th><td><a target="_blank" rel="nofollow" title="' . esc_attr($e_name) . '" href="' . esc_url($exchange_data['reddit']) . '">';
                    if (strlen($exchange_data['reddit']) >= 32) {
                        $excerpt = substr($exchange_data['reddit'], 0, 32);
                        $output .= esc_html($excerpt) . '...';
                    } else {
                        $output .= esc_html($exchange_data['reddit']);
                    }
                    $output .= '</a></td></tr>';
                }
                if (!empty($exchange_data['facebook'])) {
                    $output .= '<tr><th><i class="cmc_icon-facebook"></i> ' . __('Facebook', 'celp') . '</th><td><a target="_blank" rel="nofollow" title="' . esc_attr($e_name) . '" href="' . esc_url($exchange_data['facebook']) . '">';
                    if (strlen($exchange_data['facebook']) >= 32) {
                        $excerpt = substr($exchange_data['facebook'], 0, 32);
                        $output .= esc_html($excerpt) . '...';
                    } else {
                        $output .= esc_html($exchange_data['facebook']);
                    }
                    $output .= '</a></td></tr>';
                }
                if (!empty($exchange_data['slack'])) {
                    $output .= '<tr><th><i class="cmc_icon-slack"></i> ' . __('Slack', 'celp') . '</th><td><a target="_blank" rel="nofollow" title="' . esc_attr($e_name) . '" href="' . esc_url($exchange_data['slack']) . '">';
                    if (strlen($exchange_data['slack']) >= 32) {
                        $excerpt = substr($exchange_data['slack'], 0, 32);
                        $output .= esc_html($excerpt) . '...';
                    } else {
                        $output .= esc_html($exchange_data['slack']);
                    }
                    $output .= '</a></td></tr>';
                }
                if (!empty($exchange_data['blog'])) {
                    $output .= '<tr><th><i class="cmc_icon-blog"></i> ' . __('Blog', 'celp') . '</th><td><a target="_blank" rel="nofollow" title="' . esc_attr($e_name) . '" href="' . esc_url($exchange_data['blog']) . '">';
                if (strlen($exchange_data['blog']) >= 32) {
                        $excerpt = substr($exchange_data['blog'], 0, 32);
                        $output .= esc_html($excerpt) . '...';
                    } else {
                        $output .= esc_html($exchange_data['blog']);
                    }
                    $output .= '</a></td></tr>';
                }

                if (!empty($exchange_data['top_country'])) {
                    $output .= '<tr><th><i class="cmc_icon-globe"></i> ' . __('Top Country', 'celp') . '</th><td>' . esc_html($exchange_data['top_country']) . '</td></tr>';
                }

                $output .= '</tbody></table></div>';
                return $output;
            } else {
                return __('Something wrong with URL', 'celp');
            }

        }

    }

// currencies pair shortcode for single page
    public function celp_single_currency_pairs($atts, $content = null)
    {
        $atts = shortcode_atts(array(
            'id' => '',
        ), $atts, 'celp-detail');
        $output = '';
        $currency_pairs = array();
        celp_load_assets($page = 'ex_single');

        if (get_query_var('exchange-id')) {
            $ex_id = (string) trim(get_query_var('exchange-id'));
            $celp_prev = __('Previous', 'celp');
            $celp_next = __('Next', 'celp');
            $celp_show = __('Show', 'celp');
            $celp_search = __('Search', 'celp');
            $celp_entries = __('Entries', 'celp');
            $no_rs_found = __('No Pair Found', 'celp');
            $default_logo = CELP_URL . 'assets/logos/logo32/default-logo.png';
            $celp_show_entries = sprintf("%s _MENU_ %s", $celp_show, $celp_entries);

            // showing START to END of TOTAL entries
            $celp_showing = __('Showing', 'celp');
            $celp_to = __('to', 'celp');
            $celp_of = __('of', 'celp');
            $celp_entry = __('entries', 'celp');
            $celp_showing_entries = sprintf("%s _START_ %s _END_ %s _TOTAL_ %s", $celp_showing, $celp_to, $celp_of, $celp_entry);

            // filtered from _MAX_ total entries
            $celp_filter = __('filtered from', 'celp');
            $celp_total_entries = __('total entries', 'celp');
            $celp_filter_entries = sprintf("%s  _MAX_ %s", $celp_filter, $celp_total_entries);

            // Loading records preloader
            $celp_loading = __('Loading', 'celp');

            // Initialize Titan
            if (function_exists('cmc_extra_get_option')) {
                $cmc_slug = cmc_extra_get_option('single-page-slug');
                if (empty($cmc_slug)) {
                    $cmc_slug = 'currencies';
                }
            } else {
                $cmc_slug = 'currencies';
            }

            // Prevent from creating hyper link if CMC plugin is not active
            $coin_single_slug = 'false';

            if (class_exists('CoinMarketCap')) {
                $coin_single_slug = esc_url(home_url($cmc_slug, '/'));
            }

            $i = 0;
            $currency = celp_selected_currency();
            $selected_currency = sanitize_text_field($currency['c_name']);
            $currency_symbol = celp_fiat_cur_symbol($currency['c_name']);
            $currency_price = floatval($currency['c_price']);

            $output .= '<div class="currecies-pairs" data-default-logo="' . esc_attr($default_logo) . '">
		<table id="celp_currency_pairs"
		 class="celp-datatable table table-striped table-bordered"
		 data-per-page="25"
		 data-coin-symbol="' . esc_attr($currency_symbol) . '"
		 data-coin-price="' . esc_attr($currency_price) . '"
		 data-show-entries="' . esc_attr($celp_show_entries) . '" data-prev="' . esc_attr($celp_prev) . '"
		 data-next="' . esc_attr($celp_next) . '" data-search="' . esc_attr($celp_search) . '"
		 data-ex-id="' . esc_attr($ex_id) . '"
		 data-zero-records="' . esc_attr($no_rs_found) . '"
		 data-showing_entries="' . esc_attr($celp_showing_entries) . '"
		 data-filter_entries="' . esc_attr($celp_filter_entries) . '"
		 data-loading_records="' . esc_attr($celp_loading) . '"
		 ><thead>
		<tr>
			<th  data-classes="celp-rank" data-index="id">' . __('#', 'celp') . '</th>
			<th  data-classes="celp-coin_name" data-index="coin_name" data-coin-single-slug="' . esc_attr($coin_single_slug) . '">' . __('Currency', 'celp') . '</th>
			<th  data-classes="celp-pair" data-index="pair">' . __('Pair', 'celp') . '</th>
			<th  data-classes="celp-price" data-index="price">' . __('Price', 'celp') . '</th>
			<th  data-classes="celp-volume_24h" data-index="volume_24h" class="all">' . __('Volume (24h)', 'celp') . '</th>
			<th  data-classes="celp-updated" data-index="updated" class="all">' . __('Updated', 'celp') . '</th>
			<th  data-classes="celp-trust_score" data-index="trust_score" class="all">' . __('Trust Score', 'celp') . '</th>
		</tr></thead>';
            $output .= '</table>
			<!-- You must provide credits to API data providers according to their API use terms otherwise data access will be blocked by API providers - coingecko.com--->
			<div class="api-credits"><a href="https://www.coingecko.com" rel="follow" target="_blank">Data by Coingecko API</a></div>
			</div>';
            return $output;
        } else {
            return __('Something wrong with URL', 'celp');
        }
    }

/*
|--------------------------------------------------------------------------
| CELP list server side processing ajax callback
|--------------------------------------------------------------------------
 */
    public function celp_get_ex_pairs_list()
    {
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field($_POST['_wpnonce']) : (isset($_SERVER['HTTP_X_WP_NONCE']) ? sanitize_text_field($_SERVER['HTTP_X_WP_NONCE']) : '');

        if (!wp_verify_nonce($nonce, 'celp-ex-list')) {
            $response = array("draw" => 1, "recordsTotal" => 1, "recordsFiltered" => 1, "data" => [], 'error' => 'nonce_failed');

            echo json_encode($response);
            wp_die();
        }

        $all_pairs = array();
        $celpExPairs = new CELP_Exchanges_Pairs;
        $ex_id = sanitize_text_field($_POST['ex_id']);

        $order_col_name = 'volume_usd';
        $order_type = 'DESC';
        $start_point = isset($_POST['start']) ? absint($_POST['start']) : 0;
        $data_all = is_array($celpExPairs->get_exchange_coin_pairs($ex_id)) ? count($celpExPairs->get_exchange_coin_pairs($ex_id)) : 10;
        $i = $start_point;
        $data_load = isset($_POST['length']) ? absint($_POST['length']) : 25;
        $current_page = isset($_POST['draw']) ? absint($_POST['draw']) : 1;
        $exchange_pairs = $celpExPairs->get_pairs(array(
            "number" => $data_load,
            'offset' => $start_point,
            'ex_id' => $ex_id,
            'order' => $order_type,
            'type' => 'on-exchange',
            'coin_search' => sanitize_text_field($_POST['search']),
        ));

        $available = get_transient('coins_arr');
        if (is_array($exchange_pairs)) {
            foreach ($exchange_pairs as $index => $data) {
                $pair = (array) $data;
                $i++;
                $pair_data['id'] = $i;
                $pair_data['availability'] = !is_array($available) || !array_key_exists($pair['coin_id'], $available);
                $pair_data['coin_id'] = sanitize_text_field($pair['coin_id']);
                $pair_data['coin_symbol'] = sanitize_text_field($pair['base_symbol']);
                $pair_data['coin_name'] = sanitize_text_field($pair['coin_name']);
                $pair_data['volume_24h'] = sanitize_text_field($pair['volume_usd']);
                $pair_data['ex_id'] = sanitize_text_field($pair['ex_id']);
                $pair_data['price'] = sanitize_text_field($pair['price_usd']);
                if (strlen($pair['pair']) > 20) {
                    $p_arr = explode("/", $pair['pair']);
                    $base = isset($p_arr[0]) && strlen($p_arr[0]) > 8 ? substr($p_arr[0], 0, 5) . '..' : $p_arr[0];
                    $target  = isset($p_arr[1]) && strlen($p_arr[1]) > 8 ? substr($p_arr[1], 0, 5) . '..' : $p_arr[1];
                    $pair_data['pair'] = sanitize_text_field($base . '/' . $target );
                } else {
                    $pair_data['pair'] = sanitize_text_field($pair['pair']);
                }
                $pair_data['updated'] = sanitize_text_field(get_timeago($pair['updated']));
                $pair_data['trust_score'] = sanitize_text_field($pair['trust_score']);
                $all_pairs[] = $pair_data;
            }
        }
        $response = array("draw" => $current_page, "recordsTotal" => $data_all, "recordsFiltered" => $data_all, "data" => $all_pairs);
        echo wp_json_encode($response);
        wp_die();
    }

// creating dynamic page title
    public function celp_custom_page_title($title, $id = null)
    {
        $single_page_id = celp_get_single_page_id();
        if ($id == $single_page_id) {
            $title = $this->celp_create_ex_title();
        }
        return $title;
    }

    public function celp_dynamic_title($atts, $content = null)
    {
        $single_page_id = celp_get_single_page_id();
        if (is_page($single_page_id)) {
            $content = $this->celp_create_ex_title();
        }
        return $content;
    }

// generating dynamic wp title
    public function celp_ex_name_to_title($ex_title)
    {
        global $post;
        if ($post == null) {
            return;
        }
        $single_page_id = celp_get_single_page_id();
        if ($post->ID == $single_page_id) {
            $ex_title = $this->celp_create_ex_title();
        }

        /* Return the title. */
        return $ex_title;
    }

// exchange name shortcode
    public function celp_exchange_name($atts, $content = null)
    {
        $ex_title = '';
        $ex_id = (string) trim(get_query_var('exchange-id'));
        $exchange_data = CELP_api_data::celp_get_data($ex_id);
        $ex_title = isset($exchange_data['name']) ? sanitize_text_field($exchange_data['name']) : '';

        return $ex_title;
    }
// generating dynamic wp-title and page titles
    public function celp_create_ex_title()
    {

        $ex_id = (string) trim(get_query_var('exchange-id'));
        $exchange_data = CELP_api_data::celp_get_data($ex_id);

        $ex_title = isset($exchange_data['name']) ? sanitize_text_field($exchange_data['name']) : "";

        if (celp_get_option('dynamic_title')) {
            $dynamic_title = celp_get_option('dynamic_title');
        } else {
            $dynamic_title = '[name] Exchange Info, Markets & Trading Volume';
        }
        $dynamic_array = array($ex_title);
        $placeholders = array('[name]');
        $title_txt = str_replace($placeholders, $dynamic_array, $dynamic_title);

        return $title_txt;
    }

    public function celp_remove_canonical()
    {
        $single_page_id = celp_get_single_page_id();
        if (is_page($single_page_id)) {
            add_filter('wpseo_canonical', '__return_false', 10, 1);
        }
    }
//creating dynamic description
    public function celp_create_ex_desc()
    {

        if (get_query_var('exchange-id')) {

            $ex_id = (string) trim(get_query_var('exchange-id'));
            $exchange_data = CELP_api_data::celp_get_data($ex_id);

            if ($exchange_data && is_array($exchange_data)) {
                $e_id = sanitize_text_field($exchange_data['ex_id']);
                $e_name = isset($exchange_data['name']) ? sanitize_text_field($exchange_data['name']) : '';
                $e_currency_support = isset($exchange_data['coin_supports']) ? intval($exchange_data['coin_supports']) : 0;
                $e_trading_pairs = isset($exchange_data['trading_pairs']) ? intval($exchange_data['trading_pairs']) : 0;
                $e_exchange_volusd = isset($exchange_data['volume_24h']) ? floatval($exchange_data['volume_24h']) : 0;
                $e_exchange_volbtc = isset($exchange_data['btc_volume']) ? celp_format_number($exchange_data['btc_volume']) : 0;
                $exchange_est_year = (isset($exchange_data['established']) && !empty($exchange_data['established'])) ? sanitize_text_field($exchange_data['established']) : __('N/A', 'celp');
                $exchange_country = (isset($exchange_data['country']) && !empty($exchange_data['country'])) ? sanitize_text_field($exchange_data['country']) : __('N/A', 'celp');
                $currency = celp_selected_currency();
                $selected_currency = sanitize_text_field($currency['c_name']);
                $currency_price = floatval($currency['c_price']);

                if ($selected_currency == "USD") {
                    $volume = celp_fiat_cur_symbol($selected_currency) . celp_format_number($e_exchange_volusd);
                } else {
                    $volusd = (float) $e_exchange_volusd;
                    $vol_conversion = $volusd * $currency_price;
                    $volume = celp_fiat_cur_symbol($selected_currency) . celp_format_number($vol_conversion);
                }

                $vol_html = sprintf("%s (%s %s)",
                    $volume,
                    esc_html($e_exchange_volbtc),
                    __('BTC', 'celp')
                );

                $ex_title = $e_name;
                if (celp_get_option('dynamic_description')) {
                    $dynamic_desc = celp_get_option('dynamic_description');
                } else {
                    $dynamic_desc = '[name] exchange 24 hours trading volume is [volume]. [name] is established in year [established-year]. This cryptocurrency exchange is located in [established-country]';
                }

                $dynamic_array = array($ex_title, $vol_html, $exchange_est_year, $exchange_country);
                $placeholders = array('[name]', '[volume]', '[established-year]', '[established-country]');
                $desc_txt = str_ireplace($placeholders, $dynamic_array, $dynamic_desc);

                return $desc_txt;
            }

        }
    }

// generating description meta for SEO
    public function celp_generate_meta_desc()
    {
        $single_page_id = celp_get_single_page_id();
        if (is_page($single_page_id) && !class_exists('RankMath')) {
            if (!defined('WPSEO_VERSION')) {
                $desc = $this->celp_create_ex_desc();
                echo '<meta name="description" content="' . esc_attr($desc) . '" />';
            }
            $ex_id = (string) trim(get_query_var('exchange-id'));
            $slug = !empty(celp_get_option('exchange-page-slug')) ? celp_get_option('exchange-page-slug') : "exchange";
            $ex_url = home_url($slug . '/' . $ex_id . '/', '/');

            echo '<link rel="canonical" href="' . esc_url($ex_url) . '" />';
        }
    }

    public function celp_open_graph_desc($desc)
    {
        $single_page_id = celp_get_single_page_id();
        if (is_page($single_page_id)) {
            return $this->celp_create_ex_desc();
        }
        return $desc;
    }
// creating shortcode for generating dynamic description
    public function celp_dynamic_description($atts, $content = null)
    {
        $atts = shortcode_atts(array(
            'id' => '',
        ), $atts, 'celp-dynamic-description');

        $desc = $this->celp_create_ex_desc();
        return $output = '<div class="celp_dynamic_description">' . wp_kses_post($desc) . '</div>';

    }
    //facebook comment box for exchange detial page
    public function celp_comment_box($atts, $content = null)
    {
        $atts = shortcode_atts(array(
            'id' => '',
        ), $atts);
        $output = '';
        global $wp;
        $page_url = esc_url(home_url($wp->request, '/'));

        global $post;
        $page_id = $post->ID;
        $single_page_id = celp_get_single_page_id(); //get_option('cmc-coin-single-page-id');
        $fb_app_id = celp_get_option('celp_fb_id');
        if (is_page($page_id) && $page_id == $single_page_id && !empty($fb_app_id)) {

            $app_id = $fb_app_id ? $fb_app_id : '1798381030436021';

            $output .= ' <div id="disqus_thread"></div>
                    <script>
                    (function() {
                        var d = document, s = d.createElement("script");
                        s.src = "https://' . $app_id . '.disqus.com/embed.js";
                        s.setAttribute("data-timestamp", +new Date());
                        (d.head || d.body).appendChild(s);
                    })();
                    </script>
                   <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>';

        }

        return $output;

    }

    //celp exchange description
    public function celp_description($atts, $content = null)
    {
        $atts = shortcode_atts(array(
            'id' => '',
        ), $atts, 'celp-description');

        $output = '';
        $desc = '';
        $api_ex_desc = celp_get_option('api_ex_desc', true);
        $ex_id = (string) trim(get_query_var('exchange-id'));
        $custom_content = get_custom_content($ex_id);

        if (isset($custom_content['desc']) && !empty($custom_content['desc'])) {
            $desc = $custom_content['desc'];
        } else {
            $exchange_data = CELP_api_data::celp_get_data($ex_id);
            if (!is_array($exchange_data) || count($exchange_data) < 1) {
                return false;
            }
            $ex_about = isset($exchange_data['about']) ?  sanitize_text_field($exchange_data['about']) : '';
      
            if ($api_ex_desc == 'show') {
                $desc = $ex_about;
            }
        }
        $output .= '<div class="celp-exchange-details">';
        $output .= '<div class="celp_desc"><p>' . wp_kses_post($desc) . '</p></div>';
        return $output;
    }

    public function celp_affiliate_link($atts, $content = null)
    {
        $output = '';
        $link = "#";
        $ex_id = (string) trim(get_query_var('exchange-id'));
        $custom_content = get_custom_content($ex_id);
        if (isset($custom_content['affiliate_link']) && !empty($custom_content['affiliate_link'])) {
            $link = $custom_content['affiliate_link'];
        } else {
            $exchange_data = CELP_api_data::celp_get_data($ex_id);
            $exchange_website = isset($exchange_data['website']) ? esc_url($exchange_data['website']) : '';
            $link = $exchange_website;
        }

        $output .= '<span class="celp_affiliate_links">
		<a target="_blank" class="celp_trade_now" href="' . esc_url($link) . '">' . __('Trade', 'celp') . '</a>
		</span>';

        return $output;
    }

    //Shortcode for Twitter Feeds
    public function celp_twitter_feed()
    {

        if (get_query_var('exchange-id')) {
            $ex_id = (string) trim(get_query_var('exchange-id'));

            $exchange_data = CELP_api_data::celp_get_data($ex_id);
            if (isset($exchange_data['twitter']) && !empty($exchange_data['twitter'])) {
                global $wpdb;
                $coin_id = (string) trim(get_query_var('exchange-id'));

                // The Query
                $query = array('post_type' => 'celp-description', 'meta_value' => $coin_id);
                $the_query = new WP_Query($query);
                $twitter_name = "";
                // The Loop
                if ($the_query->have_posts()) {
                    while ($the_query->have_posts()) {
                        $the_query->the_post();
                        $cmcd_id = get_the_ID();

                        $coin_twt_name = get_post_meta($cmcd_id, 'cmc_single_settings_coin_twt', true);
                        $twitter_name = sanitize_text_field($coin_twt_name);
                    }
                } else {
                    $coin_data = CELP_api_data::celp_get_data($coin_id);
                    $twitter_name = '';
                    if (isset($coin_data['twitter']) && $coin_data['twitter'] != "N/A") {
                        $twitter_name = sanitize_text_field($coin_data['twitter']);
                    }
                }

                $output = '';
                $output .= $this->celp_advance_twitter_feed_loader();
                wp_enqueue_script('celp-simple', CELP_URL . 'assets/js/celp-simple.js', array('jquery'));

                if (isset($twitter_name) && !empty($twitter_name)) {
                    wp_enqueue_script('celp-twitter-widget', CELP_URL . 'assets/js/twitter-widget.js', null, CELP_VERSION);
                    $output .= '<a class="twitter-timeline" href="https://twitter.com/' . $twitter_name . '?ref_src=twsrc%5Etfw"></a>';

                    return $output;

                } else {
                    return false;
                }
            }
        }
    }

    public function celp_advance_twitter_feed_loader()
    {
        return "<div class='celp_tweet_loader'>
		<div class='ph-item'>
			<div class='ph-col-12'>
				<div class='ph-row'>
					<div class='ph-col-6 big'></div>
					<div class='ph-col-4  big'></div>
					<div class='ph-col-2 big'></div>
					<div class='ph-col-4'></div>
					<div class='ph-col-8 '></div>
					<div class='ph-col-6'></div>
					<div class='ph-col-6 '></div>
					<div class='ph-col-12'></div>
				</div>
			</div>
		</div></div>";
    }

    public function celp_twitter_embed()
    {
        global $wpdb;
        if (get_query_var('exchange-id')) {
            $coin_id = (string) trim(get_query_var('exchange-id'));
            // The Query
            $query = array('post_type' => 'celp-description', 'meta_value' => $coin_id);
            $the_query = new WP_Query($query);
            $twitter_name = "";
            // The Loop
            if ($the_query->have_posts()) {
                while ($the_query->have_posts()) {
                    $the_query->the_post();
                    $cmcd_id = get_the_ID();

                    $coin_twt_name = get_post_meta($cmcd_id, 'cmc_single_settings_coin_twt', true);
                    $twitter_name = sanitize_text_field($coin_twt_name);
                }
            } else {
                $coin_data = CELP_api_data::celp_get_data($coin_id);
                $twitter_name = '';
                if (isset($coin_data['twitter']) && $coin_data['twitter'] != "N/A") {
                    $twitter_name = sanitize_text_field($coin_data['twitter']);
                }
            }

            $output = '';

            if (isset($twitter_name) && !empty($twitter_name)) {

                wp_enqueue_script('celp-twitter-widget', CELP_URL . 'assets/js/twitter-widget.js', null, CELP_VERSION);

                $output .= '<a class="twitter-timeline" href="https://twitter.com/' . $twitter_name . '?ref_src=twsrc%5Etfw"></a>';
                return $output;

            } else {
                return false;
            }

        }

    }

    /*
    |-------------------------------------------------------------|
    |    Shortcode for coin details page (Advanced Design)        |
    |-------------------------------------------------------------|
     */

  public function celp_shortcode_advanced_details_page_design()

  {
    // Primary shortcode to be rendered before tabs
    $primary_data = array('celp_create_ex_desc');
    $coin_id = (string) trim(get_query_var('exchange-id'));

    $coin = CELP_api_data::celp_get_data($coin_id);
    $disqus_app_id = celp_get_option('celp_fb_id');
    // Array contains names of all Tabs
    if ($coin) {
        $tab_name = array(__('Markets', 'celp'), __('Description', 'celp'), __('Twitter Feeds', 'celp'), __('Comments', 'celp'));

        $data = '';

        ob_start();

        // $data .= do_shortcode('[celp-detail]'); // General details outside the tabs, if needed
        $data .= '<div class="celp-container-advanced-design">';
        $data .= do_shortcode('[celp-detail]');
        $data .= '<div class="celp-container-advanced-design-inner">';
        $twt_plugin_enabled = 'yes';
        $data .= "<div id='celp-tabbed-area'>"; // Main container for tabs

        // Main Tab Buttons
        $data .= "<ul class='celp-tab-group'>";
        $data .= "<li><a class='celp-tabsBtn active' data-id='#celp-container-exchanges'><i class='celp_icon-chart'></i> " . esc_html($tab_name[0]) . "</a></li>";

        $data .= "<li><a class='celp-tabsBtn' data-id='#celp-container-description'><i class='celp_icon-info'></i> " . esc_html($tab_name[1]) . "</a></li>";
        if (isset($coin['twitter']) && !empty($coin['twitter'])) {
            $data .= "<li><a class='celp-tabsBtn' data-loaded='no' data-twt-plugin-enabled=" . esc_attr($twt_plugin_enabled) . " id='coin-twt-tab' data-id='#celp-container-twitter-feeds'><i class='celp_icon-twitter'></i> " . esc_html($tab_name[2]) . "</a></li>";
        }
        if (isset($disqus_app_id) && !empty($disqus_app_id)) {
            $data .= "<li><a class='celp-tabsBtn' data-id='#celp-container-facebook-comments'><i class='celp_icon-comment'></i> " . esc_html($tab_name[3]) . "</a></li>";
        }
        
        $data .= "</ul>";

        // Tab Content Containers
        $data .= "<div class='celp-containers-group'>";

        // Markets Tab Content
        $data .= "<div id='celp-container-exchanges' class='celp-data-container active'>";
        $data .= do_shortcode('[celp-currencies-pairs]');
        $data .= "</div>";

        // Twitter Feeds Tab Content
        $data .= "<div id='celp-container-twitter-feeds' class='celp-data-container'>";
        if (isset($coin['twitter']) && !empty($coin['twitter'])) {
            $data .= $this->celp_advance_twitter_feed_loader();
            $data .= $this->celp_twitter_embed();
        }
        $data .= "</div>";

        // Comments Tab Content
        if (isset($disqus_app_id) && !empty($disqus_app_id)) {
            $data .= "<div id='celp-container-facebook-comments' class='celp-data-container'>";
            $data .= do_shortcode('[celp-comments]');
            $data .= "</div>";
        }

        // Description Tab Content
        $data .= "<div id='celp-container-description' class='celp-data-container'>";
        $data .= "<div class='celp-description-content'>";
        $data .= "<p>" . $this->celp_create_ex_desc() . "</p>"; // Dynamically generated description
        $data .= do_shortcode('[celp-description]'); // Include additional description content from shortcode
        $data .= "</div>";
        // $data .= "</div>";

        $data .= "</div>"; // End of celp-containers-group
        $data .= "</div>"; // End of celp-tabbed-area
        $data .= "</div>";
        $data .= "</div>";
        ob_end_flush();

        return $data;
    } else {
        return __('Currency Not Found', 'celp');
    }
}

} // class end
