<?php 
// if ( ! defined('BASEPATH')) exit('No direct script access allowed');
namespace App\Controllers\User;
use App\Views;
use Binance;
use App\Models\CommonModel;
use App\Helpers\site_helper;
use App\Libraries\MyEncrypt;



class Dashboard extends BaseController {

	public function __construct() {
	    $this->db = db_connect();
	    helper('site_helper');

		$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(!empty($session->get('uusersid')) || $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 home_page(){
		$this->db = db_connect();
		$this->session  = session();
		$uusersid = $this->session->get('uusersid');
		$slider_condition = "status = '1'";
		$this->data['sliders'] = $this->common_model->GetResults('slider_controls',$slider_condition);
		$this->data['operation'] =$this->db->query("SELECT * FROM trade_process WHERE uusersid='".$uusersid."' and trade_status != 2 order by id desc")->getResult();
		$i=0;
		foreach ($this->data['operation'] as $key => $value) {
			$required_pairs[$i] = substr($value->pair, 0, -4);
			$i++;
		}
		$this->data['required_pairs'] = $required_pairs;
		echo view('user/home',$this->data);
	}
	
	public function index()  {
        $this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$this->finance_model = model('finance_model');
	    $this->userdash_model = model('userdash_model');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!($session->get('user_login') || $session->get('admin_login')))
		{			
			return redirect()->to('login');
		}
		$languageid = ($session->get('user_langid')) ? $session->get('user_langid'): '1';	
		$this->data['user'] = $this->common_model->GetUser($session->get('uusersid'));
		$user_balance = $this->check_balance();
		if($user_balance < 0) {
			$this->data['balance'] = 0;	
		} else {
			$this->data['balance'] = $user_balance;	
		}

		$site_data = $this->common_model->GetSettingall('infobox');
		if($site_data) {		
			foreach ($site_data as $row) {
				$this->data[$row->site_key] = $row->site_value;
			}

		} else {
			$site_data_default = $this->common_model->defaultlangSettingall('infobox');
			foreach ($site_data_default as $row) {
				$this->data[$row->site_key] = $row->site_value;
			}
		}

		$site_lang_data = $this->common_model->GetSiteSettings('site');
		
		
		if($site_lang_data){	
			$site_data = array_merge($site_data, $site_lang_data);
		}

		foreach ($site_data as $row) {
			$this->data[$row->site_key] = $row->site_value;
		}
		

		$deposit_condition = "type IN ('deposit')";
		$this->data['total_deposit'] = $this->userdash_model->MyHistoryData($deposit_condition);

		$payout_condition = "type IN ('withdraw_request', 'withdrawal')";
		$this->data['total_payouts'] = $this->userdash_model->MyHistoryData($payout_condition);

		$reff_comm_condition = "type IN ('commissions')";
		$this->data['total_ref_comm'] = $this->userdash_model->MyHistoryData($reff_comm_condition);

		$reff_condition = "referral_id = '".$session->get('uusersid')."'";
		$this->data['total_sponser'] = $this->userdash_model->MySponserCount($reff_condition);
		
		$withdraw_condition = "history.type IN ('bonus', 'fund_send', 'deposit', 'fund_received')";
		$this->data['transactions'] = $this->userdash_model->Mydashresult($withdraw_condition,'6');

		$condition = "history.type IN ('withdraw_request', 'withdrawal')";
		$this->data['payouts'] = $this->userdash_model->Mydashresult($condition,'6');

		$reff_condition = "referral_id = '".$session->get('uusersid')."' AND status='1'";
		$this->data['active_sponser'] = $this->userdash_model->MySponserCount($reff_condition);
		
		// $this->data['sponser_level'] = $this->downlines($session->get('uusersid'), '0');
		$this->data['sponser_level'] = $this->downlinesmatrix($session->get('uusersid'), '0');


		// $this->data['sponser_level_count'] = $this->downlinecount($session->get('uusersid'), '0');
		$this->data['sponser_level_count'] = $this->downlinecountmatrix($session->get('uusersid'), '0');

        $user = $this->common_model->GetUser($session->get('uusersid'));
        
		if($user)
		$this->data['referral_url'] = base_url().'referral/'.$user->username;

		$referralern_condition ="uusersid = '".$session->get('uusersid')."' AND type in ('commissions')";
		$this->data['referralhis_res'] = $this->common_model->GetResults('history',$referralern_condition);	
		
		$msg_condition = "user LIKE '%".$session->get('uusersid')."%' AND message_status = '1'";
		$this->data['message_data'] = $this->common_model->GetRow('message_controls', $msg_condition);
		// print_r($this->data['message_data']);
		$condition = "status = '1'";
		$this->data['all_active_coin'] = $this->common_model->GetResults('coin_info',$condition);

		$this->data['fuel_amount1'] = $this->db->query("SELECT SUM(amount)as amt from history where type IN('fuel','bonus') AND  status='1' and uusersid ='".$session->get('uusersid')."'")->getRow();
		$this->data['fuel_amount2'] = $this->db->query("SELECT SUM(amount)as amt from history where type = ('penalty') AND  status='1' and uusersid ='".$session->get('uusersid')."'")->getRow();


	$this->data['profit'] = $this->db->query("SELECT SUM(amount) AS amount FROM `history` WHERE `type` IN('commissions','trade_profit') AND uusersid = '".$session->get('uusersid')."'")->getRow();

		$this->data['withdraw'] = $this->db->query("SELECT SUM(amount) as amount from history WHERE uusersid = '".$session->get('uusersid')."' and type IN('withdraw_request','withdraw_fee') ")->getRow();

		// $this->data['balance'] = $this->data['profit']->amount - $this->data['withdraw']->amount;
		$buy_bal = curbalance($session->get('uusersid'));

		$this->data['balance'] = $buy_bal;

		$session= \Config\Services::session();
	 	$uusersid=SESSION('uusersid');    
		$condition = "uusersid ='".$uusersid."'";
		$this->data['user1'] = $this->common_model->GetRow('user_strategy',$condition);
			    
		if(!empty($this->request->getPost('sub')))
		{
			
			$margin_column_limit =$this->request->getPost('replenishment_time');
			$first_buy_amount=$this->request->getPost('first_buy_amount');
			$open_position_doubled=$this->request->getPost('open_position_doubled');
			$whole_profit_ratio=$this->request->getPost('whole_profit_ratio');
			$whole_profit_callback=$this->request->getPost('whole_profit_callback');
			$buyin_callback=$this->request->getPost('buyin_callback');
			$sub_position_callback=$this->request->getPost('sub_position_callback');
			
			$num=$margin_column_limit;
			for($i=0; $i < $num; $i++) 
			{					
				$trade1[$i]=$_POST["call_time".$i.""];
				
				$buyin_ratio_times[$i]=$_POST["order_time".$i.""];
				
			}
				
			if($num >= 5)
			{
				$j=0;
				for ($i=4; $i < $num; $i++) 
				{  
					$sub_positon[$i]=$_POST["rep_time".$j.""];
					$buyin_ratio_times[$i]=$_POST["order_time".$i.""];
					$j++;
				}
						
				$trade2 =array(implode(',',$buyin_ratio_times));
				$trade3 =array(implode(',',$sub_positon));							
			}
			else
			{							
				$trade2 = $buyin_ratio_times;												
			}
			$tade1=implode(',',$trade1);
			$tade2=implode(',',$trade2);
			if($trade3)
			{
			 $tade3=implode(',',$trade3);
			}
			else
			{
			$tade3=0;
			}
			
			$session= \Config\Services::session();
	 		$uusersid=SESSION('uusersid');


			$condition1 = "uusersid ='".$uusersid."'";
			$user=$this->common_model->GetRow('user_strategy',$condition1);
			
			if($user=='')
			{
		 		$trade_data1=array(
		 			"uusersid"				=> $uusersid,
					"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,
			         "sub_position"           => $tade3,
			        "sub_position_callback" =>  $sub_position_callback,
			        "sync_strategy_status"	=>  0
				);

			$query_status = $this->db->table('user_strategy')->insert($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');
			}
			
		}
		else
		{
			$trade_data1=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,
	         "sub_position"           => $tade3,
	        "sub_position_callback" =>  $sub_position_callback,
	        "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');
			}
		}
		}

		if(!empty($this->request->getPost('strategy')))
		{

			$qury = $this->db->query("SELECT * FROM suggested_strategy WHERE id='1' ")->getResult();
		    $qry=$qury[0];
			$margin_column_limit =$qry->margin_column_limit;
			$first_buy_amount=$qry->first_buy_amount;
			$open_position_doubled=$qry->open_position_doubled;
			$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;
			$tade3=$qry->sub_position;

			
			$session= \Config\Services::session();
	 		$uusersid=SESSION('uusersid');

			$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,
		        "sub_position"		    =>	$tade3,
		        "sub_position_callback" =>  $sub_position_callback,
		        "sync_strategy_status"	=> 	0
			);

			$this->db = db_connect();

			$query_status = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($trade_data);
			if($query_status)
			{
				$session = \Config\Services::session();
				$session->setFlashData('success_message', 'Suggested Strategy Successfully Applied');
			}
			else
			{
				$session = \Config\Services::session();
				$session->setFlashData('error_message', 'Failed to apply Suggested Strategy');
			}
			
		}
		
		$buy_bal = curbalance($session->get('uusersid'));

        $this->data['exchange_list'] = $this->db->query('select * from api_exchange_list where status="1"')->getResult();

		$this->data['balance'] = $buy_bal;
		echo view('user/dashboard',$this->data);
	}
	
	public function balance_update()
	{
		$uusersid =$this->request->getPost('uusersid');
		$exchange = $this->request->getPost('exchange');
		$total_asset='0';
		if($exchange=='1')
		{
		    $get_api_bind=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type='1'")->getRow();
		    if($get_api_bind)
		    {
			$key = $get_api_bind->api_key;
			$secret = $get_api_bind->secret_key;
			$balances=binance_balance($key,$secret);
			if($balances)
			{
			    $total_asset=$balances;
			}
			else
			{
			    $total_asset='0';
			}
			
		    }
		}
		else
		{
		    $get_api_bind=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type='5'")->getRow();
		    
		     if($get_api_bind)
            {
              $key = $get_api_bind->api_key;
              $secret = $get_api_bind->secret_key;
              $account = $get_api_bind->account;
              $acc_type = $account == 1 ? 'CONTRACT' : 'UNIFIED';
              $bybitApi = new App\Libraries\BybitApi($key, $secret);
              
              $total_asset = $bybitApi->getBalance('USDT',$acc_type);
            }
		    
		    
		}
		


		echo number_format($total_asset,2);

	}
	
	
	public function asset_update()
	{
		$this->db = db_connect();
		$this->session  = session();
		$uusersid = $this->session->get('uusersid');
		helper('text');
		
		$get_history=$this->db->query("select * from history")->getResult();
		
		/*foreach($get_history as $history)
		{
		    $userinfo1=$this->db->query("select * from uusers where uusersid='".$history->uusersid."'")->getRow();
		    echo "update history set user_group='".$userinfo1->new_entry."' where historyid='".$history->historyid."'";
		    $this->db->query("update history set user_group='".$userinfo1->new_entry."' where historyid='".$history->historyid."'");
		}*/
			
			
		$get_user_address=$this->db->query("select * from pay_address where userid='".$uusersid."' and payment_type='1'")->getRow();
		$userinfo=$this->db->query("select * from uusers where uusersid='".$uusersid."'")->getRow();
	
		if($get_user_address)
		{
		   $contract_address='0x55d398326f99059ff775485246999027b3197955';
			//$data=$this->getTRC20Transactions($get_user_address->address);
			$data=$this->getBEp20Transactions($get_user_address->address);
			
			
			if (isset($data['result']) && is_array($data['result'])) {
			    
			 
			    
            // Display the results
            foreach ($data['result'] as $transaction) {
                
                $txID = $transaction['hash'];
                $from = $transaction['from'];
                $to = $transaction['to'];
                $value = $transaction['value'] / (10 ** 18); // Adjust for token decimals
                $timestamp=date("Y-m-d H:i:s",$transaction['timeStamp']);
                
                
                
                if(strtolower($to)==strtolower($get_user_address->address) && strtolower($transaction['contractAddress'])==strtolower($contract_address))
                {
                    
                    $get_verify=$this->db->query("select * from history where transhash='".$transaction['hash']."'")->getRow();
                    if($get_verify)
                    {
                        
                    }
                    else
                    {
                        $bonus_data = array(
							"uusersid" 		=> $uusersid,
							"currency"      => '17',
							"amount"		=>	$value,
							"type" 			=>  "deposit",
							"description" 	=> "Fund Deposited",
							"date"     		=>  $timestamp,
							"transactionid" => strtoupper(random_string('alnum', 16)),
							"transhash"=>$transaction['hash'],
							"user_group"    => $userinfo->new_entry,
							"status"		=> 1
						);
					
					
						$query_status = $this->db->table('history')->insert($bonus_data);
                    }
                    
                    
                }
               
            }
        } else {
            echo "Failed to retrieve data from TRC20 API.\n";
        }
			
		
			
			
		}
		
	}

	public function getTRC20Transactions($address)
	{

		$url="https://api.trongrid.io/v1/accounts/".$address."/transactions/trc20";
	
		$ch = curl_init();
    	// Set cURL options
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		// Execute cURL request and get the response
		$response = curl_exec($ch);
		// Close cURL session
		curl_close($ch);
		// Decode the JSON response
		$data = json_decode($response, true);
		return $data;
	}
	
	public function  getBEp20Transactions($address)
	{
	    $url="https://api.bscscan.com/api?module=account&action=tokentx&address=$address&startblock=0&endblock=99999999&sort=asc&apikey=GIZWMXXDJG1TCNE824K3EQ3WXNHK979SMP";
	    
	    $ch = curl_init();
    	// Set cURL options
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		// Execute cURL request and get the response
		$response = curl_exec($ch);
		// Close cURL session
		curl_close($ch);
		// Decode the JSON response
		$data = json_decode($response, true);
		return $data;
	    
	}

	public function quantify()
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$this->finance_model = model('finance_model');
	    $this->userdash_model = model('userdash_model');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$required_pairs = ['1INCH','ADA','AAVE','ATOM','ALGO','AION','AVAX','AKRO','ANT','APE','BAT','BTC','BCH','BNB','BTCST','BAKE','BOME','BONK','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','NOT','OMG','ONT','PEPE','QTUM','REEF','RSR','SUN','SHIB','SLP','SOL','SUSHI','SXP','TRX','THETA','TFUEL','UNI','VET','WRX','XRP','XMR','XEM','XLM','XTZ','YFI','YFII','ZEC','ZEN'];
                
		$this->data['required_pairs']=$required_pairs;
		echo view('user/quantify1',$this->data);
	}
	
	public function quantify1()
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$this->finance_model = model('finance_model');
	    $this->userdash_model = model('userdash_model');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$required_pairs = ['1INCH','ADA','AAVE','ATOM','ALGO','AION','AVAX','AKRO','ANT','APE','BAT','BTC','BCH','BNB','BTCST','BAKE','BOME','BONK','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','NOT','OMG','ONT','PEPE','QTUM','REEF','RSR','SUN','SHIB','SLP','SOL','SUSHI','SXP','TRX','THETA','TFUEL','UNI','VET','WRX','XRP','XMR','XEM','XLM','XTZ','YFI','YFII','ZEC','ZEN'];
                
		$this->data['required_pairs']=$required_pairs;
		echo view('user/quantify1',$this->data);
	}
	
	public function websocket()
	{
	    $this->data['pair']='welcome pairs';
	    echo view('user/websocket_pairs',$this->data);
	}


	public function arbit()
	{
		$this->common_model = Model('CommonModel');

		// $condition = "status = '1' and arbit_status='1'";
		// $this->data['all_active_coin'] = $this->common_model->GetResults('coin_info',$condition);
		$condition = "status = '1' and arbit_status='1'";
		$this->data['all_active_coin'] = $this->common_model->GetActiveArbitPlans();
		
		// echo $this->db->last_query();
		// exit();

		// print_r($this->data['all_active_coin']);
		// exit();

		echo view('user/arbit',$this->data);

	}

	public function autoLoad()
	{

	   echo view('user/all_list');

     }
     
     public function tradeLoad()
	{

	echo view('user/trans_list');

	}
    public function favourites_trade()
	{
		$this->db = db_connect();
		$this->common_model = model('CommonModel');
        $symbol =$this->request->getPost('symbl');
        $uusersid =$this->request->getPost('uusersid');
     $condition = "trader_id ='".$symbol."' AND uusersid ='".$uusersid."'";
     $res = $this->common_model->GetRow('favourites_trade',$condition);
        if(empty($res)){
				$datas = array(
				'uusersid' =>$uusersid,
				'trader_id' => $symbol,
				'status'=>1,
				);
			$bulider =$this->db->table('favourites_trade');
			$bulider->insert($datas);
		}
		else{
			$datas = array(
        'status'=>1,
			);
			$bulider = $this->db->table('favourites_trade')->where('trader_id',$symbol)->where('uusersid',$uusersid);
			$bulider->update($datas);
		}
			echo true;
	   }

	public function favourites1_trade()
	{
		 $session= \Config\Services::session();
         $uusersid=$session->get('uusersid');
         $symbol =$this->request->getPost('symbl');
         $this->db = db_connect();
         $datas = array(
        'status'=>0,
			);
         // print_r($datas);
         // die();
			$bulider =$this->db->table('favourites_trade')->where('trader_id',$symbol)->where('uusersid',$uusersid);
			// echo $this->db->getlastQuery();
			// die();
			$bulider->update($datas);
	}

     	public function autoLoad1()
	{

	   echo view('user/operation_list');

     }

    public function autoLoad2()
	{

	   echo view('user/okex_operation_list');

     }


    public function autoLoad3()
	{

	   echo view('user/okex_all_list');

     }

         public function autoLoad4()
	{

	   echo view('user/ftx_all_list');

     }

     public function getPairDetails()
     {

	$session= \Config\Services::session();
	$uusersid =SESSION('uusersid');

$this->data['symbol'] = service('request')->getPost('pair');

if(service('request')->getPost('pair')!="")
{
$this->data['get_active'] = $this->db->query("SELECT * from trade_process where  pair = '".$this->data['symbol']."' and uusersid='".$uusersid."'  ")->getRow();
}
else
{
	$this->data['symbol'] = $uusersid;
	$this->data['get_active'] = $this->db->query("SELECT * from user_strategy where uusersid='".$uusersid."'  ")->getRow();
	
}


         echo view('user/trnModel',$this->data);
     }

	public function first_preset_drop()
	{
	$this->db = db_connect();
	$first_preset_drop = $this->request->getPost('first_preset_drop');
	$symbol = $this->request->getPost('pair');
	$uusersid = $this->request->getPost('uusersid');
 $pair_available = $this->db->table('trade_process')->where('pair', $symbol)->where('uusersid', $uusersid)->where('trade_status !=',2)->orderBy('id','desc')->get()->getRow();
   	$data=array(
	"first_buy_amount" 		=>  $first_preset_drop
	);
	if($pair_available)
	$query_status = $this->db->table('trade_process')->where('pair', $symbol)->where('uusersid', $uusersid)->update($data);
	$query_status = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($data);
	echo "1";
    }



	public function oneshot_limit()
	{
	$session= \Config\Services::session();
	$uusersid=SESSION('uusersid');
	$this->db = db_connect();


	$oneshot_limit = $this->request->getPost('oneshot_limit');
	$symbol = $this->request->getPost('pair');
 
    $id= $symbol;

    if(!is_numeric($id))
    {
   	$data=array(
	"oneshot_limit" 		=>  $oneshot_limit
	);
	$query_status = $this->db->table('trade_process')->where('pair', $id)->update($data);
	echo "success";
    }
    else
    {  
	$data=array(
	"oneshot_limit" 		=>  $oneshot_limit
	);
	$query_status = $this->db->table('user_strategy')->where('uusersid', $uusersid)->update($data);
    }
	}


public function favourites()
	{
		$session= \Config\Services::session();
		$uusersid =SESSION('uusersid');
		$symbol = $this->request->getPost('symbl');


		$data=array(
			"pair" 			=>  $symbol,
			"uusersid"		=>  $uusersid,
			"status"		=>	1
		);

		$this->db = db_connect();

		$condition1 = "pair ='".$symbol."' AND uusersid='".$uusersid."'";
		$user=$this->common_model->GetRow('favourites',$condition1);

		if($user=='')
		{
			$query_status = $this->db->table('favourites')->insert($data);
		}
		else
		{
			$query_status = $this->db->table('favourites')->where('pair', $symbol)->update($data);
		}
	}
	public function favourites1()
	{
		$session= \Config\Services::session();
		$uusersid =SESSION('uusersid');
		$symbol = service('request')->getPost('symbl');


		$data=array(
			"pair" 			=>  $symbol,
			"uusersid"		=>  $uusersid,
			"status"		=>	0
		);

		$this->db = db_connect();

		$condition1 = "pair ='".$symbol."' AND uusersid='".$uusersid."'";
			$user=$this->common_model->GetRow('favourites',$condition1);

		if($user=='')
		{
			$query_status = $this->db->table('favourites')->insert($data);
		}
		else
		{
			$query_status = $this->db->table('favourites')->where('pair', $symbol)->update($data);
		}
	}


	public function buylist()
	{
		$this->common_model = Model('CommonModel');

		$condition = "status = '1' and arbit_status='1'";
		$this->data['all_active_coin'] = $this->common_model->GetResults('coin_info',$condition);
		echo view('user/buyback',$this->data);

	}

	public function arbit_add($id="")
	{
		$this->db = db_connect();
		$this->uri = service('uri');
		$id=$this->uri->getSegment(2);

		$myencrypt = new MyEncrypt;
	    //$id = $myencrypt->decode($id);
	    $this->data['buy_bal'] = $buy_bal;
	    $this->data['id'] = $id;
	    $cond = "id = '".$id."'";
		$coin = $this->common_model->GetRow('arbit_plans',$cond);


		if(!empty($this->request->getPost('amt')))
		{
			

			$condition = "coid = '".$this->request->getPost('coid')."'";
			$coin_det = $this->common_model->GetRow('coin_info',$condition);

			$conditions = "uusersid = '".$session->get('uusersid')."'";
			$userdet = $this->common_model->GetRow('uusers',$conditions);


			$now=date("Y-m-d H:i:s");
			$duration=$coin->duration;
			$mature= date('Y-m-d H:i:s', strtotime($now. ' + '.$duration.' days'));

			
			$trans = 'ART'.rand(0,9999999);
			$history_data = array(
	                        "uusersid" 			=> $session->get('uusersid'),
	                        "coin_id"    		=> $this->request->getPost('coid'),
	                        "plan_id"    		=> $this->request->getPost('id'),
	                        "amount" 			=> $this->request->getPost('amt'),
	                        "invest_date"   	=> date("Y-m-d H:i:s"),
	                        "mature_date"   	=> $mature,
	                        "first_date"   	=> $mature,
	                        "status"			=> '1',
	                        "transaction_id" 	=> $trans
	                        );

			$query_status = $this->db->table('arbit_fund')->insert($history_data);  


			$find_plans=$this->db->query("select * from arbit_plans where id='".$id."'")->row();
			if($find_plans)
			{
				$prelunch_status=$find_plans->freelance_bonus_status;
				$direct_status=$find_plans->direct_bonus_status;
				$level_status=$find_plans->level_comm_status;
				$prelunch=$find_plans->freelance_bonus_perc;
				$direct=$find_plans->direct_bonus_perc;
				$level=$find_plans->commission;

				if($prelunch_status=='1')
				{

					$pre_amount=$this->request->getPost('amt')*$prelunch/100;
					if($pre_amount>0)
					{
						$trid = strtoupper(random_string('alnum', 16));
						$userdata1=array(
						"uusersid"=>$session->get('uusersid'),
						"amount"=>$pre_amount,
						"type"=>'commissions',
						"transactionid" => $trid,
						"description"=>'Prelaunch Bonus Earned',
						"date"=>date("Y-m-d H:i:s"),
						"currency"=>$this->request->getPost('coid'),
						);
						$this->db->table('history')->insert($userdata1);
						
					}

				}


				if($direct_status=='1')
				{

					$dir_amount=$this->request->getPost('amt')*$direct/100;
					if($dir_amount>0)
					{
						$trid = strtoupper(random_string('alnum', 16));
						$userdata1=array(
						"uusersid"=>$userdet->referral_id,
						"amount"=>$dir_amount,
						"type"=>'commissions',
						"transactionid" => $trid,
						"description"=>'Direct commission Earned From Arbit Invest - '.$userdet->username,
						"date"=>date("Y-m-d H:i:s"),
						"currency"=>$this->request->getPost('coid'),
						);
						$this->db->table('history')->insert($userdata1);
						
					}

				}

				if($level_status=='1')
				{

					$conditions = "uusersid = '".$userdet->referral_id."'";
					$userdet = $this->common_model->GetRow('uusers',$conditions);
					if($userdet)
					{
						$amount=$this->request->getPost('amt');
						$coid=$this->request->getPost('coid');
						$this->levelcommission($userdet->referral_id,$amount,$level,0,$coid);
					}



				}
			}



			$session->setFlashData('success_message', 'Arbitrage Successfully Added');
			return redirect()->to('arbit');
			
		}
		else
		{
			
			$condition = "id = '".$id."'";

			
			$this->data['coin'] = $this->common_model->GetRow('arbit_plans',$condition);
			// echo $this->db->last_query();
			// //$this->data['coid']=$coid;
			// print_r($this->data['coin']);
			// exit();
			echo view('user/arbit_payment',$this->data);
		}
	}


	public function levelcommission($sponser,$amount,$levels,$level,$coid)
	{
		$this->db = db_connect();
		$this->common_model = model('CommonModel');
		if($sponser>0)
		{
			$level_split=explode("-",$levels);
			$level_com=$amount*$level_split[$level]/100;
			$level=$level+1;
			if($level_com>0)
			{
				$conditions = "uusersid = '".$session->get('uusersid')."'";
				$userdet = $this->common_model->GetRow('uusers',$conditions);
				$trid = strtoupper(random_string('alnum', 16));
				$userdata1=array(
				"uusersid"=>$sponser,
				"amount"=>$level_com,
				"type"=>'commissions',
				"transactionid" => $trid,
				"description"=>'Level '.$level.' commission Earned From Arbit Invest - '.$userdet->username,
				"date"=>date("Y-m-d H:i:s"),
				"currency"=>$coid,
				);
				$this->db->table('history')->insert($userdata1);

			}

			$conditions = "uusersid = '".$sponser."'";
			$userdet = $this->common_model->GetRow('uusers',$conditions);
			if($userdet->referral_id)
			{
				$this->levelcommission($userdet->referral_id,$amount,$levels,$level,$coid);
			}

		
		}

	}
	public function openorder()
	{

		echo view('user/open');

	}

	public function myorder()
	{
		echo view('user/myorder');		
	}

	public function torder()
	{
		echo view('user/trades');
	}

	public function trans()
	{
		echo view('user/trans');
	}


	public function arbit_close($id='')
	{
		$this->db = db_connect();
		$id = basename($_SERVER['REQUEST_URI']);
		$condition = "id = '".$id."'";
		$arbit_det = $this->common_model->GetRow('arbit_fund',$condition);
		$coin=$arbit_det->coin_id;
		$condition = "coid = '".$coin."'";
		$coin_det = $this->common_model->GetRow('coin_info',$condition);
		$ret=$coin_det->ret_balance;
		$this->db->query("update arbit_fund set status='3' where id='".$arbit_det->id."'");
		if($ret=='1')
		{
			$next_due_date=date("Y-m-d H:i:s");

			$desc="Relesed ArbitRage Investment";
			$trans = 'REL'.rand(0,9999999);	
			$insert_data=array("uusersid" => $arbit_det->uusersid,"amount" => $arbit_det->amount, "type" => 'return_principal',"description" => $desc, "date" => $next_due_date,  "transactionid" => $trans, "depositid" => $arbit_det->id, "currency" =>$arbit_det->coin_id);
			$this->db->table("history")->insert($insert_data);
			
		}
		$session->setFlashData('success_message', 'Arbitrage Earnings Successfully Closed');
		return redirect()->to('arbit');
	}


	public function request_raise($id='')
	{
        $this->db = db_connect();
		$id = basename($_SERVER['REQUEST_URI']);
		$this->db->query("update exchange set status='2' where cid='".$id."'");
		$session->setFlashData('success_message', 'Buyback Reuest Successfully sent');
		return redirect()->to('buylist');

	}


	public function coin($id='')	
	{
		$this->common_model = model('CommonModel');
		$session = session();
		$this->db = db_connect();
		$coin_name = basename($_SERVER['REQUEST_URI']);
		if($coin_name=="")
		{
			return redirect()->to('dashboard');
		}
		else
		{
			$myencrypt = new MyEncrypt;
			$coinid = $myencrypt->decode($coin_name);
			$condition = "coid ='".$coinid."'";
			$cointable = $this->common_model->GetRow('coin_info',$condition);
			

			$this->data['coin_det']=$cointable;
			$pay_status=$cointable->pay_status;

			if($pay_status=='1')
			{



				$payment = $cointable->coid;	
				
				$payment_data = $this->common_model->GetPayment($payment);
				
				// echo $this->db->last_query();
				// exit();

				foreach ($payment_data as $row)
				{
					$form_data[$row->payment_key] = $row->payment_value;
				}

				if($coinid < 6)
				{
					
					if($cointable->pay_mode=='1')
					{
						if($form_data['pay_mode']=='block')
						{
							$condition  =  "uuserid = '".$session->get('uusersid')."' and coin_id='".$coinid."' and status='1' and payment_id='1'";
							$getaddress =  $this->common_model->GetRow('deposit_address',$condition);
							
							if(!$getaddress)
							{
								$main_url="https://api.blockcypher.com/";
								if($coinid=='1')
									$path = 'v1/btc/main/addrs?token='.$form_data['api_key'];
								else if($coinid=='3')
									$path = 'v1/ltc/main/addrs?token='.$form_data['api_key'];
								else if($coinid=='4')
									$path = 'v1/dash/main/addrs?token='.$form_data['api_key'];
								else if($coinid=='5')
									$path = 'v1/doge/main/addrs?token='.$form_data['api_key'];
								else
									$path = 'v1/eth/main/addrs?token='.$form_data['api_key'];

								$headers = array('Content-Type: application/x-www-form-urlencoded');
								$ch = curl_init();
								curl_setopt($ch, CURLOPT_URL,$main_url.$path);
								curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Ignore Verify SSL Certificate
								curl_setopt_array($ch, array(
								CURLOPT_POST => TRUE,
								CURLOPT_RETURNTRANSFER => TRUE,
								CURLOPT_HTTPHEADER => $headers
								));
								$output = curl_exec($ch);
								curl_close($ch);
								$result = json_decode($output,true);

								$getaddress=$result['address'];
								$private=$result['private'];
								$public=$result['public'];
								$user=$session->get('uusersid');
								$query_status =  $this->db->query("insert into deposit_address(btc_address,amount,status,uuserid,typ,coin_id,payment_id,public_key,private_key)values('$getaddress','0','1','$user','1','".$coinid."','1','$public','$private')");
								if($query_status)
		                        {
								$condition  =  "uuserid = '".$session->get('uusersid')."' and coin_id='".$coinid."' and payment_id='1' and status='1'";
								$getaddress =  $this->common_model->GetRow('deposit_address',$condition);
									$this->data['address'] = $getaddress->btc_address;
									$this->data['coind'] = $getaddress->coin_id;
									$this->data['coinname'] = $cointable->coin_name;
									$this->data['coinsymbol'] = $cointable->coin_symbol;
									$this->data['coinconfirm'] = $form_data['number_of_confirmation'];
								}
							}
							else
							{


								$condition  = "uuserid = '".$session->get('uusersid')."' and coin_id='".$coinid."' and payment_id='1' and status='1'";
								$getaddress =  $this->common_model->GetRow('deposit_address',$condition);
								$this->data['address'] = $getaddress->btc_address;
								$this->data['coind'] = $getaddress->coin_id;
								$this->data['coinname'] = $cointable->coin_name;
								$this->data['coinsymbol'] = $cointable->coin_symbol;
								$this->data['coinconfirm'] = $form_data['number_of_confirmation'];
							}
						}
						else
						{
							$condition  =  "uuserid = '".$session->get('uusersid')."' and coin_id='".$coinid."' and payment_id='1' and status='2'";
							$getaddress =  $this->common_model->GetRow('btc_addresses',$condition);
							if($getaddress)
							{
								$this->data['address'] = $getaddress->payment_value;
								$this->data['coind'] = $getaddress->coin_id;
								$this->data['coinname'] = $cointable->coin_name;
								$this->data['coinsymbol'] = $cointable->coin_symbol;
								$this->data['coinconfirm'] = $form_data['number_of_confirmation'];
							}
							else
							{
								$update = array(
									"uuserid" => $session->get('uusersid'),
									"coin_id" => $coinid,
									"status" =>'2'
									);
								$condition = "uuserid ='0' and coin_id ='0' and status='1' and payment_id='1' order by pid asc limit 1";
								$this->db->where($condition);
								$query_status =  $this->db->update('btc_addresses',$update);
								if($query_status)
								{
									$condition  =  "uuserid = '".$session->get('uusersid')."' and coin_id='".$coinid."' and payment_id='1' and status='2'";
									$getaddress =  $this->common_model->GetRow('btc_addresses',$condition);
									$this->data['address'] = $getaddress->payment_value;
									$this->data['coind'] = $getaddress->coin_id;
									$this->data['coinname'] = $cointable->coin_name;
									$this->data['coinsymbol'] = $cointable->coin_symbol;
									$this->data['coinconfirm'] = $form_data['number_of_confirmation'];
								}					
					
							}

						}
					}
					else
					{
						$payment ='7';														
						$payment_data = $this->common_model->GetPayment($payment);
						foreach ($payment_data as $row)
						{
							$form_data[$row->payment_key] = $row->payment_value;
						}

						$this->data['address'] = $getaddress->btc_address;
						$this->data['coind'] = $getaddress->coin_id;
						$this->data['coinname'] = $cointable->coin_name;
						$this->data['coinsymbol'] = $cointable->coin_symbol;
						$this->data['coinconfirm'] = $form_data['number_of_confirmation'];
					}
				}
			}
			else if($pay_status=='2')
			{
				


				$payment ='2';														
				$payment_data = $this->common_model->GetPayment($payment);
				
				// echo $this->db->last_query();
				// exit();

				foreach ($payment_data as $row)
				{
					$form_data[$row->payment_key] = $row->payment_value;
				}

				if($form_data['pay_mode']=='BTC')
				{
					

					$condition  =  "uuserid = '".$session->get('uusersid')."' and coin_id='".$coinid."' and status='1' and payment_id='2'";
					$getaddress =  $this->common_model->GetRow('deposit_address',$condition);

					if(!$getaddress)
					{
						$main_url="https://api.blockcypher.com/";
						$path = 'v1/eth/main/addrs?token='.$form_data['api_key'];
						$headers = array('Content-Type: application/x-www-form-urlencoded');
						$ch = curl_init();
						curl_setopt($ch, CURLOPT_URL,$main_url.$path);
						curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Ignore Verify SSL Certificate
						curl_setopt_array($ch, array(
						CURLOPT_POST => TRUE,
						CURLOPT_RETURNTRANSFER => TRUE,
						CURLOPT_HTTPHEADER => $headers
						));
						$output = curl_exec($ch);
						curl_close($ch);
						$result = json_decode($output,true);
						$getaddress=$result['address'];
						$private=$result['private'];
						$public=$result['public'];
						$user=$session->get('uusersid');
						$query_status =  $this->db->query("insert into deposit_address(btc_address,amount,status,uuserid,typ,coin_id,payment_id,public_key,private_key)values('$getaddress','0','1','$user','1','".$coinid."','2','$public','$private')");
						if($query_status)
                        {


							$condition  =  "uuserid = '".$session->get('uusersid')."' and coin_id='".$coinid."' and payment_id='2' and status='1'";
							$getaddress =  $this->common_model->GetRow('deposit_address',$condition);
							$this->data['address'] = $getaddress->btc_address;
							$this->data['coind'] = $getaddress->coin_id;
							$this->data['coinname'] = $cointable->coin_name;
							$this->data['coinsymbol'] = $cointable->coin_symbol;
							$this->data['coinconfirm'] = $form_data['number_of_confirmation'];
						}
					}
					else
					{
						

						$condition  = "uuserid = '".$session->get('uusersid')."' and coin_id='".$coinid."' and payment_id='2' and status='1'";
						$getaddress =  $this->common_model->GetRow('deposit_address',$condition);
						$this->data['address'] = $getaddress->btc_address;
						$this->data['coind'] = $getaddress->coin_id;
						$this->data['coinname'] = $cointable->coin_name;
						$this->data['coinsymbol'] = $cointable->coin_symbol;
						$this->data['coinconfirm'] = $form_data['number_of_confirmation'];
						
					}
				}
				else
				{
					



					$condition  =  "uuserid = '".$session->get('uusersid')."' and coin_id='".$coinid."' and payment_id='2' and status='2'";
					$getaddress =  $this->common_model->GetRow('btc_addresses',$condition);
					if($getaddress)
					{


						$this->data['address'] = $getaddress->payment_value;
						$this->data['coind'] = $getaddress->coin_id;
						$this->data['coinname'] = $cointable->coin_name;
						$this->data['coinsymbol'] = $cointable->coin_symbol;
						$this->data['coinconfirm'] = $form_data['number_of_confirmation'];
					}
					else
					{
						



						$update = array(
								"uuserid" => $session->get('uusersid'),
								"coin_id" => $coinid,
								"status" =>'2'
								);
							$condition = "uuserid ='0' and coin_id ='0' and status='1' and payment_id='2' order by pid asc limit 1";
							$this->db->where($condition);
							$query_status =  $this->db->update('btc_addresses',$update);
							


							if($query_status)
							{
								


								$condition  =  "uuserid = '".$session->get('uusersid')."' and coin_id='".$coinid."' and payment_id='2' and status='2'";
								$getaddress =  $this->common_model->GetRow('btc_addresses',$condition);
								
								// echo $this->db->last_query();
								// exit();

								$this->data['address'] = $getaddress->payment_value;
								$this->data['coind'] = $getaddress->coin_id;
								$this->data['coinname'] = $cointable->coin_name;
								$this->data['coinsymbol'] = $cointable->coin_symbol;
								$this->data['coinconfirm'] = $form_data['number_of_confirmation'];
							}					
					
					}

				}

			}
			else if($pay_status=='3')
			{

					if($cointable->pay_mode=='3')
					{
						$payment ='6';														
						$payment_data = $this->common_model->GetPayment($payment);
						foreach ($payment_data as $row)
						{
							$form_data[$row->payment_key] = $row->payment_value;
						}
					}

					if($cointable->pay_mode=='5')
					{
						$payment ='7';														
						$payment_data = $this->common_model->GetPayment($payment);
						foreach ($payment_data as $row)
						{
							$form_data[$row->payment_key] = $row->payment_value;
						}

					}
					if($cointable->pay_mode=='6')
					{
						$payment ='8';														
						$payment_data = $this->common_model->GetPayment($payment);
						foreach ($payment_data as $row)
						{
							$form_data[$row->payment_key] = $row->payment_value;
						}
					}
					$this->data['address'] = $getaddress->btc_address;
					$this->data['coind'] = $getaddress->coin_id;
					$this->data['coinname'] = $cointable->coin_name;
					$this->data['coinsymbol'] = $cointable->coin_symbol;
					$this->data['coinconfirm'] = $form_data['number_of_confirmation'];

			}

			$condition = "uusersid ='".$session->get('uusersid')."' and currency ='".$coinid."' order by depositid desc limit 10";	
			$this->data['all_active'] = $this->common_model->GetResults('deposit',$condition);
			echo view('user/payment',$this->data);			
		}
	}

	public function payment()
	{
		
		if($this->request->getPost())
		{
			$amount=$this->request->getPost('amount');
			$coinid=$this->request->getPost('coinid');
			$session->set('cid',$coinid);
			$session->set('amt',$amount);
			$condition = "coid ='".$coinid."'";
			$cointable = $this->common_model->GetRow('coin_info',$condition);
				



			$dates=date("Y-m-d H:i:s");

			$pay_mode=$cointable->pay_mode;

			if($cointable->pay_mode=='3')
				$payment_id='6';
			else if($cointable->pay_mode=='5')
				$payment_id='7';
			else if($cointable->pay_mode=='2')
				$payment_id='7';
			if($cointable->pay_mode=='6')
				$payment_id='8';

			$form_data['coinid']=$coinid;
			$form_data['symbol']=strtoupper($cointable->coin_symbol);
			$form_data['pay_mode']=$payment_id;


			$payment_data = $this->common_model->GetPayment($payment_id);
			
			// echo $this->db->last_query();
			// exit();

			foreach ($payment_data as $row) {
						$form_data[$row->payment_key] = $row->payment_value;
						$form_data[$row->payment_key] = $row->payment_value;
						$payment_name=$row->payment_name;
			}


			$form_data['action'] = base_url().'user/deposit/success';
			$form_data['success_url'] = base_url().'user/deposit/success';
			$form_data['cancel_url'] = base_url().'user/deposit/cancel';

			if($payment_id=='7')
				$form_data['ipn_url'] = base_url().'ipn/payment/bitcoin';
			else
				$form_data['ipn_url'] = base_url().'ipn/payment/'.$payment_name;

			
			// print_r($form_data);
			// exit();

			$this->data['form_payment'] = $form_data;
			
			


			$userid=$session->get('uusersid');

			$this->db->query("insert into deposit set uusersid='$userid',payment_id='$payment_id',pay_mode='$pay_mode',amount='$amount',btc_amount='$amount',coin_id='".$coinid."',currency='".$coinid."',transhash='0', confirmation='0',description='deposit',status='pending',invest_date='$dates'");
            $lastuserid = $this->db->insert_id();
            $session->set('depid',$lastuserid);
            echo view('user/paymentconfirm', $this->data);	
		}
		else
		{
			return redirect()->to('dashboard');
		}

	}

	public function bank()
	{

		$amount=$this->request->getPost('amount');
		$bank=$this->request->getPost('bank');
		$trans_id=$this->request->getPost('trans_id');
		$coinid=$this->request->getPost('coinid');
		$session->set('cid',$coinid);
		$session->set('amt',$amount);
		$session->set('bid',$bank);
		$session->set('trans_id',$trans_id);
		$condition = "coid ='".$coinid."'";
		$cointable = $this->common_model->GetRow('coin_info',$condition);
		$dates=date("Y-m-d H:i:s");
		$condition="id ='".$bank."'";
		$this->data['bank_det']=$this->common_model->GetRow('bankwire',$condition);
		echo view('user/bankconfirm', $this->data);	
	}



	public function nonlive()
	{

		$amount=$this->request->getPost('amount');
		$trans_id=$this->request->getPost('trans_id');
		$coinid=$this->request->getPost('coinid');
		$session->set('cid',$coinid);
		$session->set('amt',$amount);
		$condition = "coid ='".$coinid."'";
		$cointable = $this->common_model->GetRow('coin_info',$condition);
		$dates=date("Y-m-d H:i:s");
		$coins_per=$cointable->coins_per * $amount;
		$userid=$session->get('uusersid');
		$this->db->query("insert into deposit set uusersid='$userid',payment_id='0',pay_mode='0',amount='$coins_per',btc_amount='$coins_per',pay_amount='$amount',coin_id='".$coinid."',currency='".$coinid."',transhash='0', confirmation='0',description='deposit',status='pending',invest_date='$dates',ac_mode='2'");
		$depositid = $this->db->insert_id();
        $trid = "TRAN".strtoupper(uniqid());
                        $history_data = array(
                                "uusersid" 		=> $userid,
                                "amount"    	=>  $coins_per,
                                "btc_amount" 	=> $coins_per,
                                "type"   		=>  "deposit_req",
                                "description"	 => 'deposit made',
                                "date"     		=>  date("Y-m-d H:i:s"),
                                "payment_id"    =>  '0',
                                "transactionid" => $trid,
                                "depositid" 	=>  $depositid,
                                "currency"		=> $coinid,
                                "referance_id"	=> $trans_id,
                                "ac_mode"		=> '2'
                        );
         $query_status = $this->db->insert('history',$history_data);  
		$session->setFlashData('success_message', 'Deposit Request Sent to Admin verification. Pls wait until confirmation');
		return redirect()->to('dashboard');

		}


	public function bank_det($id='')
	{
		$this->common_model = Model('CommonModel');
		$id=$this->request->getPost('id');
		$condition="id ='".$id."'";
		$this->data['bank_det']=$this->common_model->GetRow('bankwire',$condition);
		echo view('user/bankdet',$this->data);
	}

	public function bankconfirm()
	{
		$this->db = db_connect();
		$this->common_model = Model('CommonModel');
        $session = session();
		$coinid=$session->get('cid');
		$amount=$session->get('amt');
		$bank=$session->get('bid');
		$trans_id=$session->get('trans_id');
		$userid=$session->get('uusersid');
		$condition = "coid ='".$coinid."'";
		$cointable = $this->common_model->GetRow('coin_info',$condition);
		$dates=date("Y-m-d H:i:s");
        $this->db->query("insert into deposit set uusersid='$userid',payment_id='$bank',pay_mode='$bank',amount='$amount',btc_amount='$amount',coin_id='".$coinid."',currency='".$coinid."',transhash='0', confirmation='0',description='deposit',status='pending',invest_date='$dates',ac_mode='2'");

        $depositid = $this->db->insertID();
        $trid = "TRAN".strtoupper(uniqid());
                        $history_data = array(
                                "uusersid" 		=> $userid,
                                "amount"    	=>  $amount,
                                "btc_amount" 	=> $amount,
                                "type"   		=>  "deposit_req",
                                "description"	 => 'deposit made',
                                "date"     		=>  date("Y-m-d H:i:s"),
                                "payment_id"    =>  '1',
                                "transactionid" => $trid,
                                "depositid" 	=>  $depositid,
                                "currency"		=> $coinid,
                                "referance_id"	=> $trans_id,
                                "ac_mode"		=> '2'
                        );
                        $query_status = $this->db->insert('history',$history_data);  
			$session->setFlashData('success_message', 'Deposit Request Sent to Admin verification. Pls wait until confirmation');
		return redirect()->to('dashboard');
	}



	public function downlines($uusersid,$level)
	{
		static $array = array();
		$condition = "referral_id = '".$uusersid."' AND status='1'";	
		$select_count = $this->userdash_model->MySponserCount($condition);
		$select = $this->userdash_model->MySponsersLevel($condition);
		if($select_count > 0)
		{
			$level++;
			for($i=0; $i<$select_count; $i++)
			{
				$uusersid = $select[$i]->uusersid;
				$array[$level][$i]['level'] = $level;
				$array[$level][$i]['uusersid'] = $uusersid;
				$array[$level][$i]['ref_user'] = $select[$i]->fullname;

				$deposit_condition = "uusersid ='".$uusersid."' AND type IN ('deposit', 'reinvest', 'deposit_req')";
				$deposit_amount = $this->userdash_model->MylevelHistoryData($deposit_condition);
				$array[$level][$i]['deposit'] = $deposit_amount;
				// $array[$level] = $uusersid.',';
				$this->downlines($uusersid,$level);
			}
		}
		return $array;
	}

	public function downlinesmatrix($uusersid,$level)
	{
		static $array = array();

		$condition = "uusers_matrix.spillover_id = '".$uusersid."'";
		$select = $this->userdash_model->MySponsersLevelmatrix($condition);
		$level++;

		if($select) {

			foreach ($select as $row) {
				$uusersid = $row->uusersid;
				$deposit_condition = "uusersid ='".$uusersid."' AND type IN ('deposit', 'reinvest', 'deposit_req')";
				$deposit_amount = $this->userdash_model->MylevelHistoryData($deposit_condition);

				$lvlarray = array(
					'level' => $level,
					'uusersid' => $uusersid,
					'ref_user' => $row->fullname,
					'deposit' => $deposit_amount,
					$level => $uusersid.','
				);

				array_push($array, $lvlarray);
				
				$this->downlinesmatrix($uusersid,$level);
			}
		}
		
		return $array;
	}

	public function downlinecount($uusersid,$level)
	{
		static $array = array();

		$condition = "referral_id = '".$uusersid."' AND status='1'";
		
		$select_count = $this->userdash_model->MySponserCount($condition);
		$select = $this->userdash_model->MySponsersLevel($condition);
		
		if($select_count > 0)
		{
			$level++;
			
			for($i=0; $i<$select_count; $i++)
			{
				$uusersid = $select[$i]->uusersid;
				$array[$level]['level'] = $level;
				$array[$level]['count'] = $select_count;
				
				$this->downlinecount($uusersid,$level);
			}
		}
		
		return $array;
	}

	

	public function downlinecountmatrix($uusersid,$level)
	{
		static $array = array();

		$condition = "spillover_id = '".$uusersid."'";
		$select = $this->userdash_model->MySponsersLevelmatrix($condition);
		// echo "<br/>".$this->db->last_query();

		// $select_count = count($select);
		
		if($select)
		{
			$level++;
			$count=0;;
			foreach ($select as $row) {
				$uusersid = $row->uusersid;

				$condition1 = "uusersid = '".$uusersid."'";
				$count = $this->common_model->RecordCount('uusers_matrix', $condition1);
				if(isset($count)){
					// echo "<br/>".$this->db->last_query();
					$array[$level]['level'] = $level;
					if(!empty($array[$level]['count']))
						$array[$level]['count']+= $count;
					// $array['count'] += $count;
				}

				$this->downlinecountmatrix($uusersid,$level);
			}

			
			
		}
		// echo "<pre>";
		// print_r($array);
		// echo "</pre>";
		return $array;
	}


	public function deposit()
	{

		echo view('user/deposits');

	}


	public function withdraw()
	{
		echo view('user/withdraws');

	}

	private function check_balance() {
		$session =session();
		$earnings_type  = "'deposit'";
        $expenses_type  = "'token'";
		$uusersid = $session->get('uusersid');
		// calculate user earnings 
        $condition = "uusersid = '".$uusersid."' AND type IN (".$earnings_type.")";
        $earnings = $this->common_model->GetEarnings('history',$condition);

        // calculate user expenses
        $condition1 = "uusersid = '".$uusersid."' AND type IN (".$expenses_type.")";
        $expenses = $this->common_model->GetEarnings('history',$condition1);

        $Earnings = ($earnings->earnamt) ? $earnings->earnamt : '0';
        $Expenses = ($expenses->earnamt) ? $expenses->earnamt : '0';
        $AvailableBalance = $Earnings - $Expenses;
        
        return ($AvailableBalance) ? $AvailableBalance : '0';
	}

	private function sendCURL($url)
    {
        $response = '';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        curl_close($ch);
        $response1 = json_decode($response);
        return $response1;
    }

	public function refresh()
	{

		$key = $this->request->getPost('key');
		$secret = $this->request->getPost('secret');
		$total_asset=0;
		$api = new Binance\API($key,$secret);
		$ticker='';
		$balances = $api->balances($ticker);     

		if($balances)
			$total_asset = $balances['USDT']['available'];
		else
			$total_asset='0';

		echo $total_asset;
	}

     
	public function changeSession($id)
	{ 
     
		$session = \Config\Services::session();
		$session->remove('exchange');
        // Regenerate the session ID
        $session->set('exchange',$id);

        // Optionally destroy old session data
        // $session->destroy();

        // Optionally redirect or perform other actions
        return redirect()->to('/user/dashboard');
	}

}