<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;
  }

.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 
$this->session = session();

$uusersid = $this->session->get('uusersid');
$validation =  \Config\Services::validation();
$this->db = db_connect();
$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."'")->getResult();
$ref=$referral1[0];
$key = $ref->api_key;
$secret = $ref->secret_key;
if(empty($ref)){
  $key = "tJuR6dN9AZp9KiAn41avxq64KsyDxa8FIaRjxTf0k1qplZIv1MRnHrS3zQIqHuzZ";
$secret = "GlRLQS2VGYfa1sOUaS3NIgGmszJOAuxu7Xk0anY1r4ifRmGYVYxoG25LOBnESE67";
$api = new Binance\API($key,$secret);
}else{
   $api = new Binance\API($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);
    }
}

$marketpair = $api->prevDay();
$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'];
foreach ($marketpair as $key => $value) {
if(substr($value['symbol'], -4) == "USDT"){
if(in_array(substr_replace($value['symbol'] ,"",-4), $required_pairs)){
$output[$i]['symbol'] = $value['symbol'];
$output[$i]['price'] = $value['lastPrice'];
$output[$i]['change'] = $value['priceChangePercent'];
}
$i++;
}
}

$k = 0;
foreach ($output as $key => $value) {
  $output[$k] = $value;
  $k++;
}

$output =  array_unique($output,SORT_REGULAR);

$j=0;
foreach ($output as $key => $value) {


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

      $where_ = array(
        'pair' => $pair,
        'uusersid' => $uusersid,
        'trade_status != ' => '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
        );

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

        $profit_where = array(
            'uuserid' => $uusersid,
            'type' => '3',
            'trade_process_id' => $trade_record->id,
            'status' => 0
        );
      
        $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;
        }



      

       $ticker = $api->prices($value['symbol']); 
          $live_price =  $ticker[$value['symbol']];

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

          // $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($output){
foreach ($output 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];
?> 

   <tr> <!--  data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>" -->
    <td class="get"  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'];?> </td>
    <td class="text-center get"  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 get"  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 get"  data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><?php echo $value['price'];?></td>
    <td class="text-center get"  data-href="<?php echo base_url('tradedetails/'.$value['symbol']);?>"><span class="<?php echo $class;?>"><?php echo $change;?></span></td>
    <td class="text-center get"  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 type="text/javascript">
  $(document).ready(function() {
//     var table = $('#table_example').DataTable( {
//         rowReorder: {
//             selector: 'td:nth-child(2)'
//         },
//         responsive: true
//     } );
// });

$('input#id_search').quicksearch('table#table_example tbody tr');

 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");

  });

   $('.get').click(function(){
        window.location = $(this).data('href');
        return false;
    });
 });
</script>