<?php 
session_start();
date_default_timezone_set("Asia/Kuala_Lumpur");

 $conn = mysqli_connect("localhost","dms111_livbot","livbot@123","dms111_livbot");
 if (mysqli_connect_errno()) 
 {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    exit();
 }

 function get_time()
 {
   $base_url = "https://api.binance.com";
   $endpoint = "/api/v3/time";
   $url = $base_url . $endpoint;
   $curl = curl_init();
   curl_setopt_array($curl, [
      CURLOPT_URL => $url,
      CURLOPT_RETURNTRANSFER => true,
   ]);

      $response = curl_exec($curl);
      $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
      curl_close($curl);

   // Output response
   if ($http_code == 200) 
   {

      $data = json_decode($response, true);
      $serverTime=$data['serverTime'];
      return $serverTime;
   }
}

function balance($api_key,$api_secret)
{
    $base_url = "https://api.binance.com";
    $endpoint = "/api/v3/account";
    //$timestamp = round(microtime(true) * 1000); // Get current time in milliseconds
    $timestamp=get_time();
    $query_string = "timestamp=$timestamp";
    $signature = hash_hmac('sha256', $query_string, $api_secret);
    $url = "$base_url$endpoint?$query_string&signature=$signature";

    $headers = [
        "X-MBX-APIKEY: $api_key",
        "Content-Type: application/json"
    ];

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers,
    ]);

    $response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    if ($http_code == 200) 
    {
        $data = json_decode($response, true);
        if(!empty($data['balances']))
        {
            $balance=$data['balances'];
        }
        else
        {
            $balance=0;
        }
       
        
    }
    else
    {
        $balance=0;
    }
    return $balance;
    
}

function balance1($api_key,$api_secret,$password)
{
    $api_key = $api_key;
    $secret_key = $api_secret;
    $passphrase = $password;

    $base_url = "https://www.okx.com";
    $endpoint = "/api/v5/account/balance";

    // Generate timestamp (OKX requires UTC timestamp)
    $timestamp = gmdate("Y-m-d\TH:i:s\.000\Z");

    // Function to generate OKX API signature
    function generateSignature($timestamp, $method, $endpoint, $body, $secret_key) {
        $message = $timestamp . $method . $endpoint . $body;
        return base64_encode(hash_hmac('sha256', $message, $secret_key, true));
    }

    // Create signature
    $signature = generateSignature($timestamp, "GET", $endpoint, "", $secret_key);

    // Set cURL options
    $curl = curl_init();
    curl_setopt_array($curl, [
    CURLOPT_URL => $base_url . $endpoint,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "OK-ACCESS-KEY: $api_key",
        "OK-ACCESS-SIGN: $signature",
        "OK-ACCESS-TIMESTAMP: $timestamp",
        "OK-ACCESS-PASSPHRASE: $passphrase",
        "Content-Type: application/json"
    ],
]);

// Execute cURL request
$response = curl_exec($curl);

$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);

// Output response
if ($http_code == 200) 
{
    $data = json_decode($response, true);
    
    if(!empty($data['data']))
    {
        $balance=$data['data'];
    }
    else
    {
        $balance=0;
    }
   
} 
else 
{
    $balance=0;
}
return $balance;
    
}


function get_binance_order($api_key,$api_secret)
{

    $baseUrl = 'https://api.binance.com';
    // API endpoint for all orders
    $endpoint = '/api/v3/allOrders';
    // Symbol for the ETH/USDT trading pair
    $symbol = 'ETHUSDT';
    // Parameters for the API request
    $limit = 10;  // Last 10 orders
    $timestamp = round(microtime(true) * 1000); // Current timestamp in milliseconds

    // Create the query string
    $query = http_build_query([
        'symbol' => $symbol,
        'limit' => $limit,
        'timestamp' => $timestamp
    ]);

// Create the signature
$signature = hash_hmac('sha256', $query, $api_secret);

// Final URL with signature
$url = $baseUrl . $endpoint . '?' . $query . '&signature=' . $signature;

// Set cURL options
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'X-MBX-APIKEY: ' . $api_key
]);

// Execute the cURL request
$response = curl_exec($ch);
curl_close($ch);

// Decode the response JSON
$orders = json_decode($response, true);

// Check if the response is an error
/*if (isset($orders['msg'])) {
    echo 'Error: ' . $orders['msg'];
    exit;
}

// Output the last 10 orders
echo "Last 10 Orders for ETH/USDT:\n";
foreach ($orders as $order) {
    echo "Order ID: " . $order['orderId'] . "\n";
    echo "Price: " . $order['price'] . "\n";
    echo "Quantity: " . $order['origQty'] . "\n";
    echo "Status: " . $order['status'] . "\n";
    echo "Side: " . $order['side'] . "\n";
    echo "Time: " . date('Y-m-d H:i:s', $order['time'] / 1000) . "\n";
    echo "--------------------------------\n";
}*/


return $orders;

}


function get_okx_order($api_key,$api_secret,$api_pass)
{
    
    $apiKey = $api_key;
    $secretKey = $api_secret;
    $passphrase = $api_pass;

    // OKX API URL for fetching account orders
    $url = "https://www.okx.com/api/v5/trade/orders-history?instType=SPOT&instId=ETH-USDT&limit=10";

    // Generate the OKX required timestamp
    $timestamp = gmdate('Y-m-d\TH:i:s\.000\Z');

    // Create the prehash string (timestamp + method + requestPath + body)
    $method = "GET";
    $requestPath = "/api/v5/trade/orders-history?instType=SPOT&instId=ETH-USDT&limit=10";
    $body = ""; // Empty for GET request
    $preHash = $timestamp . $method . $requestPath . $body;

    // Generate the signature using HMAC-SHA256
    $signature = base64_encode(hash_hmac('sha256', $preHash, $secretKey, true));

    // Set up the request headers
    $headers = [
    "OK-ACCESS-KEY: $apiKey",
    "OK-ACCESS-SIGN: $signature",
    "OK-ACCESS-TIMESTAMP: $timestamp",
    "OK-ACCESS-PASSPHRASE: $passphrase",
    "Content-Type: application/json"
    ];

    // Initialize cURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    // Execute cURL request and close connection
    $response = curl_exec($ch);
    curl_close($ch);

    // Decode the JSON response
    $data = json_decode($response, true);
    
    return $data;
    
}
?>