<?php

/**
 * Exchanges list main shortcode
 */
if (!defined('ABSPATH')) {
    exit;
}
function celp_shortcode($atts, $content = null)
{

    $atts = shortcode_atts(array(
        'id' => '',
        'class' => '',
        'type' => "all",
        'show-country' => "yes",
        'show-year' => "yes",
        'trust-score' => "",
        'website-link' => "yes",
        'per-page' => "",

    ), $atts, 'celp');
    $get_license = get_option('celp_license_registration');
    $purchased_code = isset($get_license["celp-purchase-code"]) ? $get_license["celp-purchase-code"] : '';
    $notice = "";
    // Do not proceed further if
    if (empty($purchased_code)) {
        $notice = __('<b>Please enter and activate your license key for Cryptocurrency Exchanges List PRO plugin for unrestricted and full access of all premium features.</b><br>', 'ccpw');

    }
    // Do not proceed further if
    if (!celp_check_required_settings()) {
        if ($notice) {
            return $notice;
        }
        return __('Please enter Coingecko Free Api Key to get this plugin works', 'cmc');
    }

    $output = '';
    $post_id = $atts['id'];
    $currency = celp_selected_currency();
    $currency_symbol = celp_fiat_cur_symbol($currency['c_name']);
    $currency_price = $currency['c_price'];
    $description = empty($atts['description']) ? 'no' : sanitize_text_field($atts['description']);

    $website_link = empty($atts['website-link']) ? 'yes' : sanitize_text_field($atts['website-link']);
    $show_year = empty($atts['show-year']) ? 'yes' : sanitize_text_field($atts['show-year']);
    $show_country = empty($atts['show-country']) ? 'yes' : sanitize_text_field($atts['show-country']);
    $trust_score = !empty($atts['trust-score']) ? sanitize_text_field($atts['trust-score']) : 'no';

    $exchangetype = in_array($atts['type'], ["decentralized", "centralized", "all"]) ? $atts['type'] : "all";

    $default_logo = CELP_URL . 'assets/logos/logo32/default-logo.png';
    celp_load_assets($page = 'exchanges_list');
    $per_page = celp_get_option('exchanges_per_page') ? absint(celp_get_option('exchanges_per_page')) : 10;
    $per_page = !empty($atts['per-page']) ? absint($atts['per-page']) : $per_page;
    $per_page = apply_filters('celp/exchanges_per_page', $per_page);

    // datatable translated text
    $celp_prev = __('Previous', 'celp');
    $celp_next = __('Next', 'celp');
    $celp_show = __('Show', 'celp');
    $celp_search = __('Search', 'celp');
    $celp_entries = __('Entries', 'celp');

    $no_rs_found = __('No Exchange Found', 'celp');
    $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');

    $slug = !empty(celp_get_option('exchange-page-slug')) ? sanitize_title(celp_get_option('exchange-page-slug')) : "exchange";
    $detail_page_url = esc_url(home_url($slug, '/'));
    $output .= '<!-- Cryptocurrency Exchanges List PRO  Version:-' . CELP_VERSION . ' -->';

    $output .= '<div class="celp_container" data-default-logo="' . esc_attr($default_logo) . '">';

    $output .= '<table  data-per-page="' . esc_attr($per_page) . '"
		id="celp_main_list"
		class="celp-datatable table table-striped table-bordered"
		data-coin-exchangetype="' . esc_attr($exchangetype) . '"
		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-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>';

    $output .= '<th data-classes="celp-rank" data-index="id" >' . __('#', 'celp') . '</th>';
    $output .= '<th data-classes="celp-name exchange-name-logo" data-index="name" data-single-page-url="' . esc_attr($detail_page_url) . '"  class="all" title="' . __('Name', 'celp') . '">' . __('Name', 'celp') . '</th>';
    if (strtolower($trust_score) == "yes") {
        $output .= '<th data-classes="celp-trust-score exchange-trust-score" data-index="trust_score" title="' . __('Trust Score ', 'celp') . '">' . __('Trust Score ', 'celp') . '</th>';
    }
    $output .= '<th data-classes="celp-vol exchange-volume" data-index="volume_24h" title="' . __('Volume (24H)', 'celp') . '">' . __('Volume (24H)', 'celp') . '</th>';

    if (strtolower($description) == "yes") {
        $output .= '<th data-classes="celp-desc exchange-description" data-index="description" title="' . __('Description', 'celp') . '">' . __('Description', 'celp') . '</th>';
    }

    if (strtolower($show_country) == "yes") {
        $output .= '<th data-classes="celp-country exchange-country" data-index="country" class="all" title="' . __('Country', 'celp') . '">' . __('Country', 'celp') . '</th>';
    }
    if (strtolower($show_year) == "yes") {
        $output .= '<th data-classes="celp-established exchange-established" data-index="established" title="' . __('Established', 'celp') . '">' . __('Established', 'celp') . '</th>';
    }
    if (strtolower($website_link) == "yes") {
        $output .= '<th data-classes="celp-official-website exchange-website-link" data-index="official_website" class="all" data-orderable="false" title="' . __('Official Website', 'celp') . '">' . __('Official Website', 'celp') . '</th>';
    }
    $output .= '</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 $notice . $output;
}

/*
|--------------------------------------------------------------------------
| CELP list server side processing ajax callback
|--------------------------------------------------------------------------
 */
function celp_get_ex_list_data()
{
    $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);
        die();

    }

    $start_point = 0;
    $data_all = 350;
    $celpEx = new CELP_Exchanges;
    $exchangetype = isset($_POST['exchangetype']) ? sanitize_text_field($_POST['exchangetype']) : '';

    $exchangetype_array = '';
    if ($exchangetype == "decentralized") {
        $exchangetype_array = decentralized_coin_array();
    }
    if ($exchangetype == "centralized") {
        $exchangetype_array = centralized_coin_array();
    }

    $order_col_name = 'volume_24h';
    $order_type = 'DESC';
    $start_point = isset($_POST['start']) ? absint($_POST['start']) : 0; // Sanitize and validate the start point.
    $data_all = count($celpEx->get_all_exchanges());
    $i = $start_point + 1;
    $data_load = isset($_POST['length']) ? absint($_POST['length']) : 10; // Sanitize and validate the data load.
    $current_page = isset($_POST['draw']) ? absint($_POST['draw']) : 1; // Sanitize and validate the current page.
    $coin_search = isset($_POST['search']) ? strtoupper(sanitize_text_field($_POST['search'])) : ''; // Sanitize and validate the coin search.
    //$exchangetype_array = array_map('esc_attr', $exchangetype_array); // Escape the exchangetype_array values.
    $all_exchanges = $celpEx->get_exchanges(array(
        "number" => $data_load,
        'offset' => $start_point,
        'orderby' => $order_col_name,
        'order' => $order_type,
        'type' => 'on-coin',
        'coin_search' => $coin_search,
        'exchangetype_array' => $exchangetype_array,
    ));
    $filtered_data_all = count($celpEx->get_exchanges([
        'orderby' => $order_col_name,
        'order' => $order_type,
        'type' => 'on-coin',
        'coin_search' => $coin_search,
        'exchangetype_array' => $exchangetype_array,
        'number' => -1, // get all to count them
    ]));
    $ex_array = array();
    $all_affilates = get_all_affilate_links();

    if ($all_exchanges) {
        foreach ($all_exchanges as $index => $exchange) {
            $ex_data = (array) $exchange;

            $ex_data['country'] = empty($ex_data['country']) ? 'N/A' : sanitize_text_field($ex_data['country']); // Sanitize and validate the country data.
            $ex_data['trust_score'] = empty($ex_data['trust_score']) ? 'N/A' : sanitize_text_field($ex_data['trust_score']); // Sanitize and validate the trust score data.
            $ex_data['established'] = empty($ex_data['established']) ? 'N/A' : sanitize_text_field($ex_data['established']); // Sanitize and validate the established data.
            $extra_data = json_decode($ex_data['extra_data']);
            $e_id = $ex_data['ex_id'];

            $e_logo = '';
            $local_logo = CELP_PATH . 'assets/logos/logo32/' . $e_id . '.png';
            if (file_exists($local_logo)) {
                $e_logo = esc_url(CELP_URL . 'assets/logos/logo32/' . $e_id . '.png'); // Escape the logo URL.
            } else {
                if (isset($extra_data->logo)) {
                    $e_logo = esc_url($extra_data->logo); // Escape the logo URL.
                }
            }
            $ex_data['logo'] = $e_logo;

            if (isset($extra_data->website) && $extra_data->website != "N/A") {
                $ex_data['official_website'] = esc_url($extra_data->website); // Escape the official website URL.
            } else {
                $ex_data['official_website'] = '#';
            }
            if (isset($all_affilates[$e_id])) {
                $ex_data['official_website'] = esc_url($all_affilates[$e_id]['affiliate_link']); // Escape the affiliate link URL.
            }

            $ex_data['id'] = $i;
            $ex_data['volume_24h'] = $ex_data['volume_24h'];

            $ex_array[] = $ex_data;
            $i++;
        }
    }

    $response = array(
        "draw" => $current_page,
        "recordsTotal" => $data_all,
        "recordsFiltered" =>$filtered_data_all,
        "data" => $ex_array,
    );
    echo wp_json_encode($response); // Escape the JSON response.
    exit();
}
