<?php
/*
dev: https://factweb.ir
channel telegram : @factwebir
*/
include "../config.php";
//------------------------------------------------------//
error_reporting(0);
date_default_timezone_set('Asia/Tehran');

$target_symbols = ['USDT_IRT', 'TON_IRT', 'TON_USDT'];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.bitpin.org/api/v1/mkt/tickers/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode == 200 && $response) {
    $tickers = json_decode($response, true);
    
    if (isset($tickers['results'])) { 
         $tickers = $tickers['results'];
    }

    foreach ($tickers as $ticker) {
        $symbol = $ticker['symbol'];


        if (in_array($symbol, $target_symbols)) {
            
            $price = $ticker['price'] ?? 0;
            $daily_change = $ticker['daily_change_price'] ?? 0;
            $low = $ticker['low'] ?? 0;
            $high = $ticker['high'] ?? 0;


            $price_sql = $connect->real_escape_string($price);
            $daily_change_sql = $connect->real_escape_string($daily_change);
            $low_sql = $connect->real_escape_string($low);
            $high_sql = $connect->real_escape_string($high);
            $symbol_sql = $connect->real_escape_string($symbol);


            $sql = "INSERT INTO crypto_prices (symbol, price, daily_change_price, low, high)
                    VALUES ('$symbol_sql', '$price_sql', '$daily_change_sql', '$low_sql', '$high_sql')
                    ON DUPLICATE KEY UPDATE
                        price = '$price_sql',
                        daily_change_price = '$daily_change_sql',
                        low = '$low_sql',
                        high = '$high_sql',
                        last_updated = CURRENT_TIMESTAMP";
            

            $connect->query($sql);
        }
    }
} else {

    error_log("Failed to fetch BitPin API. HTTP Code: " . $httpCode);
}
?>