<?php
if (!defined('ABSPATH')) {
    exit;
}
/**
 * Coin based exchanges price for Coin market Cap Plugin
 *
 *
 */

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

    $currency_pairs = array();
    celp_load_assets($page = 'coin_single');

    if (get_query_var('coin_id')) {
        $coin_id = sanitize_text_field(trim(get_query_var('coin_id')));
        $coin_symbol = sanitize_text_field(trim(get_query_var('coin_symbol')));

        if (false === ($cache = get_transient($coin_id . '-all-markets-saved'))) {
            $rs = CELP_api_data::celp_save_coins_ex_pairs($coin_id);
            if ($rs) {
                $api_option = get_option("openexchange-api-settings");
                $coingecko_api_cache_time = isset($api_option['select_cache_time']) ? (int) $api_option['select_cache_time'] : 10;
                $timing = $coingecko_api_cache_time * MINUTE_IN_SECONDS;
                set_transient($coin_id . '-all-markets-saved', date('H:s:i'), $timing);
            }
        }
        $slug = !empty(celp_get_option('exchange-page-slug')) ? celp_get_option('exchange-page-slug') : "exchange";
        $per_page = celp_get_option('coin_details_exchange_per_page') ? celp_get_option('coin_details_exchange_per_page') : 10;
        $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');
        $ex_single_slug = esc_url(home_url($slug, '/'));
        $e_logo = CELP_URL . 'assets/logos/logo32/default-logo.png';

        $celp_show_entries = sprintf("%s _MENU_ %s", $celp_show, $celp_entries);
        $output .= '<div class="currecies-pairs" data-ex-default-logo="' . esc_attr($e_logo) . '">
            <table  data-per-page="' . esc_attr($per_page) . '" id="celp_coin_exchanges"
             class="celp-datatable table table-striped table-bordered"
              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-coin-symbol="' . esc_attr($coin_symbol) . '"
              data-zero-records="' . esc_attr($no_rs_found) . '"
              data-coin-id="' . esc_attr($coin_id) . '"
              ><thead>
            <tr>
            <th data-classes="celp-id" data-index="id"  class="desktop">' . __('#', 'celp') . '</th>
            <th data-classes="exchange-name-logo" data-index="exchange_name" data-ex-single-slug="' . esc_attr($ex_single_slug) . '" class="">
            ' . __('Exchange', 'celp') . '</th>
            <th data-classes="celp-pair" data-index="pair" class="all">' . __('Pair', 'celp') . '</th>
            <th data-classes="celp-price" data-index="price" class="all">' . __('Price', 'celp') . '</th>
            <th data-classes="celp-volume" data-index="volume_24h" class="all">' . __('Volume (24h)', 'celp') . '</th>
            <th data-orderable="false" data-classes="celp-updated" data-index="updated" class="all">' . __('Updated', 'celp') . '</th>
            <th data-orderable="false" 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
|--------------------------------------------------------------------------
 */
function celp_get_coin_exchanges_handler()
{
    $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 wp_json_encode($response);
        wp_die();
    }

    // clear old exchange pair data
    celp_cleanOldData();
    $all_pairs = array();
    $search_query = sanitize_text_field($_POST['search']);
    $start_point = isset($_POST['start']) ? absint($_POST['start']) : 0;
    $current_page = isset($_POST['draw']) ? absint($_POST['draw']) : 1;
    $show_per_page = isset($_POST['length']) ? absint($_POST['length']) : 25;
    $total_records = $show_per_page * ($current_page + 1);
    $celpExPairs = new CELP_Exchanges_Pairs;
    $coin_id = sanitize_text_field($_POST['coin_id']);
    $exchange_list = $celpExPairs->get_exchange_coin_price($coin_id, $start_point, $show_per_page);
    $api_option = get_option("openexchange-api-settings");
    $coingecko_api_cache_time = isset($api_option['select_cache_time']) ? absint($api_option['select_cache_time']) : 10;

    // Cache handling
    if (in_array($show_per_page, [10, 25, 50, 100]) && $current_page % (100 / $show_per_page) == 0) {
        $api_Page = $current_page / (100 / $show_per_page) + 1;
        if (get_transient($coin_id . '-all-markets-saved-' . $api_Page) == '') {
            $response = CELP_api_data::celp_save_coins_ex_pairs($coin_id, $api_Page);
            if ($response == true) {
                set_transient($coin_id . '-all-markets-saved-' . $api_Page, date('H:s:i'), $coingecko_api_cache_time * MINUTE_IN_SECONDS);
            }
        }
    }

    $i = $start_point;

    if (is_array($exchange_list)) {
        foreach ($exchange_list as $index => $pair) {

            if (isset($search_query['value']) && !empty($search_query['value']) && stripos($pair['ex_id'], $search_query['value']) === false) {
                continue;
            }
            $Exchange = new CELP_Exchanges();
            // make sure the exchange is not disabled from backend
            $status = $exchange = $Exchange->get_exchanges(array('ex_id' => $pair['ex_id'], 'exchange_status' => 'enable'));
            if ($status == false) {
                continue;
            }

            $i++;
            $pair_data['id'] = $i;
            $pair_data['volume_24h'] = $pair['volume_usd'];
            $pair_data['ex_id'] = $pair['ex_id'];

            if (strlen($pair['pair']) > 20) {
                $p_arr = explode("/", $pair['pair']);
                if (isset($p_arr[0]) && strlen($p_arr[0]) > 8) {
                    $part1 = substr($p_arr[0], 0, 5) . '..';
                } else {
                    $part1 = $p_arr[0];
                }
                if (isset($p_arr[1]) && strlen($p_arr[1]) > 8) {
                    $part2 = substr($p_arr[1], 0, 5) . '..';
                } else {
                    $part2 = $p_arr[1];
                }

                $coin_pair = $part1 . '/' . $part2;
                $pair_data['pair'] = $coin_pair;

            } else {
                $pair_data['pair'] = $pair['pair'];
            }

            $e_id = $pair['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');
            } else {
                $e_logo = esc_url(celp_get_exchange_logo($e_id));
            }

            $pair_data['logo'] = $e_logo;
            $pair_data['exchange_name'] = sanitize_text_field($pair['name']);
            $pair_data['price'] = floatval($pair['price_usd']);
            $pair_data['trust_score'] = $pair['trust_score'];
            $pair_data['updated'] = esc_html(get_timeago($pair['updated']));
            $all_pairs[] = $pair_data;

        }
    }
    // disable 'NEXT' button if response data is less than the show_per_page
    if (count($all_pairs) < $show_per_page) {
        $total_records = $show_per_page;
    }
    $response = array("draw" => $current_page, "recordsTotal" => $total_records, "recordsFiltered" => $total_records, "data" => $all_pairs, "start" => $start_point, 'max' => count($all_pairs));
    echo wp_json_encode($response);

    wp_die();
}
