<?php 

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

/**
 * Create response for datatable AJAX request
 */
function ccpwp_get_ajax_data() {
   

    $origin = isset($_SERVER['HTTP_ORIGIN']) ? sanitize_text_field($_SERVER['HTTP_ORIGIN']) : '';
    $referer = isset($_SERVER['HTTP_REFERER']) ? sanitize_text_field($_SERVER['HTTP_REFERER']) : '';
    $allowed_origin = get_site_url();
    if ((strpos($origin, $allowed_origin) !== 0) && (strpos($referer, $allowed_origin) !== 0)) {
        echo json_encode(array('draw' => 1, 'recordsTotal' => 1, 'recordsFiltered' => 1, 'data' => [], 'error' => 'Invalid referer'));
        wp_die();
    }

    // Initialize variables
    $rtype = isset($_POST['rtype']) ? sanitize_text_field($_POST['rtype']) : 0;
    $start_point = isset($_POST['start']) ? (int) sanitize_text_field($_POST['start']) : 0;
    $data_length = isset($_POST['length']) ? (int) sanitize_text_field($_POST['length']) : 10;
    $current_page = isset($_POST['draw']) ? (int) sanitize_text_field($_POST['draw']) : 1;
    $requiredCurrencies = isset($_POST['requiredCurrencies']) ? sanitize_text_field($_POST['requiredCurrencies']) : '10';
    $fiat_currency = isset($_POST['currency']) ? sanitize_text_field($_POST['currency']) : 'USD';
    $fiat_currency_rate = isset($_POST['currencyRate']) ? (float) sanitize_text_field($_POST['currencyRate']) : 1.0;

    $coin_no = $start_point + 1;
    $coins_list = array();
    $order_col_name = 'market_cap';
    $order_type = 'DESC';
    $DB = new ccpwp_database();
    $Total_DBRecords = 2500;
    $coins_request_count = $data_length + $start_point;

    // Adjust API data request based on start point
    if ($start_point > 2149) {
        CCPWP_api_data::ccpwp_get_selected_api_data(10);
    } elseif ($start_point > 1999) {
        CCPWP_api_data::ccpwp_get_selected_api_data(9);
    } elseif ($start_point > 1749) {
        CCPWP_api_data::ccpwp_get_selected_api_data(8);
    } elseif ($start_point > 1399) {
        CCPWP_api_data::ccpwp_get_selected_api_data(7);
    } elseif ($start_point > 1149) {
        CCPWP_api_data::ccpwp_get_selected_api_data(6);
    } elseif ($start_point > 899) {
        CCPWP_api_data::ccpwp_get_selected_api_data(5);
    } elseif ($start_point > 699) {
        CCPWP_api_data::ccpwp_get_selected_api_data(4);
    } elseif ($start_point > 399) {
        CCPWP_api_data::ccpwp_get_selected_api_data(3);
    } elseif ($start_point > 99) {
        CCPWP_api_data::ccpwp_get_selected_api_data(2);
    }

    // Determine number of currencies to fetch
    switch ($requiredCurrencies) {
        case 'top-10':
            $requiredCurrencies = 10;
            break;
        case 'top-20':
            $requiredCurrencies = 20;
            break;
        case 'top-50':
            $requiredCurrencies = 50;
            break;
        case 'top-100':
            $requiredCurrencies = 100;
            break;
        case 'top-200':
            $requiredCurrencies = 200;
            break;
        case 'all':
            $requiredCurrencies = $Total_DBRecords;
            break;
        default:
            $requiredCurrencies = 10;
            break;
    }

    $coindata = $DB->get_coins(array(
        "number" => $data_length,
        'offset' => $start_point,
        'orderby' => $order_col_name,
        'order' => $order_type,
    ));

    if ($coindata) {
        foreach ($coindata as $coin) {
            $coin = (array) $coin;
            $coins_list[] = array(
                'rank' => esc_html($coin_no++),
                'id' => esc_html($coin['coin_id']),
                'logo' => ccpwp_coin_logo_html($coin['coin_id'], false),
                'symbol' => esc_html(strtoupper($coin['symbol'])),
                'name' => esc_html($coin['name']),
                'price' => esc_html($fiat_currency == "USD" ? $coin['price'] : $coin['price'] * $fiat_currency_rate),
                'market_cap' => esc_html($fiat_currency == "USD" ? $coin['market_cap'] : $coin['market_cap'] * $fiat_currency_rate),
                'total_volume' => esc_html($fiat_currency == "USD" ? $coin['total_volume'] : $coin['total_volume'] * $fiat_currency_rate),
                'change_percentage_24h' => number_format($coin['percent_change_24h'], 2, '.', ''),
                'supply' => esc_html($coin['circulating_supply']),
            );
        }
    }

    // Prepare response
    $response = array(
        'draw' => esc_html($current_page),
        'recordsTotal' => esc_html($Total_DBRecords),
        'recordsFiltered' => esc_html($requiredCurrencies),
        'data' => $coins_list,
    );

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


