<?php
// Enqueue necessary Datatables CSS and JS
function cwpai_enqueue_datatables_assets() {
    echo '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/2.0.7/css/dataTables.dataTables.min.css">';
    echo '<script type="text/javascript" src="//cdn.datatables.net/2.0.7/js/dataTables.min.js"></script>';
}
add_action('admin_head', 'cwpai_enqueue_datatables_assets');

// Fetch crypto prices from CoinCap API
function cwpai_fetch_crypto_prices() {
    $api_url = 'https://api.coincap.io/v2/assets';
    $args = array(
        'headers' => array(
            'Accept' => 'application/json',
            'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
        )
    );
    $response = wp_remote_get($api_url, $args);
    if (is_wp_error($response)) {
        error_log('Error fetching data from CoinCap API: ' . $response->get_error_message());
        return ['error' => 'Failed to fetch data from CoinCap API.'];
    }
    $data = json_decode(wp_remote_retrieve_body($response), true);
    if (!isset($data['data'])) {
        error_log('Invalid response structure from CoinCap API.');
        return ['error' => 'Invalid response structure from CoinCap API.'];
    }
    $coins = ['bitcoin', 'ethereum', 'solana'];
    $crypto_prices = [];
    foreach ($data['data'] as $coin) {
        if (in_array($coin['id'], $coins)) {
            $crypto_prices[] = [
                'name' => $coin['name'],
                'symbol' => $coin['symbol'],
                'price' => number_format((float)$coin['priceUsd'], 2),
                'change' => number_format((float)$coin['changePercent24Hr'], 2) . '%',
            ];
        }
    }
    return $crypto_prices;
}

// Display crypto prices in a dashboard widget
function cwpai_crypto_dashboard_widget() {
    $crypto_prices = cwpai_fetch_crypto_prices();
    if (isset($crypto_prices['error'])) {
        echo '<p>' . esc_html($crypto_prices['error']) . '</p>';
        return;
    }
    echo '<table id="crypto-prices" class="display">';
    echo '<thead><tr><th>Name</th><th>Symbol</th><th>Price (USD)</th><th>24h Change</th></tr></thead>';
    echo '<tbody>';
    foreach ($crypto_prices as $crypto) {
        echo '<tr>';
        echo '<td>' . esc_html($crypto['name']) . '</td>';
        echo '<td>' . esc_html($crypto['symbol']) . '</td>';
        echo '<td>' . esc_html($crypto['price']) . '</td>';
        echo '<td>' . esc_html($crypto['change']) . '</td>';
        echo '</tr>';
    }
    echo '</tbody>';
    echo '</table>';
    echo '<script> jQuery(document).ready(function($) { $("#crypto-prices").DataTable(); }); </script>';
}

// Register the dashboard widget
function cwpai_register_crypto_dashboard_widget() {
    wp_add_dashboard_widget('cwpai_crypto_dashboard_widget', __('Crypto Prices', 'codewp'), 'cwpai_crypto_dashboard_widget');
}
add_action('wp_dashboard_setup', 'cwpai_register_crypto_dashboard_widget');