<?php 
namespace App\Controllers\User;
use App\Views;
use App\Models\CommonModel;
use App\Helpers\site_helper;
use App\Libraries\MyEncrypt;
use Binance;


class Mycircle extends BaseController {
	
	public function __construct() 
	{
		helper('site_helper');
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		$status = site_info('site_status');
		if($status!='on')
		{
			return redirect()->to('offline');
		} 
		// user login only
		if($session->get('user_login') || $session->get('admin_login')) 
		{
			// form validation library
			// $this->load->library('form_validation');
			// $this->load->model('userdash_model');
			// $this->load->model('finance_model');
			$this->finance_model = model('finance_model');
			$this->userdash_model = model('userdash_model');
		} 
		else 
		{
			throw new \CodeIgniter\Router\Exceptions\RedirectException('login');
		}		
	}
	
	public function index()
	{
		$session = \Config\Services::session();
		if(!($session->get('user_login') || $session->get('admin_login')))
		{			
			return redirect()->to('login');
		}
		echo view('user/mycircle');

	}
	public function mycircle_view($id='')
	{
		$session = \Config\Services::session();
		if(!$session->get('user_login')){
			return redirect()->to(site_url('user/login'));
		}
		$condition = "id ='".$id."'";
		$this->data['trade'] = $this->common_model->GetRow('trader',$condition);
		echo view('user/mycircle_view',$this->data);
	}


	public function cancel_sync($id=""){
		$uusersid=SESSION('uusersid');

		$trade_data1 = array(
            "strategy_id" => "",
            "sync_strategy_status" => 0
		);
		

		$query_status = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($trade_data1);
		
			if($query_status)
			{
				$session = \Config\Services::session();
				$session->setFlashData('success_message', 'Trader Settings Updated Successfully');
			}
			else
			{
				$session = \Config\Services::session();
				$session->setFlashData('error_message', 'Trader Settings Updation Failed');
			}

		return redirect()->to('mycircle/mycircle_view/'.$id);
        
	}

	public function strategy_table($id='')
	{
		$this->db = db_connect();
		$this->session = session();
		$condition = "id ='".$id."'";
		$trader_tab=$this->common_model->GetRow('trader',$condition);
		$margin_column_limit =$trader_tab->margin_column_limit;
		$strategy_id=$trader_tab->id;
		$tade1=$trader_tab->margincall_drop;
		$tade2=$trader_tab->buyin_ratio_times;
		// $first_buy_amount=$trader_tab->first_buy_amount;
		// $open_position_doubled=$trader_tab->open_position_doubled;
		$whole_profit_ratio=$trader_tab->whole_profit_ratio;
		$whole_profit_callback=$trader_tab->whole_profit_callback;
		$buyin_callback=$trader_tab->buyin_callback;
		$sub_position_callback = $trader_tab->sub_position_callback;
		$no_strategies=$trader_tab->no_strategies;
		$session= \Config\Services::session();
 		$uusersid=$session->get('uusersid');


		$condition1 = "uusersid ='".$uusersid."'";
		$user=$this->common_model->GetRow('user_strategy',$condition1);
		$first_buy_amount=$this->request->getPost('first_buy_amount');
		$open_position_doubled=$this->request->getPost('open_position_doubled');
		$no_strategies =$this->request->getPost('no_of_strategies');
		if($first_buy_amount < 11)
				$first_buy_amount = 11;
		if($user=='')
		{
			$qury = $this->db->query("SELECT * FROM suggested_strategy WHERE id='1' ")->getResult();
		    $qry = $qury[0];
			$margin_column_limit =$qry->margin_column_limit;
		
			$whole_profit_ratio=$qry->whole_profit_ratio;
			$whole_profit_callback=$qry->whole_profit_callback;
			$buyin_callback=$qry->buyin_callback;
			$sub_position_callback	= $qry->sub_position_callback;
			
			$tade1=$qry->margincall_drop ;
			$tade2=$qry->buyin_ratio_times;
		
            $trade_data = array(
				"first_buy_amount" 		=>  $first_buy_amount,
		        "open_position_doubled" =>  $open_position_doubled,
		        "margin_column_limit" 	=>  $margin_column_limit,
		        "whole_profit_ratio"	=>  $whole_profit_ratio,
		        "whole_profit_callback" =>  $whole_profit_callback,
		        "buyin_callback" 		=>  $buyin_callback,
		        "margincall_drop"		=> 	$tade1,
		        "buyin_ratio_times"		=>	$tade2,
		        "strategy_id"           =>  $id, //trade_id ( circle trader id)
		        "sub_position_callback" =>  $sub_position_callback,
		        "no_strategies"         =>  $no_strategies,
		        "sync_strategy_status"	=> 	1
			);

		$query_status = $this->db->table('user_strategy')->insert($trade_data);
        
		}
		else
		{
			$trade_data1=array(
 			
			"first_buy_amount" 		=>  $first_buy_amount,
	        "open_position_doubled" =>  $open_position_doubled,
	        "no_strategies"      =>  $no_strategies,
	        "strategy_id"          => $id,
	        "sync_strategy_status"	=>  1
			);

			$query_status = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($trade_data1);
		}

		$user =$this->common_model->GetRow('user_strategy',$condition1);
        $kj= 0;
	 if($user->currency_block_list == ""){
			$pairs = explode(',', $trader_tab->coin_id);
	 }else{
			$pairs_pre = explode(',', $trader_tab->coin_id);
		    foreach ($pairs_pre as $key => $value) {
				if(!in_array($value, explode(',', $user->currency_block_list))){
                     $pairs[$kj] = $value;
                     $kj++;
				}
			}
		}



	if($query_status && $pairs)
	{
	$this->session = session();

	 $sync_data = array(
	 	        "uusersid"              =>  $this->session->get('uusersid'),
				"first_buy_amount" 		=>  $first_buy_amount,
		        "open_position_doubled" =>  $open_position_doubled,
		        "margin_column_limit" 	=>  $trader_tab->margin_column_limit,
		        "whole_profit_ratio"	=>  $trader_tab->whole_profit_ratio,
		        "whole_profit_callback" =>  $trader_tab->whole_profit_callback,
		        "buyin_callback" 		=>  $trader_tab->buyin_callback,
		        "margincall_drop"		=> 	$trader_tab->margincall_drop,
		        "buyin_ratio_times"		=>	$trader_tab->buyin_ratio_times,
		        "strategy_id"           =>  $id, //trade_id ( circle trader id)
		        "sub_position_callback" =>  $trader_tab->sub_position_callback,
		        "strategy_mode"         =>  $trader_tab->strategy_mode,
		        "buyin_callback"         =>  $trader_tab->buyin_callback,
		        "sub_position"         =>  $trader_tab->sub_position,
		        "strategy_type"         =>  "Cycle Strategy",
		        "exchange" => 1,
		        "sync_strategy_status"	=> 	1
			);
    $lk=0;
    foreach ($pairs as $key => $value) {
    	$trade_query = $this->db->query("SELECT * FROM trade_process WHERE uusersid= '".$this->session->get('uusersid')."' and pair = '".$value."' and trade_status != 2 and exchange = 1 order by id desc")->getRowArray();
    	if(empty($trade_query) || $trade_query == ''){
            $pairs_pre1[$lk] = $value;
            $lk++;
    	}
    }
  
    $pairs = $pairs_pre1;


    if($pairs_pre1 != '')
        $avaliable_pair_count = count($pairs_pre1);
    else
    	$avaliable_pair_count = 0;

    $already_available = $this->db->query("SELECT * FROM trade_process WHERE strategy_id = '".$strategy_id."' and uusersid= '".$this->session->get('uusersid')."'  and trade_status != 2 and sync_strategy_status = 1 and exchange = 1 order by id desc")->getNumRows();
   
    $trade_active_query = $this->db->query("SELECT * FROM trade_process WHERE strategy_id = '".$strategy_id."' and uusersid='".$this->session->get('uusersid')."' and trade_status != 2 and exchange = 1 and sync_strategy_status = 1")->getResult();

	if(empty($trade_active_query) || $trade_active_query == ''){
		if($already_available > $no_strategies){
			$pairs = array_slice($pairs, 0, $no_strategies);
		}
	}else{
		// $trade_active_count = count($trade_active_query);
		$no_strategies = $no_strategies - $already_available;
		if($no_strategies != 0){
		if($already_available > $no_strategies){
			$pairs = array_slice($pairs, 0, $no_strategies);
		}
	    }else{
	    	$pairs = "";
	    }
}

if(!empty($pairs)) { 	
	foreach($pairs as $pair) { 
		$sync_data['trade_status'] = 1;
		$sync_data['pair'] = $pair;
		$sync_data['margin_call'] = 1;
		$sync_data['created_time'] = time();
        $query_status = $this->db->table('trade_process')->insert($sync_data);
         $last_id = $this->db->insertId();
         if($last_id) { 
       	$qry_new = $this->db->query("SELECT * FROM trade_process WHERE id='".$last_id."'")->getRowArray();
        if($qry_new['open_position_doubled'] != 'on' || $qry_new['open_position_doubled'] == '')
        	$quantity = 1;
        else
            $quantity = 2;
            $price = $qry_new['first_buy_amount'] * $quantity;
            $flags['isQuoteOrder'] = true;
            	
        $referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$qry_new['uusersid']."'");

        $ref=$referral1->getRow();
        $key = $ref->api_key;
        $secret = $ref->secret_key;
        $api = new Binance\API($key,$secret);

        if($price <= 11){
        	$price = 11;
        }

		$order = $api->marketQuoteBuy($qry_new['pair'], $price,$flags);



		$order_history = array(
			'pair' => $order['symbol'],
			'order_id' => $order['orderId'],
			'trade_process_id' => $qry_new['id'],
			'uuserid' => $qry_new['uusersid'],
			'type' => '1',
			'strategy_mode' => $qry_new['strategy_mode'],
			'quantity' => $order['cummulativeQuoteQty'],
			'original_quantity' => $price,
			'time' => $order['transactTime'],
			'received_amount' => $order['executedQty'],
			'date' => date('Y-m-d',time()),
			'description'=>'first_buy',
			'live_price' => $order['fills'][0]['price'],
			'status' => 0,
		);
		$this->db = db_connect();
		$this->db->table('api_trade_history')->insert($order_history);
	}
  }
    echo 1;
  exit;
}else{
	$session = \Config\Services::session();
				$session->setFlashData('error_message', 'Sync Failed');
				echo 0;
				exit;
}
}
			
			
	}          

	public function replenishment_time()
	{
			$id = service('request')->getPost('id');
			$num = service('request')->getPost('number');
			$this->db = db_connect();
			$qury = $this->db->query("SELECT * FROM trader WHERE id='".$id."'")->GetResult();
			$qry=$qury[0];				
			$lmt=$qry->buyin_ratio_times;
			$margin=explode(',',$lmt);
			$margn=array_slice($margin,-$num);
			if($num >= 5)
			{
				for ($i=4; $i < $num; $i++) 
				{ 
					$c=$i+1;
					echo   "<div class='modal-form mb-4'>";
					echo    "<label class=''>The ".$c."th sub-position</label>";
					echo   "<div class='input-group'>";
					echo    "<input type='text' class='form-control mt-1' name='rep_time".$i."' disabled placeholder='' value=".$margn[$i].">";
					echo    "<span class='input-group-text mt-1'>% </span> </div>";
					echo   "</div>";
				}
		   }
		   else
		   {
		   	 echo "";
		   }
	}
	

	public function replenishment_time1()
	{
		$id = service('request')->getPost('id');
		$num = service('request')->getPost('number1');
		$this->db = db_connect();
		$qury = $this->db->query("SELECT * FROM trader WHERE id='".$id."' ")->GetResult();
		$qry=$qury[0];
		
		$marg=$qry->margincall_drop;
		$margin=explode(',',$marg);

		for ($i=0; $i < $num; $i++) 
		{ 
			$c=$i+1;
			echo   "<div class='modal-form mb-4'>";
			echo    "<label class=''>The ".$c."nd call</label>";
			echo   "<div class='input-group'>";
			echo    "<input type='text' class='form-control mt-1' name='call_time".$i."' disabled placeholder='' value=".$margin[$i].">";
			echo    "<span class='input-group-text mt-1'>% </span> </div>";
			echo   "</div>";
		}
	}

	public function replenishment_time2()
	{
		$id = service('request')->getPost('id');
		$num = service('request')->getPost('number2');
		$this->db = db_connect();
		$qury = $this->db->query("SELECT * FROM trader WHERE id='".$id."' ")->GetResult();
		$qry=$qury[0];		
		$buy=$qry->buyin_ratio_times;
		$buyin=explode(',',$buy);
		for ($i=0; $i < $num; $i++) 
		{ 
			$c=$i+1;
			echo   "<div class='modal-form mb-4'>";
			echo    "<label class=''>The ".$c."th order amount</label>";
			echo   "<div class='input-group'>";
			echo    "<input type='text' class='form-control mt-1' name='order_time".$i."' disabled placeholder='' value=".$buyin[$i].">";
			echo    "<span class='input-group-text mt-1'>Times </span> </div>";
			echo   "</div>";
	   }
	}		
}