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


class Circle 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');
		if(!$session->get('user_login')) 
		{
			return redirect()->to('login');
		}
		$status = site_info('site_status');
		if($status!='on')
		{
			return redirect()->to('offline');
		} 

		// user login only
		if($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 index()
	{
	$this->db = db_connect();
	helper('site_helper');
	$this->common_model = model('CommonModel');
	$session = \Config\Services::session();
	if(!$session->get('uusersid'))
	throw new \CodeIgniter\Router\Exceptions\RedirectException('login');
	$this->data['user'] = $this->common_model->GetUser($session->get('uusersid'));
	$user_balance = $this->check_balance();
	$this->data['fuel_amount'] = $this->db->query("SELECT SUM(amount)as amt from history where type ='fuel' AND status='0' and uusersid ='".$session->get('uusersid')."'")->getRow();

		$buy_bal = curbalance($session->get('uusersid'));
		$this->data['balance'] = $buy_bal; 
		// if($user_balance < 0) {
		// 	$this->data['balance'] = 0;	
		// } else {
		// 	$this->data['balance'] = $user_balance;	
		// }

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

	public function circle_list(){

		$session = \Config\Services::session();
		if(!($session->get('user_login') || $session->get('admin_login')))
		{			
			return redirect()->to('login');
		}
		echo view('user/circle_list');

	}
public function promotion_list(){


		echo view('user/promotion_list');


}



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

	public function circle_registration(){
         $session = session();
		if(!$session->get('uusersid'))
			throw new \CodeIgniter\Router\Exceptions\RedirectException('login');

		$get_active = ['1INCHUSDT','ADAUSDT','AAVEUSDT','ATOMUSDT','AKROUSDT','ANTUSDT','BATUSDT','BTCUSDT','BCHUSDT','BNBUSDT','BTCSTUSDT','CRVUSDT','COMPUSDT','CAKEUSDT','COSUSDT','DOGEUSDT','DASHUSDT','DOTUSDT','ETHUSDT','EOSUSDT','ETCUSDT','FTTUSDT','FILUSDT','GRTUSDT','IOTAUSDT','IOSTUSDT','JSTUSDT','KAVAUSDT','LTCUSDT','LINKUSDT','LITUSDT','MANAUSDT','MDXUSDT','NEOUSDT','OMGUSDT','ONTUSDT','REEFUSDT','RSRUSDT','SUNUSDT','SUSHIUSDT','SXPUSDT','TRXUSDT','THETAUSDT','UNIUSDT','XRPUSDT','XMRUSDT','XEMUSDT','XTZUSDT','YFIUSDT','YFIIUSDT','ZECUSDT','ZENUSDT'];
	   
	
		$data['get_active'] = $get_active;

					
		    echo view('user/circle_registration',$data);
	}

	public function pair_select(){
		$get_active = ['1INCHUSDT','ADAUSDT','AAVEUSDT','ATOMUSDT','AKROUSDT','ANTUSDT','BATUSDT','BTCUSDT','BCHUSDT','BNBUSDT','BTCSTUSDT','CRVUSDT','COMPUSDT','CAKEUSDT','COSUSDT','DOGEUSDT','DASHUSDT','DOTUSDT','ETHUSDT','EOSUSDT','ETCUSDT','FTTUSDT','FILUSDT','GRTUSDT','IOTAUSDT','IOSTUSDT','JSTUSDT','KAVAUSDT','LTCUSDT','LINKUSDT','LITUSDT','MANAUSDT','MDXUSDT','NEOUSDT','OMGUSDT','ONTUSDT','REEFUSDT','RSRUSDT','SUNUSDT','SUSHIUSDT','SXPUSDT','TRXUSDT','THETAUSDT','UNIUSDT','XRPUSDT','XMRUSDT','XEMUSDT','XTZUSDT','YFIUSDT','YFIIUSDT','ZECUSDT','ZENUSDT'];
		foreach ($get_active as $key => $value) {
			echo "<option value='".$value.'">"'.$value.'"</option>"';

		}
	}


public function circle_delete($id) {
		$this->session = session();
		$this->db = db_connect();
		$myencrypt = new MyEncrypt;
		
		
		
		
			$delete_status = $this->db->table('trader')->where('id',$id)->delete();

			if($delete_status) {
				$this->session->setFlashData('success_message', lang('language_lang.subadmin_delete_success_message'));
				return redirect()->to('circle_list');
			} else {
				$this->session->setFlashData('error_message', lang('language_lang.subadmin_delete_error_message'));
				return redirect()->to('circle_list');
			}	
			
		} 
	
public function promotion_delete($id) {
		$this->session = session();
		$this->db = db_connect();
		$myencrypt = new MyEncrypt;
		
		
		
		
			$delete_status = $this->db->table('promotion')->where('id',$id)->delete();

			if($delete_status) {
				$this->session->setFlashData('success_message', lang('language_lang.promotion_delete_success_message'));
				return redirect()->to('promotion_list');
			} else {
				$this->session->setFlashData('error_message', lang('language_lang.promotion_delete_error_message'));
				return redirect()->to('promotion_list');
			}	
			
		} 
		public function tickets(){

			$this->session = session();
	        if(!$this->session->get('uusersid'))
			  throw new \CodeIgniter\Router\Exceptions\RedirectException('login');
			$this->db = db_connect();

		    if($this->request->getPost()) {

  
            $validation =  \Config\Services::validation();

            $validation->setRules([
				'subject' => ['label' => lang("language_lang.contact_Your_name"), 'rules' => 'trim|required'],
				'message' => ['label' => lang("language_lang.contact_email_address"), 'rules' => 'trim|required'],
				'contact_mail' => ['label' => lang("language_lang.contact_subject"), 'rules' => 'trim|required'],
				'contact_no' => ['label' => lang("language_lang.contact_message"), 'rules' => 'trim|required'],
			]);

			// $this->form_validation->set_rules('g-recaptcha-response', 'g-recaptcha-response', 'required|captcha_check');

	        if ($validation->withRequest($this->request)->run() == TRUE) {

	        	       if(isset($_FILES['image']['tmp_name']) && $_FILES['image']['size'] > 0) 
            {
              // img path
					$uploads_dir = './uploads/tickets';

					//img get name 
					$tmp_name = $_FILES["image"]["tmp_name"];
				
				//set name
			         $name = basename($_FILES['image']['name']);
                      
                   //get file
			         $img = $this->request->getFile('image');

			       
                   
                   //uplode file
                     $img->move('./uploads/tickets', $name);    


				
			}
	             	$userdata = array(
						"uusers_id"	=>	$this->request->getPost('uusersid'),
	                    "contact_no"	    =>	$this->request->getPost('contact_no'), 						
						"contact_mail"	=>	$this->request->getPost('contact_mail'),
						"subject"	=>	$this->request->getPost('subject'),
						"message"	=>	$this->request->getPost('message'),
						"ticket_status"	=>	'new',
						"image"	=>	$name,
						"post_date"	=>	date('Y-m-d H:i:s'),
						"ip_address"	=>	$this->request->getIpAddress(),
						"status"	=>	'1'
						
					);
					$query_status = $this->db->table('tickets')->insert($userdata);
					$user = $this->common_model->GetUser($this->session->get('uusersid'));
					$subject = 'Ticket';
					$mailid = '14';
					$mail_subject_data = $this->common_model->getMailTemplate($mailid);
					$message  = str_replace('[FIRSTNAME]', $user->fullname, $mail_subject_data->message);
					$message  = str_replace('#ticketno', $ticketno, $message);
					$message  = str_replace('#subject', $this->request->getPost('subject'), $message);
					$message  = str_replace('#status', 'new', $message);
					$message  = str_replace('#content', $this->request->getPost('message'), $message);
					$message  = str_replace('#sitename', site_info_lang('site_name',$this->session->get('langid')), $message);

					if($mail_subject_data->status=='1'){

					$mail_status = $this->sendmail($user->email, $user->fullname, $subject, $message,$mail_subject_data->from_mail);

					}

					if($query_status){
						$this->session->setFlashData('success_message', 'Ticket queued Successfully. Please wait for admin reply');
				        return redirect()->to('tickets');
					}else{
						$this->session->setFlashData('error_message', 'Ticket Queue Failed!!!');
				return redirect()->to('circle_list');
					}
            }
        }

		    echo view('user/ticket');
	}

public function promotion_add(){

	   $this->session = session();
		
		$this->db = db_connect();
		$session = \Config\Services::session();


       
  if($this->request->getPost()) {

// print_r($this->request->getPost());
// die();


	       if(isset($_FILES['profile']['tmp_name']) && $_FILES['profile']['size'] > 0) 
            {
              // img path
            	$config['upload_path'] = WRITEPATH .'/uploads/promotion';
					$uploads_dir = './uploads/promotion';

					//img get name 
					$tmp_name = $_FILES["profile"]["tmp_name"];
				
				//set name
			         $name = basename($_FILES['profile']['name']);
                      
                   //get file
			         $img = $this->request->getFile('profile');


                   
                   //uplode file
                     $img->move('./uploads/promotion', $name);


              if($img){
			        
							$data['profile'] = $name;
							
			        }
			        

}
$last_id = $this->request->getPost('id');
$query_status=$this->db->query("SELECT * from promotion WHERE id='$last_id'")->getRow();


if($name=="")
 {

$name=$query_status->profile;

  }
if(isset($_FILES['profile1']['tmp_name']) && $_FILES['profile1']['size'] > 0) 
            {
              // img 
            	    $config['upload_path'] = WRITEPATH .'/uploads/promotion';
					$uploads_dir = './uploads/promotion';

					//img get name 
					$tmp_name = $_FILES["profile1"]["tmp_name"];
				
				//set name
			         $name1 = basename($_FILES['profile1']['name']);
                      
                   //get file
			         $img1 = $this->request->getFile('profile1');


                   
                   //uplode file
                     $img1->move('./uploads/promotion', $name1);


              if($img1){
			        
							$data['profile1'] = $name1;
							
			        }
			      

}
 $last_id = $this->request->getPost('id');
$query_status=$this->db->query("SELECT * from promotion WHERE id='$last_id'")->getRow();


if($name1=="")
    {
	
	$name1=$query_status->profile1;
			      
    }   

                    $trader_data = array(
						

                       "uusersid"     =>  $this->session->get('uusersid'),


				        "title"	         =>	$this->request->getPost('title'),


                        "trader_id"  =>$this->request->getPost('trade_name'),

				        "description"=>$this->request->getPost('description'),

				       "profile" =>$name,
				       "profile1" =>$name1,
				       "status" => 0
						
					);
				
				
						 
                  $this->db = db_connect();
            	if($this->request->getPost('id')){
				

  $query_status = $this->db->table('promotion')->where('id',$last_id)->update($trader_data);

 

 // $query_status=$this->db->query("UPDATE promotion SET profile='".$name."',  profile1='".$name1."'  WHERE id='".$last_id."' and uusersid = '".$this->session->get('uusersid')."'");



// echo $this->db->getLastQuery();
// die();


}else{
$query_status = $this->db->table('promotion')->insert($trader_data);

}
  


              
		if($query_status)
			{
				
			$session->setFlashData('success_message', lang('language_lang.user_success_message'));

				return	redirect()->to('promotion_list');
			}
			else
			{
				$session->setFlashData('error_message', lang('language_lang.user_error_message'));
                    if($this->request->getPost('id'))

					 return redirect()->to('promotion_edit/'.$this->request->getPost('$id'));

			}
		

}    

	echo view('user/promotion');


}

public function promotion_edit($id){




   $this->data['qry'] = $this->db->query('SELECT * from promotion where id = "'.$id.'"')->getRow();
	  // echo $this->db->getLastQuery();
	  // die();
	$this->data['id'] = $id;
	echo view('user/promotion',$this->data);


}

	public function sendmail($useremail, $fullname, $subject, $message,$from_mail="") {
        $session = session();
		// $this->load->library('My_PHPMailer');
		$condition = "settings_name = 'email'";
		$email_setting_data = $this->common_model->GetSettingall_lang($condition);

		foreach ($email_setting_data as $row) {
			$mail_data[$row->site_key] = $row->site_value;
		}

		if($mail_data['email_throw']=='php')
		{
			$mail = new PHPMailer();
	        $mail->isMail();

		} else {

			$mail = new PHPMailer();
	        $mail->IsSMTP(); 
	        $mail->SMTPAuth   = TRUE; 
	        $mail->SMTPSecure = $mail_data['smtp_type'];  
	        $mail->Host       = $mail_data['smtp_hostname'];      
	        $mail->Port       = $mail_data['smtp_portno'];                   
	        $mail->Username   = $mail_data['smtp_username'];  
	        $mail->Password   = $mail_data['smtp_password'];   
		}
		         
        $mail->SetFrom($from_mail, site_info_lang('site_name',$session->get('langid')));  
        $mail->AddReplyTo($from_mail,site_info_lang('site_name',$session->get('langid')));

        $message  = str_replace('#adminemail', $from_mail, $message);

        $mail->Subject    = $subject;
        $mail->msgHTML($message);
        
        $mail->AddAddress($useremail, $fullname);
        
        if(!$mail->Send()) {
        	// return $mail->ErrorInfo;
        	return false;
        } else {
            return true;
        }
	}

	public function circle_edit($id){

	$this->data['get_active'] = ['1INCHUSDT','ADAUSDT','AAVEUSDT','ATOMUSDT','AKROUSDT','ANTUSDT','BATUSDT','BTCUSDT','BCHUSDT','BNBUSDT','BTCSTUSDT','CRVUSDT','COMPUSDT','CAKEUSDT','COSUSDT','DOGEUSDT','DASHUSDT','DOTUSDT','ETHUSDT','EOSUSDT','ETCUSDT','FTTUSDT','FILUSDT','GRTUSDT','IOTAUSDT','IOSTUSDT','JSTUSDT','KAVAUSDT','LTCUSDT','LINKUSDT','LITUSDT','MANAUSDT','MDXUSDT','NEOUSDT','OMGUSDT','ONTUSDT','REEFUSDT','RSRUSDT','SUNUSDT','SUSHIUSDT','SXPUSDT','TRXUSDT','THETAUSDT','UNIUSDT','XRPUSDT','XMRUSDT','XEMUSDT','XTZUSDT','YFIUSDT','YFIIUSDT','ZECUSDT','ZENUSDT'];

	$this->data['qry'] = $this->db->query('SELECT * from trader where id = "'.$id.'"')->getRow();
	 // echo $this->db->getLastQuery();
	  // die();
	$this->data['id'] = $id;
	echo view('user/circle_registration',$this->data);

	}


	public function circle_add(){
		// print_r('fhsdfh');
		//  die();
		$this->session = session();
		$session = session();
		$this->db = db_connect();

		if($this->request->getPost())
		{
			  // print_r($this->request->getPost());
			  // die();
			$profit = $this->request->getPost('profit');
			$admin_fee = $this->request->getPost('admin_fee');
			$first_buy_amount = $this->request->getPost('first_buy_amount');       
          	$margin_column_limit = $this->request->getPost('margin_column_limit');
            $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');
            $stratgy = $this->request->getPost('stratgy');


			$this->form_validation = \Config\Services::validation();
		
			$this->form_validation->setRules([

	 'profit' => [
				'label' => 'Profit', 
				 'rules' => 'trim|required|numeric'
				 ],
			
    //         'coin_id' => [
    //             'label' => 'List Coins', 
    //              'rules' => 'trim|required'
    //         ],
           
            'description' => [
                 'label' => 'Description', 
                  'rules' => 'trim|required'
              ],
    //          'stratgy' => [
    //              'label' => 'Strategy Name', 
    //              'rules' => 'trim|required'
    //         ],
    //          'trade_mode' => [
    //              'label' => 'Trade Name', 
    //              'rules' => 'trim|required'
    //         ],
    //          'first_buy_amount' => [
    //              'label' => 'First Buy in Amount', 
    //             'rules' => 'trim|required|numeric'
    //          ],
            
    //          'margin_column_limit' => [
    //              'label' => 'Margin column limit', 
    //              'rules' => 'trim|required|numeric'
    //          ],
    //          'whole_profit_ratio' => [
    //             'label' => 'Whole poistion take profit ratio', 
    //              'rules' => 'trim|required|numeric'
    //          ],
    //          'whole_profit_callback' => [
    //             'label' => 'Whole poistion take profit callback', 
    //              'rules' => 'trim|required|numeric'
    //         ],
    //          'buyin_callback' => [
    //              'label' => 'Buy in callback', 
    //              'rules' => 'trim|required|numeric'
    //         ],
            'trade_image' => [
			  		'label' => 'Trade Image',
					 'rules' => 'trim|trim|ext_in[trade_image,jpg,png,gif,jpeg]|is_image[trade_image]'
			 ],
		  //    'address' => [
    //             'label' => 'Address', 
    //              'rules' => 'trim|required'
    //       ],

			]);

			 // if($margin_column_limit >= 5)
			//  {
			// 	$validation->setRules([
			//  	'sub_position_callback'	=> [
			//  		'label' => 'Sub-position take-profit callback',
			//  		'rules' =>'trim|required|numeric'
		 // 	  ]
			 
			//  ]);

	  // }
		
   
			if ($this->form_validation->withRequest($this->request)->run())
            {
            	 // print_r('hi');
            	 // die();
            	
            	// $logo = $_FILES['trade_image']['name'];
            	
            	
            if(isset($_FILES['trade_image']['tmp_name']) && $_FILES['trade_image']['size'] > 0) 
            {
            
            	    $config['upload_path'] = WRITEPATH .'/public/uploads/trader';
					$uploads_dir = './public/uploads/trader';

					//img get name 
					$tmp_name = $_FILES["trade_image"]["tmp_name"];

				//set name
			         $name = basename($_FILES['trade_image']['name']);
                  //get file
			         $img = $this->request->getFile('trade_image');
// print_r($img);
// die();                   
                   //uplode file
                     $img->move('./public/uploads/trader', $name);    


             if($img){
			        	//delete existing file
			   //         if(isset($site_data['profile_pic'])){
						// 	unlink('./uploads/trader/',$site_data['trade_image']);
						// }
						 //$sitedata = array(
							$data['trade_image'] = $name;
							//"profile_pic"=>$name
						 //);
						
			        }

              }
      
			$num=$this->request->getPost('replenishment_time');
			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;
			}

				$trade = array(
					"trade_mode"	   		=>  $this->request->getPost('trade_mode'),
					"uusersid"              =>  $this->session->get('uusersid'),
               "coin_id" => str_replace(" ","",$this->request->getPost('stacked')),
            		"profit"		   		=>  $this->request->getPost('profit'),
            		"description" 	   		=>  $this->request->getPost('description'),
	            	"margin_column_limit" 	=>  $this->request->getPost('replenishment_time'),
	            	"strategy_mode" =>  $this->request->getPost('strategy_mode'),
	            	"sub_position_callback" =>  $this->request->getPost('sub_position_callback'),
	            	"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'),
	            	"margincall_drop"		=> 	$tade1,
			        "buyin_ratio_times"		=>	$tade2,
		            "sub_position"           => $tade3,
	            	"status"	            =>  0	
				);

            	$this->db = db_connect();
            	if($this->request->getPost('id')){
				$last_id = $this->request->getPost('id');
				$query_status1 = $this->db->table('trader')->where('id',$last_id)->update($trade);
		
            	}
            	else{
				$query_status1 = $this->db->table('trader')->insert($trade);
				$last_id = $this->db->insertID();
            	}


			$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');


            $coin_id = str_replace(" ", "", $this->request->getPost('stacked'));
			$sub_position_callback=$this->request->getPost('sub_position_callback');
			
			$num=$this->request->getPost('replenishment_time');
			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;
			}

$query_status=$this->db->query("UPDATE trader SET margincall_drop='".$tade1."',buyin_ratio_times='".$tade2."',sub_position='".$tade3."' WHERE id='".$last_id."' and uusersid = '".$this->session->get('uusersid')."'");

if($name != "")
$query_status1=$this->db->query("UPDATE trader SET trade_image='".$name."' WHERE id='".$last_id."' and uusersid = '".$this->session->get('uusersid')."'");
			if($query_status)
			{
			$session->setFlashData('success_message', 'Trader Successfully updated his circle form. Please wait for admin confirmation');
				return redirect()->to('circle_list');
			}
			else
			{
				$session->setFlashData('error_message', 'Trader failed to update');
				if($this->request->getPost('id'))
					return redirect()->to('circle_edit/'.$this->request->getPost('id'));
		        else
				    return redirect()->to('circle_registration');
			}
	}
	else{
		 return redirect()->to(site_url('circle_registration'))->withInput()->with('error', $this->validator);
	   }
   }
}

	public function user_view($id='')
	{
		
        $this->db = db_connect();
		helper('site_helper');
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$this->data['user'] = $this->common_model->GetUser($session->get('uusersid'));
		$user_balance = $this->check_balance();
		$this->data['fuel_amount'] = $this->db->query("SELECT SUM(amount)as amt from history where type ='fuel' AND  status='0' and uusersid ='".$session->get('uusersid')."'")->getRow();

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

		$condition = "id ='".$id."'";
			
		$this->data['up_id'] = $this->common_model->GetRow('trader',$condition);
     
     echo view('user/user_view',$this->data);

}

public function currency_block_list()
{

  $session= \Config\Services::session();
  $uusersid=$this->request->getPost('uusersid');
  $id=$this->request->getPost('id');
  $datas = array(
         "currency_block_list" =>implode(",",$this->request->getPost('stacked')),
			);


 $this->db=db_connect();
$builder=$this->db->table('user_strategy')->where('uusersid',$uusersid)->update($datas);

// $bulider->update($datas);
    echo 1;
	}

public function currency_edits($id='')
{

  $session= \Config\Services::session();
  $uusersid=$session->get('uusersid');
         

 $datas = array(
         "coin_id" =>implode(",",$this->request->getPost('coin_id')),
			);


 $this->db=db_connect();
$builder=$this->db->table('user_strategy')->where('uusersid',$uusersid)->update($datas);

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

public function strategy_payment_cancel($id='')
	{
		// print_r($this->request->getPost());
		// die();

		$session= \Config\Services::session();
         $uusersid=$session->get('uusersid');

         $datas = array(
        'activation'=>0,
			);
			$bulider =$this->db->table('trader_activation')->where('trader_id',$id)->where('uusersid',$uusersid);
			$bulider->update($datas);
			
			return redirect()->to('user/circle');
		}
// 		public function strategy_payment_exit(){


// $this->session = session();
// 		$this->db = db_connect();
// 		$myencrypt = new MyEncrypt;
		
		
		
		
// 			$delete_status = $this->db->table('trader_activation')->where('uusersid',$uuserid)->where('trader_id'->$trader_id)AND activat->delete();

// 			if($delete_status) {
// 				$this->session->setFlashData('success_message', lang('language_lang.subadmin_delete_success_message'));
// 				return redirect()->to('circle/strategy_payment');
// 			} else {
// 				$this->session->setFlashData('error_message', lang('language_lang.subadmin_delete_error_message'));
// 				return redirect()->to('circle/strategy_payment');
// 			}	
			
// 		} 
	

	public function strategy_payment($id='')
	{
		// print_r($this->request->getPost());
		// die();

		$session= \Config\Services::session();
        $uusersid=$session->get('uusersid');
		$condition = "trader_id ='".$id."' AND uusersid ='".$uusersid."'";		
			
	 //$this->data['up_id'] = $this->common_model->GetRow('trader_activation',$condition);
	 $mod=$this->common_model->GetRow('trader_activation',$condition);		


		//  $amount=$mod->amount;
		
		// $qry=$this->db->query("SELECT * FROM  payment_controls WHERE payment_name='bitcoin' && payment_key='btc_address' ")->getResult();

		// $res=$qry[0];
		// $btc=$res->payment_value;
		// $pay_nme=$res->payment_name;

		// $coin_name ='BTC';
		// $condition = "payment_name ='".$pay_nme."'";
		// $cointable = $this->common_model->GetRow('payment_controls',$condition);
		
		// $qry1=$this->db->query("SELECT * FROM  payment_controls WHERE payment_name='bitcoin' && payment_key='api_key' ")->getResult();
		// $res1=$qry1[0];
		// foreach ($cointable as $row)
		// {
		// 	$form_data[$row->payment_key] = $row->payment_value;
		// }
		// $apikey = $res1->payment_value;


		// $main_url="https://api.blockcypher.com/";
		// $path = 'v1/btc/main/addrs?token='.$apikey;
		// $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);

		// $getaddress1=$result['address'];
		// $private=$result['private'];
		// $public=$result['public'];
		// $this->db = db_connect();	
		// $confirm = $this->db->query("SELECT * FROM  trader_activation WHERE trader_id=$id ")->getResult();
		// $conf=$confirm[0];
		// if($conf->btc_address!='' && $conf->private_key!='')
		// {

		// }
		// else
		// {
		// 	if($conf->type=='')
		// 	{
		// $amount = "";
		// $private = "";
		// $public = "";
		// $getaddress1 = "";
		// 		$query_status =  $this->db->query("INSERT INTO trader_activation(trader_id,amount,type,depositid,private_key,public_key,btc_address,activation)VALUES('$id','$amount','strategy','','$private','$public','$getaddress1','1')");
				// echo $this->db->getLastQuery();
				// die();
		// 	}
		// 	if($conf->type!='' && $conf->btc_address=='')
		// 	{
		// 		$query_status = $this->db->query("UPDATE trader_activation SET private_key='$private',public_key='$public',btc_address='$getaddress1' where trader_id='".$id."'");
		// 	}
		// }
		
		// $condition2 = "trader_id ='".$id."'";		
			
		// $this->data['updata'] = $this->common_model->GetRow('trader_activation',$condition2);
             
  //            $id=$_SESSION["uusersid"];
		// 	$deposit_data['amount'] = $this->data['up_id']->amount;
		// 	$deposit_data['payment_id'] = 9;
		// 	$payment_id=9;

		// 	$payment_data = $this->common_model->GetPayment($payment_id);
		// 	foreach ($payment_data as $row) {
		// 	$form_data[$row->payment_key] = $row->payment_value;
		// 	$form_data[$row->payment_key] = $row->payment_value;
		// 	}

		// 	$payment_name = $payment_data[0]->payment_name;
		// 	$payment_id = $payment_data[0]->payment_id;


		// 	$form_data['payment_name'] = $payment_name;
		// 	$form_data['payment_id'] = $payment_id;
		// 	$form_deposit['amount'] = $this->data['up_id']->amount;


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

		// 	if($deposit_data['amount']!=0)
		// 	{
       if(empty($mod)){
			$datas = array(
			'uusersid' =>$uusersid,
			'trader_id' => $id,
			'activation'=>1,
			);


			$bulider =$this->db->table('trader_activation');
			$bulider->insert($datas);
		}
		else{
			$datas = array(
        'activation'=>1,
			);
			$bulider =$this->db->table('trader_activation')->where('trader_id',$id)->where('uusersid',$uusersid);
			$bulider->update($datas);
		     }
		     
			
			

			  // echo $this->db->getLastQuery();
			  // die();

			// }


		 return redirect()->to('user/mycircle');

	}
		

}