#!/usr/bin/perl -w

# crypto_update.pl

# Update the in-game Crypto market

use warnings;
use JSON;
use HTTP::Tiny;
use Data::Dumper;
use lib '.';
use CWZ;

# API URL and key
my $url = "https://api.coincap.io/v2/assets?ids=bitcoin,ethereum,tether,binance-coin,usd-coin,xrp,cardano,dogecoin,polygon,solana,polkadot,litecoin,shiba-inu,neo,chainlink,stellar,vechain,algorand,hedera-hashgraph,enjin-coin";
my $key = "48c52dc7-543c-4bbf-bb05-55982a1cb4d3";

# Set headers
my %headers = (
    "Accept-Encoding" => "deflate",
    "Content-Type" => "application/json",
    "Authorization" => "Bearer $key"
);

# Retrieve data from the API
my $http = HTTP::Tiny->new();
my $response = $http->get($url, { headers => \%headers });
my $json = JSON->new->decode($response->{content});

qDb_do("DELETE FROM Crypto_Live");
qDb_do("ALTER TABLE Crypto_Live AUTO_INCREMENT=11");
qDb_do("DELETE FROM Crypto_Live_History");
qDb_do("ALTER TABLE Crypto_Live_History AUTO_INCREMENT=11");

# Process the data
foreach my $asset (@{$json->{data}}) {
  my $shortnm = $asset->{symbol};
  my $name = $asset->{name};
  my $price = $asset->{priceUsd};
  my $circulating_supply = int($asset->{supply}) // "0";
  my $max_supply = $asset->{maxSupply} // "0";
  if ($price >= 10) {
  $price = sprintf("%.2f", $price);
} elsif (10 > $price && $price >= 0.01) {
  $price = sprintf("%.4f", $price); # Display up to 4 decimal places for values equal or less than 10
} else {
  $price = sprintf("%.7f", $price); # Display up to 7 decimal places for values less than 0.01
}
if ($max_supply > 0) {
$max_supply = int($max_supply);
}


  # Insert the data into Crypto Live Table in the database
    qDb_do("INSERT INTO Crypto_Live (shortnm, longnm, price_now) VALUES (?, ?, ?)", $shortnm, $name, $price);
  # Insert the data into Crypto Live History Table in the database
    qDb_do("INSERT INTO Crypto_Live_History (shortnm, longnm, price_history, circulating_supply, max_supply, timestamp) VALUES (?, ?, ?, ?, ?, NOW())", $shortnm, $name, $price, $circulating_supply, $max_supply);


    qDb_do("UPDATE Crypto_Live SET price_ref = price_now");
}
