<?php 
include('config.php');
$rest=$_POST['rest'];
$binance_buy=$_POST['binance_buy'];
$binance_sell=$_POST['binance_sell'];
$okx_buy=$_POST['okx_buy'];
$okx_sell=$_POST['okx_sell'];

$userid=$_SESSION['userid'];
$flag=0;


$user_det=mysqli_query($conn,"select * from mul_ex_apis where userid='".$_SESSION['userid']."' and type='1'");
$binance_info=mysqli_fetch_array($user_det);
 
$user_det1=mysqli_query($conn,"select * from mul_ex_apis where userid='".$_SESSION['userid']."' and type='2'");
$okx_info=mysqli_fetch_array($user_det1);


$binance_api_key = $binance_info['api_key'];
$binance_secret_key = $binance_info['api_secret'];

// OKX API Credentials
$okx_api_key = $okx_info['api_key'];
$okx_secret_key = $okx_info['api_secret'];
$okx_passphrase = $okx_info['password'];



$quantity = 0.0018; 

function get_binance_min_notional($symbol) 
{
    $url = "binance_exchange_info.json";
    
    $response = json_decode(file_get_contents($url), true);
    
   

    foreach ($response as $s) {
        
        if ($s['symbol'] === $symbol) 
        {
            foreach ($s['filters'] as $filter) 
            {
                
                if($filter['filterType'] === 'NOTIONAL') {
                    return $filter['minNotional'];
                }
            }
        }
    }
    return false;
}



function binance_trade($side, $quantity, $price) {
    global $binance_api_key, $binance_secret_key;
    
    $symbol='ETHUSDT';
    $min_notional = get_binance_min_notional($symbol);
    if (!$min_notional) 
    {
        echo "Error: Could not fetch minNotional value for $symbol.";
        exit;
    }
    
    $notional_value = $price * $quantity;
    if ($notional_value < $min_notional) 
    {
        echo "Error: Order value ($notional_value USDT) is below minNotional ($min_notional USDT). Increase quantity.";
        exit;
    }


    
    $url = "https://api.binance.com/api/v3/order";
    $timestamp = round(microtime(true) * 1000);
    $params = [
        'symbol' => 'ETHUSDT',
        'side' => strtoupper($side),
        'type' => 'MARKET',
        //'timeInForce' => 'GTC',
        'quantity' => number_format($quantity, 6, '.', ''), // Ensure correct decimal format
        //'price' => number_format($price, 2, '.', ''),
        
        'timestamp' => $timestamp
    ];

    $query_string = http_build_query($params);
    $signature = hash_hmac('sha256', $query_string, $binance_secret_key);
    $params['signature'] = $signature;

    $headers = [
        "X-MBX-APIKEY: $binance_api_key"
    ];

    return send_post_request($url, $params, $headers);
}

// Place an order on OKX
function okx_trade($side, $quantity, $price) {
    global $okx_api_key, $okx_secret_key, $okx_passphrase;
    
    if($side == 'buy')
    {
        $quantity = $price * 0.0018;
    }
    
    $url = "https://www.okx.com/api/v5/trade/order";
    $timestamp = gmdate("Y-m-d\TH:i:s.000\Z");
    $body = json_encode([
        "instId" => "ETH-USDT",
        "side" => strtolower($side),
        "ordType" => "market",
        //"px" => (string)$price,
        "sz" => (string)$quantity,
        "tdMode" => "cash"
    ]);

    $prehash = $timestamp . "POST" . "/api/v5/trade/order" . $body;
    $signature = base64_encode(hash_hmac('sha256', $prehash, $okx_secret_key, true));

    $headers = [
        "OK-ACCESS-KEY: $okx_api_key",
        "OK-ACCESS-SIGN: $signature",
        "OK-ACCESS-TIMESTAMP: $timestamp",
        "OK-ACCESS-PASSPHRASE: $okx_passphrase",
        "Content-Type: application/json"
    ];

    return send_post_request($url, $body, $headers, true);
}

// Function to execute cURL POST request
function send_post_request($url, $data, $headers, $json = false) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
    if ($json) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    } else {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    }

    $response = curl_exec($ch);
    
   /* echo '<pre>';
    print_r($response);
    echo '</pre>';*/

    curl_close($ch);
    return json_decode($response, true);
}



 
if($rest=='1')
{
    
    //$response ="ðŸ”¹ Buy on Binance at $binance_sell and Sell on OKX at $okx_buy âœ…\n";
    $order = binance_trade('buy', $quantity, $binance_sell);
    $order = okx_trade('sell', $quantity, $okx_buy);

    
}
else
{
    //$response = "ðŸ”¹ Buy on OKX at $okx_sell and Sell on Binance at $binance_buy âœ…\n";
    
    $order = okx_trade('buy', $quantity, $okx_sell); 
    
    $order = binance_trade('sell', $quantity, $binance_buy);
    
    
}

$_SESSION['success']="Trade Executed Successfully...";
echo "success";
?>