
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<script src="<?php echo base_url('/assets/js/plugins/notifications/jquery.quicksearch.js');?>"></script>
<!-- <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>
<td class="text-center"> Favourites </td>

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

$this->session = session();

$uusersid = $this->session->get('uusersid');
$validation =  \Config\Services::validation();
$this->db = db_connect();
$referral2=$this->db->query("SELECT * FROM okex_bind_process WHERE uusersid='".$userid."'")->getRow();
$key = $referral2->api_key;
$secret = $referral2->secret_key;
$passphrase = $referral2->pass_phrase;
if(empty($ref)){
  $key = 'd5c2840d-af58-4d3b-b2f6-949314f6c1b8';
  $secret = '9B24E5B3E49CB6F501EA53BDA93FB8BC';
  $passphrase = 'Yanceyker89@';
     $okex=new OkexV5($key,$secret,$passphrase);
     $okex->setOptions([
        'headers'=>['x-simulated-trading'=>1]
      ]);
}else{
   $okex=new OkexV5($key,$secret,$passphrase);
   // $okex->setOptions([
   //      'headers'=>['x-simulated-trading'=>1]
   // ]);
   // $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);
   //  }
}

   $result=$okex->market()->getTickers([
        'instType'=>'SPOT',
    ]);

$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($result['data'])) { 
foreach ($result['data'] as $key => $value) {
  if(substr($value['instId'], -5) == "-USDT"){
    if(in_array(substr_replace($value['instId'] ,"",-5), $required_pairs)){
      $output1[$i]['symbol'] = str_replace('-','',$value['instId']);
      $output1[$i]['price'] = $value['last'];
      $output1[$i]['change'] = number_format((($value['open24h'] - $value['last'])/$value['open24h']) * 100,3);
    }
      $i++;
  }
}
$k = 0;
foreach ($output1 as $key => $value) {
  $output1[$k] = $value;
  $k++;
}
$output1 =  array_unique($output1,SORT_REGULAR);
}else
   $output1 = "";

$j=0;
foreach ($output1 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')->orderBy('id','DESC')->where($where_)->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[$j]['trade_position_amount'] = number_format($total_position_amount->quantity,5);  
        }else{
          $tradeupdate[$j]['trade_position_amount'] = 0.00;
        }

            if ($total_position_quantity->received_amount > 0) {

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

          }else{

          $tradeupdate[$j]['trade_position_quantity'] = 0.00;

        }
        
        // $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[$j]['trade_avg_position'] = number_format($avg_position_amount,5);
        }else{
          $tradeupdate[$j]['trade_avg_position'] = 0.00;
        }


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

       $ticker = $okex->market()->getTicker([
        'instId'=> $new_symbol,
    ]);
         if(empty($ticker['data']) || $ticker['code'] == 51001){
        $result_okex=$okex->market()->getTickers([
        'instType'=>'SPOT',
    ]);
        if($result_okex['data']){
          foreach ($result_okex['data'] as $key => $value) {
            if($value['instId'] == $new){
              $ticker = $value;
              break;
            }
          }
      $live_price = $ticker['last'];
        }
      }else{
      $live_price = $ticker['data'][0]['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();


          // $first_buy_live_price = $first_buy->live_price;

          // $first_buy_live_price = number_format($total_position_amount->quantity,5);

           $tradeupdate[$j]['trade_avg_position'] = str_replace(',', '', $tradeupdate[$j]['trade_avg_position']);
          $tradeupdate[$j]['trade_position_amount'] = str_replace(',', '', $tradeupdate[$j]['trade_position_amount']);
          if($avg_position_amount == 0 &&  $tradeupdate[$j]['trade_position_amount'] == 0){
            $check_percentage = '0';
            $tradeupdate[$j]['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[$j]['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[$j]['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';
            $tradeupdate[$j]['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 ;
            // $tradeupdate[$j]['floating_loss'] = '+'.$live_price - $avg_position_amount;
            $floating_loss = $total_position_amount->quantity * $check_percentage / 100;
            $tradeupdate[$j]['floating_loss'] = number_format($floating_loss,5);

          }

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


        

 

      }else{
        $tradeupdate[$j]['trade_position_amount'] = "";
        $tradeupdate[$j]['floating_loss'] = "";
        $tradeupdate[$j]['trade_rate_percentage'] = "";
      }
      $j++;
}
$j=0;
if($output1){
foreach ($output1 as $key => $value) {
if($value['change'] > 0){
$class = "up";
$change = '+'.$value['change'];
}else{
$class = 'down';
$change = $value['change'];
}

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

?>   
<?php
$symbol=$value['symbol'];
$par = $this->db->query("SELECT * FROM favourites WHERE pair='".$symbol."' AND uusersid='".$uusersid."' ")->getResult();
$pair=$par[0];
                      $where_ = array(
        'pair' => $value['symbol'],
        'uusersid' => $uusersid,
        'trade_status != ' => '2',
        'exchange' => 2
      );

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

   <tr> <!--  data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>" -->
    <td class="getok"  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 getok"  data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><?php echo $tradeupdate[$j]['trade_position_amount'] ? $tradeupdate[$j]['trade_position_amount'] : "0.000000" ;?></td>
    <td class="text-center getok"  data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><?php echo $tradeupdate[$j]['floating_loss'] ? $tradeupdate[$j]['floating_loss'] : "0" ;?></td>
    <td class="text-center getok"  data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><?php echo $value['price'];?></td>
    <td class="text-center getok"  data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><span class="<?php echo $class;?>"><?php echo $change;?></span></td>
    <td class="text-center getok"  data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><button class="btn btn-<?php echo $default_style;?>"><?php echo $tradeupdate[$j]['trade_rate_percentage'] ? $tradeupdate[$j]['trade_rate_percentage'] : "0%" ;?></button></td>
              <?php  if($pair->status=='1') { ?>
                <td class="text-center get1"><i class="fa fa-heart heart" id="fa-heart1" onclick="fa_heart1('<?php echo $value['symbol'];?>');"></i></td>  
              <?php } else  { ?>
    <td class="text-center get1" ><i class="fa fa-heart-o heart" id="fa-heart" aria-hidden="true" onclick="fa_heart('<?php echo $value['symbol'];?>');"></i></td>  
              <?php } ?>
              </tr>
<?php
$j++;
}
} 
?>         
</tbody>
</table>
</div>
</div>


<!-- <script src="https://code.jquery.com/jquery-3.5.1.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 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">
  $(document).ready(function() {
//     var table = $('#table_example').DataTable( {
//         rowReorder: {
//             selector: 'td:nth-child(2)'
//         },
//         responsive: true
//     } );
// });

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

   $('.getok').click(function(){
        var className = "getok";
        var id = <?php echo $uusersid;?>;
            $.ajax({
      'method': 'POST',
      'url': '<?php echo base_url("/setExchange");?>',
      data:{'class':className,'id':id},
       
      success:function(msg)
        {
          console.log("set exchange");
        }
      });

        window.location = $(this).data('href');
        return false;
    });
 });

 function fa_heart(b)
 {   
        var uusersid = $('#uusersid').val();    
        var symbl = b;
       
        $.ajax({
          type: 'post',
          url : '<?php echo base_url("/dashboard/favourites");?>',
          data : {'uusersid':uusersid,'symbl':symbl},
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          success : function(msg)
          {
            location.reload(true);
            if(msg)
            {
               
            }
          }
      });     
    }  


     function fa_heart1(a)
     {
        var uusersid = $('#uusersid').val();
        var symbl = a;
      
        $.ajax({
          type: 'post',
          url : '<?php echo base_url("/dashboard/favourites1");?>',
          data : {'uusersid':uusersid,'symbl':symbl},
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          success : function(msg)
          {
            location.reload(true);
            if(msg)
            {

            }
          }
      }); 
    }

  $(".heart .fa").click(function() 
  {
    $(this).toggleClass("fa-heart fa-heart-o");

  });


</script>