<?php 
include('config.php');
$api_key=$_POST['api_key'];
$api_secret=$_POST['api_secret'];
$api_pass=$_POST['api_pass'];
$userid=$_SESSION['userid'];
$flag=0;
$api_key = $api_key;
$secret_key = $api_secret;
$passphrase = $api_pass;

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

$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) 
{
    $res=mysqli_num_rows(mysqli_query($conn,"select * from mul_ex_apis where type='2' and userid='".$userid."'"));
    if($res > 0)
    {
        $result= mysqli_query($conn,"select * from mul_ex_apis where type='2' and userid='".$userid."'");
        $result=mysqli_fetch_array($result);
        mysqli_query($conn, "update mul_ex_apis set api_key='".$api_key."', api_secret='".$api_secret."',password='".$api_pass."' where id='".$result['Id']."'");
    }
    else
    {
        mysqli_query($conn, "insert into mul_ex_apis set api_key='".$api_key."', api_secret='".$api_secret."', password='".$api_pass."', userid='".$userid."', type='2'");
    }
    
    $_SESSION['success']="OKX API Successfully Updated...";
    echo "success";     
} 
else 
{
    echo "Response: " . $response;
}

?>