<?php 
//error_reporting(E_ALL);
//ini_set('display_errors', '1');

require('header.php');

 $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);
 
 if($binance_info)
 {
     $balances=balance($binance_info['api_key'],$binance_info['api_secret']);
     if(!empty($balances))
     {
        foreach ($balances as $asset) 
        {
            if ($asset['asset'] == 'USDT') 
            {
                $usdt=$asset['free'];
                
            }
            if ($asset['asset'] == 'ETH') 
            {
                $eth=$asset['free'];
                
            }
        }
         
         
     }
     else
     {
        $usdt='0';
        $eth='0';
     }
    
     
 }
 else
 {
     $usdt='0';
     $eth='0';
 }
 
 
 if($okx_info)
 {
     $balances=balance1($okx_info['api_key'],$okx_info['api_secret'],$okx_info['password']);
     if(!empty($balances))
     {
        
        $ousdt = 0;
        $oeth = 0;
        
        // Loop through the details array and find ETH and USDT balances
        foreach ($balances[0]['details'] as $balance) {
            if ($balance['ccy'] === 'ETH') {
                $oeth = $balance['availBal']; // or $balance['spotBal'] if you prefer
            }
            if ($balance['ccy'] === 'USDT') {
                $ousdt = $balance['availBal']; // or $balance['spotBal'] if you prefer
            }
        }
         
         
     }
     else
     {
        $ousdt='0';
        $oeth='0';
     }
     
     
     
 }
 else
 {
    $ousdt='0';
    $oeth='0';
 }
 
                            
?>
<!--<div class="alert alert-success">
    <strong>Success!</strong> This alert box could indicate a successful or positive action.
  </div>
  <div class="alert alert-info">
    <strong>Info!</strong> This alert box could indicate a neutral informative change or action.
  </div>
  <div class="alert alert-warning">
    <strong>Warning!</strong> This alert box could indicate a warning that might need attention.
  </div>
  <div class="alert alert-danger">
    <strong>Danger!</strong> This alert box could indicate a dangerous or potentially negative action.
  </div>-->
    <div class="content">
        <div class="py-4 px-3 px-md-4">

            <div class="mb-3 mb-md-4 d-flex justify-content-between">
                <div class="h3 mb-0">Dashboard</div>
            </div>

            <div class="row">
                <?php 
                $binance_url = "https://api.binance.com/api/v3/ticker/bookTicker?symbol=ETHUSDT";

                $binance_response = file_get_contents($binance_url);
                $binance_data = json_decode($binance_response, true);
                $binance_buy_price = $binance_data["bidPrice"]; // Best bid (highest buy)
                $binance_sell_price = $binance_data["askPrice"];

                $okx_url = "https://www.okx.com/api/v5/market/ticker?instId=ETH-USDT";

                $okx_response = file_get_contents($okx_url);
                $okx_data = json_decode($okx_response, true);
                $okx_buy_price = $okx_data["data"][0]["bidPx"]; // Best bid (highest buy)
                $okx_sell_price = $okx_data["data"][0]["askPx"]; // Best ask (lowest sell)

                $rest=0;
                if ($binance_sell_price < $okx_buy_price) {
                    $response ="🔹 Buy on Binance at $binance_sell_price and Sell on OKX at $okx_buy_price ✅\n";
                    $rest=1;
                } elseif ($okx_sell_price < $binance_buy_price) {
                    $response = "🔹 Buy on OKX at $okx_sell_price and Sell on Binance at $binance_buy_price ✅\n";
                    $rest=2;
                } else {
                    $response='';
                }
                ?>
                
                
                
                <div class="col-md-6 col-xl-3 mb-3 mb-xl-4">
                    <!-- Widget -->
                    <div class="card flex-row align-items-center p-3 p-md-4">
                        <div class="icon icon-lg bg-soft-primary rounded-circle mr-3">
                            <i class="gd-wallet icon-text d-inline-block text-primary"></i>
                        </div>
                        <div>
                            <h4 class="lh-1 mb-1" id="balance_bnb"><?php echo number_format($usdt,2);?></h4>
                            <h6 class="mb-0">Binance USDT</h6>
                        </div>
                        <i class="gd-arrow-up icon-text d-flex text-success ml-auto"></i>
                    </div>
                    <!-- End Widget -->
                </div>

                <div class="col-md-6 col-xl-3 mb-3 mb-xl-4">
                    <!-- Widget -->
                    <div class="card flex-row align-items-center p-3 p-md-4">
                        <div class="icon icon-lg bg-soft-primary rounded-circle mr-3">
                            <i class="gd-wallet icon-text d-inline-block text-primary"></i>
                        </div>
                        <div>
                            <h4 class="lh-1 mb-1" id="balance_bnb"><?php echo number_format($eth,8);?></h4>
                            <h6 class="mb-0">Binance ETH</h6>
                        </div>
                        <i class="gd-arrow-up icon-text d-flex text-success ml-auto"></i>
                    </div>
                    <!-- End Widget -->
                </div>

                <div class="col-md-6 col-xl-3 mb-3 mb-xl-4">
                    <!-- Widget -->
                    <div class="card flex-row align-items-center p-3 p-md-4">
                        <div class="icon icon-lg bg-soft-secondary rounded-circle mr-3">
                            <i class="gd-wallet icon-text d-inline-block text-secondary"></i>
                        </div>
                        <div>
                            <h4 class="lh-1 mb-1"><?php echo number_format($ousdt,2);?></h4>
                            <h6 class="mb-0">OKEX USDT</h6>
                        </div>
                        <i class="gd-arrow-up icon-text d-flex text-danger ml-auto"></i>
                    </div>
                    <!-- End Widget -->
                </div>

                <div class="col-md-6 col-xl-3 mb-3 mb-xl-4">
                    <!-- Widget -->
                    <div class="card flex-row align-items-center p-3 p-md-4">
                        <div class="icon icon-lg bg-soft-secondary rounded-circle mr-3">
                            <i class="gd-wallet icon-text d-inline-block text-secondary"></i>
                        </div>
                        <div>
                            <h4 class="lh-1 mb-1"><?php echo number_format($oeth,8);?></h4>
                            <h6 class="mb-0">OKEX ETH</h6>
                        </div>
                        <i class="gd-arrow-up icon-text d-flex text-danger ml-auto"></i>
                    </div>
                    <!-- End Widget -->
                </div>

            </div>

            <div class="row">
            <div class="col-md-6 col-xl-4 mb-3 mb-md-4">
                    <!-- Card -->
                    <div class="card h-100">
                        <div class="card-header d-flex">
                            <h5 class="h6 font-weight-semi-bold text-uppercase mb-0">Binance Exchange</h5>
                        </div>
                        <div class="card-body p-0">
                       
                            <div class="border-bottom media align-items-center p-3">
                                <div class="media-body d-flex align-items-center mr-2">
                                    <span>Last Bid Price</span>
                                    <span class="ml-auto"><?php echo $binance_buy_price;?></span>
                                </div>

                                <i class="gd-arrow-down icon-text icon-text-xs d-flex text-success ml-auto"></i>
                            </div>

                            <div class="media align-items-center p-3">
                                <div class="media-body d-flex align-items-center mr-2">
                                    <span>Last Ask Price</span>
                                    <span class="ml-auto"><?php echo $binance_sell_price;?></span>
                                </div>

                                <i class="gd-arrow-up icon-text icon-text-xs d-flex text-success ml-auto"></i>
                            </div>
                        </div>
                    </div>
                    <!-- End Card -->
                </div>

                <div class="col-md-6 col-xl-4 mb-3 mb-md-4">

                    <div class="padding:10px;font-size:14px;font-weight:bold;margin-top:140px;"><?php echo $response;?></div>
                    <div style="clear:both;height:30px;"><br></div>
                     <?php 
                    if($binance_info && $okx_info)
                    {
                    ?>
                    
                    <input type="button" class="btn btn-primary" value="Execute Trade" onclick="Execute('<?php echo $rest;?>')">
                    
                    <div id="exe" class="err"></div>
                    <?php 
                    }
                    else
                    {
                    ?>
                        <input type="button" class="btn btn-primary" value="Bind API First">
                    <?php } ?>
                    
                    <?php
                     if(!empty($_SESSION['success']))
                    {
                            ?>
                            <div class="alert alert-success">
                                <strong>Success!</strong> <?php echo $_SESSION['success'];?>
                                </div>
                            <?php 
                            $_SESSION['success']='';

                    }
                    ?>

                    
                   
                </div>

                <div class="col-md-6 col-xl-4 mb-3 mb-md-4">
                    <!-- Card -->
                    <div class="card h-100">
                        <div class="card-header d-flex">
                            <h5 class="h6 font-weight-semi-bold text-uppercase mb-0">OKX Exchange</h5>
                        </div>
                        <div class="card-body p-0">
                          

                            <div class="border-bottom media align-items-center p-3">
                                <div class="media-body d-flex align-items-center mr-2">
                                    <span>Last Bid Price</span>
                                    <span class="ml-auto"><?php echo $okx_buy_price;?></span>
                                </div>

                                <i class="gd-arrow-up icon-text icon-text-xs d-flex text-success ml-auto"></i>
                            </div>

                            <div class="media align-items-center p-3">
                                <div class="media-body d-flex align-items-center mr-2">
                                    <span>Last Ask Price</span>
                                    <span class="ml-auto"><?php echo $okx_sell_price;?></span>
                                </div>

                                <i class="gd-arrow-up icon-text icon-text-xs d-flex text-success ml-auto"></i>
                            </div>
                        </div>
                    </div>
                    <!-- End Card -->
                </div>


            </div>

            

            
            <div class="row">
                <div class="col-12">
                    <div class="card mb-3 mb-md-4">
                        <div class="card-header">
                            <h5 class="font-weight-semi-bold mb-0">Binance Recent Orders</h5>
                        </div>
                        <?php 
                        if($binance_info)
                        {
                            $get_orders=get_binance_order($binance_info['api_key'],$binance_info['api_secret']);
                            
                            if(isset($orders['msg'])) 
                            {
                              $order_info='';
                            } 
                            else
                            {
                                usort($get_orders, function ($a, $b) {
                                    return $b['time'] - $a['time'];  // Sort by time field (largest to smallest)
                                });

                                $order_info=$get_orders;
                              
                            }
                           
                        }
                        else
                        {
                            $order_info='';
                        }
                        ?>
                        <div class="card-body pt-0">
                            <div class="table-responsive-xl">
                                <table class="table text-nowrap mb-0">
                                    <thead>
                                    <tr>
                                        <th class="font-weight-semi-bold border-top-0 py-2">Order ID</th>
                                        <th class="font-weight-semi-bold border-top-0 py-2">Qty</th>
                                        <th class="font-weight-semi-bold border-top-0 py-2">Executed Price</th>
                                        <th class="font-weight-semi-bold border-top-0 py-2">Status</th>
                                        <th class="font-weight-semi-bold border-top-0 py-2">Side</th>
                                        <th class="font-weight-semi-bold border-top-0 py-2">Date</th>
                                        
                                    </tr>
                                    </thead>
                                    <tbody>
                                    <?php 
                                    $sno=0;
                                     if($order_info)
                                     {
                                         foreach($order_info as $orderinfo)
                                         {
                                             $sno++;
                                             
                                             $price=$orderinfo['price'];
                                             if($price > 0)
                                                $price=$price;
                                             else
                                                $price=($orderinfo['cummulativeQuoteQty']/$orderinfo['origQty']);
                                             ?>
                                             <tr> 
                                             <td><?php echo $orderinfo['orderId'];?></td>
                                             <td>
                                                <div><?php echo $orderinfo['origQty'];?></div>
                                                <div class="text-muted"><?php echo $orderinfo['cummulativeQuoteQty'];?></div>
                                                </td>
                                             <td><?php echo number_format($price,2);?></td>
                                             <td><?php echo $orderinfo['status'];?></td>
                                             <?php
                                             if($orderinfo['side']=='BUY')
                                             {
                                                 ?>
                                                 <td class="py-3">
                                                    <span class="badge badge-pill badge-success">BUY</span>
                                                    </td>
                                                 <?php 
                                                 
                                             }
                                             else
                                             {
                                                 ?>
                                                 <td class="py-3">
                                                    <span class="badge badge-pill badge-danger">SELL</span>
                                                    </td>
                                                 <?php 
                                                 
                                                 
                                             }
                                             ?>
                                             <td><?php echo date('Y-m-d H:i:s', $orderinfo['time'] / 1000);?></td>
                                             </tr>
                                             <?php 
                                             
                                             
                                         }
                                         
                                     }
                                     if($sno=='0')
                                     {
                                         ?>
                                         <tr>
                                            <td class="py-3" colspan='6'>No Recent orders</td>
                                            </tr>
                                         
                                         <?php 
                                         
                                     }
                                     
                                    ?>
                                    
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>


                <div class="col-12">
                    <div class="card mb-3 mb-md-4">
                        <div class="card-header">
                            <h5 class="font-weight-semi-bold mb-0">OKEX Recent Orders</h5>
                        </div>
                        <?php 
                        $order_info1='';
                        if($okx_info)
                        {
                            $get_orders=get_okx_order($okx_info['api_key'],$okx_info['api_secret'],$okx_info['password']);
                            
                            if(isset($get_orders['data'])) 
                            {
                                
                                 usort($get_orders['data'], function ($a, $b) {
                                    return $b['uTime'] - $a['uTime'];  // Sort by time field (largest to smallest)
                                });

                                $order_info1=$get_orders['data'];
                                
                                
                            }
                            else
                            {
                                $order_info1='';
                            }

                            
                        }
                        else
                        
                        {
                            $order_info1='';
                        }
                        

                        ?>

                        <div class="card-body pt-0">
                            <div class="table-responsive-xl">
                                <table class="table text-nowrap mb-0">
                                    <thead>
                                    <tr>
                                        <th class="font-weight-semi-bold border-top-0 py-2">Order ID</th>
                                        <th class="font-weight-semi-bold border-top-0 py-2">Qty</th>
                                        <th class="font-weight-semi-bold border-top-0 py-2">Executed Price</th>
                                        <th class="font-weight-semi-bold border-top-0 py-2">Status</th>
                                        <th class="font-weight-semi-bold border-top-0 py-2">Side</th>
                                        <th class="font-weight-semi-bold border-top-0 py-2">Date</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    <?php 
                                    $sno=0;
                                     if($order_info1)
                                     {
                                         foreach($order_info1 as $orderinfo1)
                                         {
                                             
                                             
                                             $sno++;
                                             
                                             $qty=$orderinfo1['fillPx'] * $orderinfo1['fillSz'];
                                             
                                             ?>
                                             <tr> 
                                             <td><?php echo $orderinfo1['ordId'];?></td>
                                             <td>
                                                <div><?php echo $orderinfo1['fillSz'];?></div>
                                                <div class="text-muted"><?php echo $qty;?></div>
                                                </td>
                                            <td><?php echo $orderinfo1['fillPx'];?></td>
                                             <td><?php echo strtoupper($orderinfo1['state']);?></td>
                                             <?php
                                             if($orderinfo1['side']=='buy')
                                             {
                                                 ?>
                                                 <td class="py-3">
                                                    <span class="badge badge-pill badge-success">BUY</span>
                                                    </td>
                                                 <?php 
                                                 
                                             }
                                             else
                                             {
                                                 ?>
                                                 <td class="py-3">
                                                    <span class="badge badge-pill badge-danger">SELL</span>
                                                    </td>
                                                 <?php 
                                                 
                                                 
                                             }
                                             ?>
                                             <td><?php echo date('Y-m-d H:i:s', $orderinfo1['uTime'] / 1000);?></td>
                                             </tr>
                                             <?php 
                                             
                                             
                                         }
                                         
                                     }
                                     if($sno=='0')
                                     {
                                         ?>
                                         <tr>
                                            <td class="py-3" colspan='6'>No Recent orders</td>
                                            </tr>
                                         
                                         <?php 
                                         
                                     }
                                     
                                    ?>
                                       
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

<?php
require('footer.php');
?>
<script>
function Execute(str)
{
    $("#exe").html("Please wait Trade Execute progressing...");
    
    var rest='<?php echo $rest;?>';
    var binance_buy='<?php echo $binance_buy_price;?>';
    var binance_sell='<?php echo $binance_sell_price;?>';
    var okx_buy='<?php echo $okx_buy_price;?>';
    var okx_sell='<?php echo $okx_sell_price;?>';
    
    
    $.ajax({
            type: "POST",
            url: "trade_execute",
            data:{rest:rest,binance_buy:binance_buy,binance_sell:binance_sell,okx_buy:okx_buy,okx_sell:okx_sell},
            success: function(msg) {
                var msg = msg.trim();
                if(msg=='success')
                {
                    window.location='dashboard.php';
                }
                else
                {
                    $("#exe").html("<div class='alert alert-danger'><strong>Error !</strong>"+ msg +"</div>");
                }
            }
        });
    
    
    
}
</script>