<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/rowreorder/1.2.8/css/rowReorder.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.dataTables.min.css"> -->
<style type="text/css">
  .heart0
  {
  font-size: 25px;
  color:red;
  }
  .heart1
  {
  font-size: 25px;
  color:red;
  }
  .heart {
  font-size: 25px;
  color:red;
  }
.crypto-title{
  margin-left: 54px !important;
  margin-top:  -20px !important;
}
.btn-primary{
  background: rgb(32, 60, 157) !important;
  color: white !important;
}
</style>

<div class="trading-table">
<div class="table-responsive">
<table class="table-striped display nowrap" id="table_example">
<thead>
<tr>
<td> List </td>
<td class="text-center">Quantity </td>
<td class="text-center"> Floating Loss </td>
<td class="text-center"> Price </td>
<td class="text-center"> Change% </td>
<td class="text-center"> Rate of Return </td>

</tr>
</thead><tbody>
<?php 
use Lin\Okex\OkexV5;

$this->session = session();
$uusersid = $this->session->get('uusersid');
$this->db = db_connect();
    $operation =$this->db->query("SELECT * FROM trade_process WHERE uusersid='".$uusersid."' and trade_status != 2 and exchange = 2 order by id desc")->getResult();
    $i=0;
    foreach ($operation as $key => $value) {
      $required_pairs[$i] = substr($value->pair, 0, -4);
      $i++;
    }
$validation =  \Config\Services::validation();
$this->db = db_connect();
use Lin\Ftx\Ftx;

$referral3=$this->db->query("SELECT * FROM ftx_bind_process WHERE uusersid='".$userid."'")->getRow();
$key = $referral3->api_key;
$secret = $referral3->secret_key;
if(empty($referral3)){
 $key = "lUsmd83bvErGkf4q0ctifaK8kaT1-uf2ZATn4uaH";
$secret = "W8tKzcC420jUJPX_6Bl6MeNv5Dyg266X0rtIF33q";
$ftx=new Ftx($key,$secret);
}else{
$ftx=new Ftx($key,$secret);
   // $account = $api->accountStatus();
   // if($account['sapi']['code'] == "-2008" || $account['sapi']['code'] == "-1022" || $account['sapi']['code'] == "-2015")
   //  {
   //      $key = "tJuR6dN9AZp9KiAn41avxq64KsyDxa8FIaRjxTf0k1qplZIv1MRnHrS3zQIqHuzZ";
   //    $secret = "GlRLQS2VGYfa1sOUaS3NIgGmszJOAuxu7Xk0anY1r4ifRmGYVYxoG25LOBnESE67";
   //      $api = new Binance\API($key,$secret);
   //  }
}
  $ftx_res = $ftx->markets()->gets();

$i=0;
$required_pairs = ['1INCH','ADA','AAVE','ATOM','ALGO','AION','AVAX','AKRO','ANT','APE','BAT','BTC','BCH','BNB','BTCST','BAKE','CRV','COMP','CAKE','COS','DOGE','DASH','DOT','ETH','EOS','ETC','FTM','FTT','FIL','GALA','GRT','GMT','HBAR','HOT','IOTA','ICP','IOST','JST','KAVA','KSM','LTC','LINK','LIT','LUNA','MANA','MATIC','MDX','NEO','OMG','ONT','QTUM','REEF','RSR','SUN','SHIB','SLP','SOL','SUSHI','SXP','TRX','THETA','TFUEL','UNI','VET','WRX','XRP','XMR','XEM','XLM','XTZ','YFI','YFII','ZEC','ZEN'];
if(!empty($ftx_res['result'])) { 
foreach ($ftx_res['result'] as $key => $value) {
  if(substr($value['name'], -5) == "/USDT"){
    if(in_array(substr_replace($value['name'] ,"",-5), $required_pairs)){
      $output2[$i]['symbol'] = str_replace('/','',$value['name']);
      $output2[$i]['price'] = $value['last'];
      $output2[$i]['change'] = number_format($value['change24h'],3);
    }
      $i++;
  }
}
}

$k = 0;
foreach ($output2 as $key => $value) {
  $output2[$k] = $value;
  $k++;
}
$output2 =  array_unique($output2,SORT_REGULAR);
}else
   $output2 = "";
$this->session = session();
$uusersid = $this->session->get('uusersid');
 

              if($output2){
  foreach ($output2 as $key => $value) {

   
    $pair =  $value['symbol'];
      
      // return $session;

      $where_ = array(
        'pair' => $pair,
        'uusersid' => $uusersid,
        'trade_status != ' => '2',
        'exchange' => 2
      );

      $trade_record =  $this->db->table('trade_process')->where($where_)->orderBy('id','DESC')->get()->getRow();
     


      if ($trade_record) {
        
        $api_trade_data = array(
          'trade_process_id' => $trade_record->id,
          'uuserid' => $uusersid,
          'type' => '1',
          'status' => 0,
          'exchange' => 2
        );

        $api_trade_data1 = array(
          'trade_process_id' => $trade_record->id,
          'uuserid' => $uusersid,
          'type' => '2',
          'description' => 'manual_sell',
          'status' => 0,
          'exchange' => 2
        );

           $profit_where = array(
            'uuserid' => $uusersid,
            'type' => '3',
            'trade_process_id' => $trade_record->id,
            'status' => 0,
            'exchange' => 2
        );
      

        $total_position_amount = $this->db->table('api_trade_history')->selectSum('quantity')->where($api_trade_data)->get()->getRow();
        $total_sell_amount = $this->db->table('api_trade_history')->selectSum('quantity')->where($api_trade_data1)->get()->getRow();

      

        $total_position_amount->quantity = $total_position_amount->quantity - $total_sell_amount->quantity;


        $tradeupdate['current_position_amount'] = number_format($last_call_drop->quantity,5);
              $total_position_quantity = $this->db->table('api_trade_history')->selectSum('received_amount')->where($api_trade_data)->get()->getRow();
        $total_sell_quantity = $this->db->table('api_trade_history')->selectSum('received_amount')->where($api_trade_data1)->get()->getRow();
        $total_position_quantity->received_amount = $total_position_quantity->received_amount - $total_sell_quantity->received_amount;

        if ($total_position_amount->quantity > 0) {
          
          $tradeupdate['trade_position_amount'] = number_format($total_position_amount->quantity,5);  
        }else{
          $tradeupdate['trade_position_amount'] = 0.00;
        }

            if ($total_position_quantity->received_amount > 0) {

        $tradeupdate['trade_position_quantity'] = number_format($total_position_quantity->received_amount,5);

          }else{

          $tradeupdate['trade_position_quantity'] = 0.00;

        }
        
        // $avg_position_amount = $this->db->table('api_trade_history')->selectAvg('live_price')->where($api_trade_data)->get()->getRow();
               // $avg_position_amount = $this->db->table('api_trade_history')->selectAvg('live_price')->where($api_trade_data)->get()->getRow();
if($trade_record->strategy_mode == 1){
        $total_contract = $this->db->table('api_trade_history')->selectSum('received_amount')->where($api_trade_data)->get()->getRow();
        $total_usdt  = $this->db->table('api_trade_history')->selectSum('quantity')->where($api_trade_data)->get()->getRow();
        if($total_contract->received_amount && $total_usdt->quantity)
          $avg_position_amount = $total_usdt->quantity / $total_contract->received_amount;
        else
          $avg_position_amount = 0;
      }else{
        if($trade_record->strategy_mode == 3) {
        $total_contract = $this->db->table('api_trade_history')->selectSum('received_amount')->where($api_trade_data)->where('margin_call_drops <=',4)->get()->getRow();
        $total_usdt = $this->db->table('api_trade_history')->selectSum('quantity')->where($api_trade_data)->where('margin_call_drops <=',4)->get()->getRow();
        if($total_contract->received_amount && $total_usdt->quantity)
          $avg_position_amount = $total_usdt->quantity / $total_contract->received_amount;
        else
          $avg_position_amount = 0;
      }else{
          $total_contract = $this->db->table('api_trade_history')->selectSum('received_amount')->where($api_trade_data)->where('margin_call_drops <=',4)->get()->getRow();
        $total_usdt = $this->db->table('api_trade_history')->selectSum('quantity')->where($api_trade_data)->where('margin_call_drops <=',4)->get()->getRow();
        $total_contract2 = $this->db->table('api_trade_history')->selectSum('received_amount')->where($profit_where)->get()->getRow();
        $total_contract = $total_contract->received_amount + $total_contract2->received_amount;
        $total_usdt2 = $this->db->table('api_trade_history')->selectSum('quantity')->where($profit_where)->get()->getRow();
        $total_usdt = $total_usdt->quantity + $total_usdt2->quantity;
        if($total_contract && $total_usdt)
          $avg_position_amount = $total_usdt / $total_contract;
        else
          $avg_position_amount = 0;
      }
      }

    
        if ($avg_position_amount > 0) {
          $tradeupdate['trade_avg_position'] = number_format($avg_position_amount,5);
        }else{
          $tradeupdate['trade_avg_position'] = 0.00;
        }


$new = substr_replace( $value['symbol'], '/', -4, 0 );    

      $result=$ftx->markets()->get([
        'market_name'=> $new,// BTC/USD   BTC-PERP  BTC-0626
        //'depth'=>'10'
    ]);
          $live_price =  $result['result']['last'];

          $api_trade_data = array(
            'trade_process_id' => $trade_record->id,
            'uuserid' => $uusersid,
            'type' => '1',
            'exchange' => 2
          );

          // $first_buy =  $this->db->table('api_trade_history')->where($api_trade_data)->like('description','first_buy')->get()->getRow();


          // $tradeupdate['trade_avg_position'] = $first_buy->live_price;

            $tradeupdate['trade_avg_position'] = str_replace(',', '', $tradeupdate['trade_avg_position']);
          $tradeupdate['trade_position_amount'] = str_replace(',', '', $tradeupdate['trade_position_amount']);


          if($avg_position_amount == 0 &&  $tradeupdate['trade_position_amount'] == 0){
            $check_percentage = '0';
            $tradeupdate['floating_loss'] = 0;
          }
          else if ($avg_position_amount > $live_price) {
            
            // echo "first_buy = ".$avg_position_amount.'  -  ';
            // echo "live_price  = ".$live_price;
            // echo "<br>";
            // echo "decrease";

            // $tradeupdate['floating_loss'] = '-'.$avg_position_amount - $live_price;
            
            $check_percentage = ($avg_position_amount - $live_price) / $avg_position_amount * 100 ;
            $check_percentage = '-'.$check_percentage;
            $floating_loss = $total_position_amount->quantity * $check_percentage / 100;
            $tradeupdate['floating_loss'] = number_format($floating_loss,5);
          }elseif ($avg_position_amount == $live_price) {
            
            // echo "first_buy = ".$avg_position_amount.'  -  ';
            // echo "live_price  = ".$live_price;
            // echo "<br>";

            // echo "same";
            $check_percentage = '0.00';
            $tradeupdate['floating_loss'] = 0;
          }else{
            
            // echo "first_buy = ".$avg_position_amount.'  -  ';
            // echo "live_price  = ".$live_price;
            // echo "<br>";

            // echo "increase";
            $check_percentage = ($live_price - $avg_position_amount) / $live_price * 100 ;
            $floating_loss = $total_position_amount->quantity * $check_percentage / 100;
            $tradeupdate['floating_loss'] = number_format($floating_loss,5);

            // $tradeupdate['floating_loss'] = '+'.$live_price - $tradeupdate['trade_avg_position'];

          }

          $tradeupdate['trade_rate_percentage'] = number_format($check_percentage,2).'%';


        

 

      }else{
        $tradeupdate['trade_position_amount'] = "";
        $tradeupdate['floating_loss'] = "";
        $tradeupdate['trade_rate_percentage'] = "";
      }

    if($value['change'] > 0){
      $class = "up";
      $change = '+'.$value['change'];
    }else{
      $class = 'down';
      $change = $value['change'];
    }


    if($tradeupdate['trade_rate_percentage'] == 0){
        $default_style = "dark";
    }else if($tradeupdate['trade_rate_percentage'] > 0){
        $default_style = "primary";
    }else{
        $default_style = "danger";
    }

    if($trade_record != "") { 
    
?>
            <tr>
                <td class="getftx" data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><img src="<?php echo base_url('styles/images/tradingpair_images/'.$value['symbol'].'.png');?>"  class="img-fluid me-1" height="50px" width="50px;"><?php echo $value['symbol'];?><div class="crypto-title">
           <?php if($trade_record->sync_strategy_status == 1) { ?>
            <a href="" id="sync_strategy" class="btn btn-info">Sync Strategy</a>
            <?php } ?> </div> </td>
                <td class="text-center getftx" data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><?php echo $tradeupdate['trade_position_amount'] ? $tradeupdate['trade_position_amount'] : "0.000000" ;?></td>
                <td class="text-center getftx" data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><?php echo $tradeupdate['floating_loss'] ? $tradeupdate['floating_loss'] : "0" ;?></td>
                <td class="text-center getftx" data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><?php echo $value['price'];?></td>
                <td class="text-center getftx" data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><span class="<?php echo $class;?>"><?php echo $change;?></span></td>
                <td class="text-center getftx" data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><button class="btn btn-<?php echo $default_style; ?>"><?php echo $tradeupdate['trade_rate_percentage'] ? $tradeupdate['trade_rate_percentage'] : "0%" ;?></button></td>
              </tr>
              <?php 
            }
            }
               } 
      ?>
             
            </tbody>
          </table>
  
</div>
</div>
<script src="<?php echo base_url('styles/new_style/js/jquery-2.1.4.min.js');?>"></script>
<script src="<?php echo base_url('styles/new_style/js/bootstrap.min.js');?>"></script>
<script src="<?php echo base_url('/assets/js/plugins/notifications/jquery.quicksearch.js');?>"></script>
<!-- <script type="text/javascript" src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/rowreorder/1.2.8/js/dataTables.rowReorder.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.9/js/dataTables.responsive.min.js"></script> -->
<script type="text/javascript">
  $(document).ready(function() {
//     var table = $('#table_example').DataTable( {
//         rowReorder: {
//             selector: 'td:nth-child(2)'
//         },
//         responsive: true
//     } );
// } );

$('input#id_search2').quicksearch('table#table_example1 tbody tr');

   $('.getftx').click(function(){
    var className = this.className;
        var id = <?php echo $uusersid;?>;
            $.ajax({
      'method': 'POST',
      'url': '<?php echo base_url("/setExchange");?>',
      data:{'class':className,'id':id},
       
      success:function(msg)
        {
          console.log(msg);
          console.log("exchange set successfully");
        }
      });
        window.location = $(this).data('href');
        return false;
    });
 });
</script>