<?php 
namespace App\Controllers\Admin;
use App\Views;
use App\Models\CommonModel;
use App\Libraries\MyEncrypt;
use App\Libraries\PHPMailer;
use App\Libraries\Commission;

class Botactivate extends BaseController {

	/**
	* 
	* Start 
	* Create Date: 15 July, 2016
	* This controller to manage all transactions.
	* Created saravanan.
	* @see http://zhyip.com/
	* Last Updated: 18 November, 2016
	* End
	* 
	*/

	public function __construct() {
        $this->session = session();
		// admin login only
		if($this->session->get('admin_login')) {

			// form validation library
			// $this->load->library('form_validation');
            $this->finance_model = model('finance_model');
            $this->packages_model = model('packages_model');

			// $this->load->model('finance_model');
			// $this->load->model('packages_model');

			helper('inflector');
			$this->isSubadmin();
			
			
		} else {
			if(isset($_COOKIE['remember_token'])) {

				$myencrypt = new MyEncrypt;
				$token_value = $myencrypt->decode($this->input->cookie('remember_token'));
				$this->isCookie($token_value);	

			} else {
				$this->session->set('last_page', current_url());
				return redirect()->to('admin/login');
			}
		}

	}

	private function isSubadmin() {
		$this->router = service('router');
        $this->session = session();
        $this->form_validation = \Config\Services::validation();
		if($this->session->get('user_type') == 'subadmin') {
			$controller = $this->router->controllerName();
			$pages = json_decode($this->session->get('permission'));
		
			/*if(!in_array(ucfirst($controller), $pages)) {
				return redirect()->to('admin');
			}*/
		}
	}

	// 
	private function isCookie($values) {

		$value = explode('|', $values);
		$result = $this->common_model->getPassword($value[0]);
		$hashed_password = $result->password;

		if(crypt(urlencode($value[1]), $hashed_password)) {

			$array = array(
				"logged_in" => TRUE,
				"userid" => $result->id,
				"admin_login" => TRUE
			);
			$this->session->set($array);

		} else {
			return redirect()->to('admin/login');
		}
	}

     public function index()
     {
        $this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => 'Bot activate list'
		);
		
		$this->data['module_name'] = 'finance';
        $this->data['page_title'] = 'Bot Activate list';

		$admin_login=$this->session->get('userid');
		$get_admin=$this->db->query("select * from admin where id='".$admin_login."'")->getRow();
		$user_group = $get_admin->user_group;


		if($user_group=='0')
			$condition='';
		else if($user_group=='1')
			$condition="new_entry='0'";
		else if($user_group=='2')
			$condition="new_entry='1'";

	
        $this->data['users'] = $this->common_model->GetResults('uusers', $condition);
        $this->data['tradepair'] = $this->common_model->GetResults('tradepair_list');


		if($this->request->getPost())
		{
			$username=$this->request->getPost('username');
			$fromdate=$this->request->getPost('start_date');
			$todate=$this->request->getPost('end_date');
			$pair=$this->request->getPost('symbols');
			$status=$this->request->getPost('status');
			$user_type=$this->request->getPost('user_group');
			
			$from='';
			$to='';
         	$this->data['user']=$username;
			$this->data['fromdate']=$fromdate;
			$this->data['todate']=$todate;
			$this->data['pairs']=$pair;
			$this->data['status']=$status;
			$this->data['user_type']=$user_type;

			//print_r($this->request->getPost());
			
			$condi='';
			if($username!='')
			{
			    $get_user=$this->db->query("select * from uusers where username='".$username."'")->getRow();
			    $userid=$get_user->uusersid;
				$condi.=" and uusersid='".$userid."'";
			}
			if($pair!='')
			{
				$condi.=" and pair='".$pair."'";
			}
			if($status!='')
			{
				$condi.=" and trade_log='".$status."'";
			}
			else
			{
				if($fromdate!='' && $todate!='')
				{
					$from=date("Y-m-d 00:00:00", strtotime($fromdate));
					$to=date("Y-m-d 23:59:59", strtotime($todate));
				}
				else if($fromdate!='' && $todate=='')
				{
					$from=date("Y-m-d 00:00:00", strtotime($fromdate));
					$to=date("Y-m-d 23:59:59", strtotime($fromdate));
				}
				else if($fromdate=='' && $todate!='')
				{
					$from=date("Y-m-d 00:00:00", strtotime($fromdate));
					$to=date("Y-m-d 23:59:59", strtotime($todate));
				}
				

				if($from!='' && $to!='')
				{
					$from=strtotime($from);
					$to =strtotime($to);
					$condi.=" and created_time between $from and $to";
				}
			}

			
			
			$this->data['trades']=$this->db->query("select * from trade_process where trade_status!='2' and flag='0' $condi group by uusersid,pair order by id desc")->getResult();

		}
		else
		{
			$this->data['user']='';
			$this->data['fromdate']='';
			$this->data['todate']='';
			$this->data['pairs']='';
			$this->data['status']='';
			$this->data['user_type']='';

			$this->data['trades']=$this->db->query("select * from trade_process where trade_status!='2' and flag='0'  group by uusersid,pair order by id desc")->getResult();
		}
  
        // echo '<pre>';
        // print_r($this->data['tradepair']);
        // exit;

        echo view('admin/botactivate-list',$this->data);
     }

	 public function acitvate_trade()
	 {
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();

		$uusersid=$this->request->getPost('userid');
		$exchange=$this->request->getPost('exchange');
		$pair=$this->request->getPost('pair');

		$query_status = $this->db->query("UPDATE trade_process SET trade_status=1, updated_time='".time()."' WHERE uusersid='".$uusersid."' and pair='".$pair."' and exchange='".$exchange."' and trade_status = 0 order by id desc ");


		$session = \Config\Services::session();
		$session->setFlashData('success_message', 'Request Trade status activated successfully');
		return redirect()->to('admin/bot/activate-list');

	}

	public function pause_trade()
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();

		$uusersid=$this->request->getPost('userid');
		$exchange=$this->request->getPost('exchange');
		$pair=$this->request->getPost('pair');

		$query_status = $this->db->query("UPDATE trade_process SET trade_status=0, updated_time='".time()."' WHERE uusersid='".$uusersid."' and pair='".$pair."' and exchange='".$exchange."' and trade_status = 1 order by id desc ");


		$session = \Config\Services::session();
		$session->setFlashData('success_message', 'Request Trade status paused successfully');
		//return redirect()->to('admin/bot/activate-list');

	}
	
	public function close_trade()
	{
        
        
        $this->db = db_connect();
	    $session = \Config\Services::session();
		$validation = \Config\Services::validation();

		$uusersid=$this->request->getPost('userid');
		$exchange=$this->request->getPost('exchange');
		$pair=$this->request->getPost('pair');
		
        $trade_process = $this->db->query("SELECT * FROM trade_process WHERE uusersid='".$this->request->getPost('userid')."' and pair='".$this->request->getPost('pair')."' and exchange='".$this->request->getPost('exchange')."' and trade_status!='2' order by id desc")->getRow();

        
	    if($trade_process)
	    {
	        
	        $trade_where = array(
			'uuserid' => $uusersid,
			'type' => '1',
			'trade_close' => 0,
			'trade_process_id' => $trade_process->id,
		    );
	
			$trade_where2 = array(
				'trade_process_id' => $trade_process->id,
				'uuserid' => $uusersid,
				'type' => '2',
				'description' => 'manual_sell',
				'status' => 0
			);
			
		

       	    $total_position_amount1 = $this->db->table('api_trade_history')->selectSum('received_amount')->where($trade_where)->orderBy('id','DESC')->get()->getRow();
		    $total_sell_amount = $this->db->table('api_trade_history')->selectSum('received_amount')->where($trade_where2)->get()->getRow();
		    if($total_sell_amount->received_amount == "")
			    $total_sell_amount->received_amount = 0;
            $total_position_amount=$total_position_amount1->received_amount;
            
           
		    $quantity = number_format($total_position_amount,8);
		
		     $referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$this->request->getPost('userid')."' and type= '1'")->getRow();
		      $key = $referral1->api_key;
             $secret = $referral1->secret_key;
             
          
		    
		     if($trade_process->exchange == 1) 
		    {    
			    $ticker = ''; // Make sure you have an updated ticker object for this to work
			    $balances=0;
			    $send_pair=substr($pair,0,-4);
			    echo $send_pair;
			   	$total_asset='0';
				$balances=binance_balance1($key,$secret,$send_pair);
                if($balances)
                {
                    $total_asset=$balances;
                }
			    $quantity = str_replace(',', '', $quantity);
                $total_asset = str_replace(",",'',$total_asset);
		        if($total_asset < $quantity)
		        {
			        if($trade_process->pair == "BNBUSDT")
				        $quantity_fee = $total_asset * ( 0.65 / 100 );
			        else
				        $quantity_fee = $total_asset * ( 0.1 / 100 );
				        
				    $quantity_fee=number_format($quantity_fee,8);
				    $quantity_los = $total_asset - $quantity_fee;
			    }    
			    
			  
    		    if($total_asset < $quantity)
    		    {
    			    $quantity = $total_asset;
    		    }
		    
		        $data_binance = json_decode(file_get_contents('https://revotechbot.com/trading_pairs.json'), true);
		        
		         $live_price='';
                 foreach ($data_binance as $datas) 
                 {
                    if ($datas['symbol'] == $trade_process->pair) 
                    {
                        $live_price=$datas['lastPrice'];
                       // $high_price=$datas['closePrice'];
                       break;   
                    }
                    
                 }
             	$trade_where = array(
				    'uuserid' => $uusersid,
					'type' => '1',
					'trade_close' => 0,
					'trade_process_id' => $trade_process->id,
						);
                 $buy_records = $this->db->table('api_trade_history')->selectAvg('live_price')->where($trade_where)->get()->getRow();
                 $buy_records1 = $this->db->table('api_trade_history')->selectSum('quantity')->where($trade_where)->get()->getRow();
                 
                 $avg_price = round($buy_records,8) * $trade_process->whole_profit_ratio / 100;
                 $max_increase_price = $buy_records + $avg_price ;
			     $max_increase_price = round($max_increase_price,8);
			     $max_down_percentage = $max_increase_price * $trade_process->whole_profit_callback / 100;
                 $max_down_price = $max_increase_price - $max_down_percentage;
			     $max_down_price = round($max_down_price,8);
			     $max_increase_price = sprintf('%.8f', floatval($max_increase_price));
                 $price = $max_increase_price; 
                 $live_price=number_format($live_price,9);
                 $live_price=str_replace(',','',$live_price);
                 
                
		         $result = $this->take_profit($uusersid,$trade_process->id,$quantity,$price,$live_price,$referral1,$trade_process->pair,$buy_records1);
		         if($result)
		         {
		             
		         }
		         else
		         {
		             
		         }
		         
		         
		         
		    }
            
	        
	            
	    }
	
	
		//$session->setFlashData('success_message', 'Request Trade status paused successfully');
		$session->setFlashData('success_message', 'Trade status closed successfully');
		echo "success";
		//return redirect()->to('admin/bot/activate-list');
	    
	}
	
    public function take_profit($userid,$trade_process_id,$quantity,$price,$stopPrice,$api,$pair,$avg_price,$description="",$flag=""){


        //print_r("userid".$userid);
		//print_r("sell pair".$pair);
		//print_r("sell amount".$quantity);
     
	    $quantity = str_replace(',', '', $quantity);
	   
	     $trade_process = $this->db->table('trade_process')->where('uusersid',$userid)->where('id',$trade_process_id)->get()->getRow();

	 		  if($trade_process->exchange == 1) 
			  { 
					//$exchange_info = $api->exchangeInfo();
					
					$userid_bind_process = $this->db->table('bind_process')->where('uusersid',$userid)->get()->getRow();
					
    				$api_key = $userid_bind_process->api_key;	
    				$api_secret = $userid_bind_process->secret_key;	
    				
    				$exchange_info=binance_exchangeinfo($api_key);
		
			        $filters='';
    				foreach($exchange_info as $key => $value) 
    				{
    				   
    					if($value['symbol']==$pair)
    					{
    						 $filters=$value['filters'];
    						    break;
    					}
    				}
				
    				$lotSizeFilter = null;
                    foreach ($filters as $filter) {
                      //  print_r($filter);
                        if ($filter['filterType'] === 'LOT_SIZE') {
                            $lotSizeFilter = $filter;
                            break;
                        }
                    }
                    
                    $minQty = $lotSizeFilter['minQty'];
                    $maxQty = $lotSizeFilter['maxQty'];
                    $stepsize = $lotSizeFilter['stepSize'];
                    $stepsize1 = fmod($stepsize, 1);
					$total_no = str_replace('.', '', $stepsize1);
					$count = strlen($total_no);

					// $stepsize = explode('.', $stepsize)[1];
					if($stepsize == 1.00000000)
						$current = 0;
					else
						$current = $count - 1;
                      

                    /*echo $pair;
                    echo "<br>";
                    echo $quantity;
                    echo "<br>";*/
                    
			    	//$order = $api->sell($pair,$quantity,0,"MARKET");
			    	//$order=binance_sell($key,$secret,$pair,$quantity,"MARKET");
			    	$order=binance_order($api_key,$api_secret,"SELL", $pair, $quantity, 0,"MARKET",$flags);
			    	
			    	echo '<pre>';
			    	print_r($order);
			    	echo '</pre>';
			    	
			
					if(empty($order['orderId'])) 
					{
						$quantity = $this->truncate_number($quantity,$current); 
						$quantity = str_replace(',', '', $quantity);
						//$order = $api->sell($pair,$quantity,0,"MARKET");
						//$order=binance_sell($key,$secret,$pair,$quantity,"MARKET");
						$order=binance_order($api_key,$api_secret,"SELL", $pair, $quantity, 0,"MARKET",$flags);
						
					}
				}
		        if($order) 
		        { 
        			if(!empty($description) || $description == "") 
        			{
            			$buy_record_update = $this->db->table('trade_process')->set('flag','0')->where("id",$trade_process_id)->update();
            			$buy_record_update1 = $this->db->table('trade_process')->set('flag_buy','0')->where("id",$trade_process_id)->update();
            			$buy_record_update2 = $this->db->table('trade_process')->set('sell_limit','')->where("id",$trade_process_id)->update();
        			
        			}

            	     $db = db_connect();
            		 $admin_settings = $db->table('adminsettings')->orderBy('id','DESC')->get()->getRow();
            		 $fuel_fee_percent = $admin_settings->min_fuel_fee;
            		 $total_avg_price = $avg_price->quantity;
            		 $description='close_trade';

            		if($trade_process->exchange == 1)
            		{ 
            	         if($subsell_status != 1)
            		     $avg_price1 = $order['cummulativeQuoteQty'] - $avg_price; 
            		     else
            		     $avg_price1 = $order['cummulativeQuoteQty'] - $avg_price;
            
            			$orderid = $order['orderId'];
            			$pos_qty = $order['cummulativeQuoteQty'];
            			$time_order = $order['transactTime'];
            			$res_qty = $order['executedQty'];
            
            
            	     }else if($trade_process->exchange == 2){
                         if($subsell_status != 1)
            		     $avg_price1 = $position_quantity - $avg_price; 
            		     else
            		     $avg_price1 = $position_quantity - $avg_price; 
            
            			 $orderid = $order['ordId'];
            			 $pos_qty = $position_quantity;
            			 $time_order = $order['fillTime'];
            			 $res_qty = $order['sz'];
            	     }else{
                         if($subsell_status != 1)
            		     $avg_price1 = $position_quantity - $avg_price; 
            		     else
            		     $avg_price1 = $position_quantity - $avg_price; 
            
            			$orderid = $order['id'];
            			$pos_qty = $position_quantity;
            			$time_order = strtotime($order['createdAt']);
            			$res_qty = $order['size'];
            	     } 
                    $total_position_amount1 = $this->db->table('api_trade_history')->selectSum('quantity')->where("trade_process_id",$trade_process_id)->where("trade_close",'0')->orderBy('id','DESC')->get()->getRow();
                    $total_position_amount=$total_position_amount1->quantity;
                    $sell_quantity=$pos_qty;
		            if($sell_quantity > $total_position_amount)
            		{
            			$profit=$sell_quantity-$total_position_amount;
            		}
            		else
            		{
            			$profit=$sell_quantity- $total_position_amount;
            		}

            		$profit_percentage=($profit/$total_position_amount)*100;
            
            		$fuel_fee = $profit * ($fuel_fee_percent / 100);

       
    	if($orderid > 0)
    	{
    		$order_history = array(
    			'pair' => $pair,
    			'order_id' => $orderid,
    			'trade_process_id' => $trade_process_id,
    			'uuserid' => $userid,
    			'type' => '2',
    			'quantity' => $pos_qty,
    			' original_quantity' => $pos_qty,
    			'time' => $time_order,
    			'received_amount' => $res_qty,
    			'live_price' => $stopPrice,
    			'avg_price' => $avg_price1,
    			'comm_price' => $profit,
    			'profit_percentage' => $profit_percentage,
    			'description' => $description,
    			'margin_call_drops' => '',
    			'date' => date('Y-m-d',time()),
    			'strategy_mode' => $trade_process->strategy_mode,
    			'strategy_type' => $trade_process->strategy_type,
    			'flag' => $flag ? $flag : 0,
    			'status' => 0,
    			'exchange' => $trade_process->exchange
    		);
        	$this->db->table('api_trade_history')->insert($order_history);
    	    
    	    if($fuel_fee > 0)
        	{
                $deposit_data = array(           // fuel fee deduction
                'uusersid' => $userid,
                'amount'  => $fuel_fee,
                'depositid' => $this->db->InsertID(),
                'type'  => 'deducted_gaswallet', 
                'description'  => 'fuel fee deduction for order no '.$orderid,
                'date'  => date('Y-m-d H:i:s'),
                'currency' => 1,
                'transactionid' => $trade_process_id
                );
    		    $this->db->table('history')->insert($deposit_data);
        	}
    	$sell_record_update = $this->db->table('api_trade_history')->set('trade_close','1')->where('trade_close','0')->where("trade_process_id",$trade_process_id)->update();
    	
    	$sell_record_update = $this->db->table('trade_process ')->set('trade_status','2')->where('trade_log','0')->where("id",$trade_process_id)->update();
    	}
		$return = true;
	}
	else
	{
		/*$duplicate_check = $this->db->table('notification_table')->where('uusersid',$userid)->like('message','Binance '.$pair)->like('created_date',date('Y-m-d'))->getRow();
			if(!$duplicate_check) { 
			$notification = array(
			'uusersid' => $userid, 
			'message'  => 'Binance '.$pair.' failed to cover short position due to insufficient exchange balance and has stopped opening short position. if you need to reopen short position, please go to the strategy details page of Open margin call',
			'created_date' => date('Y-m-d H:i:s')
			);
			$this->db->table('notification_table')->insert($notification);
			}*/
		$return = false;
	}
		return $return;
	}	
	
	
	

}