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

class Finance extends BaseController {

	/**
	* 
	* Start 
	* Create Date: 26 July, 2016
	* This controller to manage for deposit.
	* Created saravanan.
	* @see http://zhyip.com/
	* Last Updated: 26 July, 2016
	* End
	* 
	*/

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

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

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

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

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

	}

	// 
	private function isCookie($values) {

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

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

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

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

	private function isSubadmin() {
		$session = session();
		if($session->get('user_type') == 'subadmin') {
			$controller = $this->router->controllerName().'/'.$this->router->methodName();
			// $method = $this->router->fetch_method();
			$pages = json_decode($session->get('permission'));
		
			if(!in_array(ucfirst($controller), $pages)) {
				return redirect()->to('admin');
			}
		}
	}

	public function index()
	{

		return redirect()->to('admin');
	}

	public function deposit($id='')
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		if($id)
		{
			$myencrypt = new MyEncrypt;
			$id_val = $myencrypt->decode($id);
			$condition = "uusersid =".$id_val;
			$this->data['member_name'] = $this->common_model->GetRow('uusers',$condition);
			$useridval = $this->common_model->GetRow('uusers',$condition);
			$this->data['flag']=1;
		}
		else
		{
			$this->data['flag']=0;
		}

		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);

		$this->data['page_title'] = lang('language_lang.deposit_page_title');

		$this->data['module_name'] = 'finance';
		$this->data['uusers_list'] = $this->common_model->GetResults('uusers');
  
		// $condition = "status = '1'";
		// $this->data['packages'] = $this->common_model->GetResults('package',$condition);
		$this->data['action'] =  'admin/finance/deposit';

		$condition = "status = '1'";
		$this->data['all_active_coin'] = $this->common_model->GetResults('coin_info',$condition);		

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

			// form validation
			$this->form_validation->set_rules('select_coin', lang("language_lang.lbl_select_coin"), 'trim|required');
		 	$this->form_validation->set_rules('description', lang("language_lang.description"), 'trim|required');
         	$this->form_validation->set_rules('amount', lang("language_lang.amount"), 'trim|required');
         	if($this->request->getPost('select_user')){
         	    $this->form_validation->set_rules('select_user',lang("language_lang.lbl_select_user"),'required');
            } 
         	$this->form_validation->set_rules('select_plan',lang("language_lang.lbl_select_plan"),'required'); 
         	// $this->form_validation->set_rules('payment',lang("language_lang.lbl_payment"),'required');             
                
            if ($this->form_validation->run() == TRUE) {

            	
            	
            	$invest_date = date("Y-m-d H:i:s", strtotime($this->request->getPost('deposit_date')));
            	
            	if($this->request->getPost('select_user')){
            		$user_id = $this->request->getPost('select_user');
            	}
            	else {
            		$myencrypt = new MyEncrypt;
			        $user_id = $myencrypt->decode($this->request->getPost('user1'));
            	}

            	$condition = "status = '1' and coid = '".$this->request->getPost('select_coin')."'";
				$coin_det = $this->common_model->GetRow('coin_info',$condition);	
				$pay_amt = $this->request->getPost('amount');
                $orignal_amt = $pay_amt;        	

	            $deposit_data = array(
					"uusersid" => $user_id,
					"amount"	=>	$this->request->getPost('amount'),
					"btc_amount"	=> $orignal_amt,
					"payment_id"	=>'0',
					"compound"	=>	$this->request->getPost('amount'),
					"currency"	=> $this->request->getPost('select_coin'),
					"status"   =>  "active",
					"description" => $this->request->getPost('description'),
					"invest_date"     =>  $invest_date,
					// "mature_date" => $mature_date,
					// "run_date"     =>  $next_run_date
				);

				$query_status = $this->db->insert('deposit',$deposit_data);
				$depositid = $this->db->insert_id();

                $source = $this->request->getPost('deposit_date');
                $date = new DateTime($source);
                $deposit_date = $date->format('Y-m-d');
	            
	            $trid = strtoupper(random_string('alnum', 16));
				$history_data = array(
					"uusersid" => $user_id,
					"amount"	=>	$this->request->getPost('amount'),
					"btc_amount"	=> $orignal_amt,
					"type"   =>  "deposit",
					"description" => $this->request->getPost('description'),
					"date"     =>  date("Y-m-d h:i:s", strtotime($deposit_date)),
					"transactionid" => $trid,
					"depositid"	=>	$depositid,
					"payment_id"	=>'0',
					"currency"	=> $this->request->getPost('select_coin')
				);
				
				$query_status = $this->db->insert('history',$history_data);
				
				/*$this->load->library('Commission');
				$comm = new commission();
				$this->commission->Commission_calc($user_id,$depositid);
				$deposits = $this->common_model->successDeposit($depositid);*/


				$user = $this->common_model->GetUser($user_id);
				// $deposits->package_name

				$amount = $this->request->getPost('amount');

				// sent mail to user
				$subject = 'Investment Information';
				$mailid = '5';
				$mail_subject_data = $this->common_model->getMailTemplate($mailid);

				$message  = str_replace('[FIRSTNAME]', $user->fullname, $mail_subject_data->message);
				$message  = str_replace('[AMT]', $amount, $message);
				$message  = str_replace('[PLAN]', $deposits->package_name, $message);
				$message  = str_replace('[PAYMENT]', 'Bankwire', $message);
				$message  = str_replace('[transid]', $trid, $message);
				$message  = str_replace('#verfyurl', base_url(), $message);
				$message  = str_replace('#adminemill', $mail_subject_data->from_mail, $message);
				$message  = str_replace('#sitename', $headers['site_name'], $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) {
					$session = \Config\Services::session();
					$session->setFlashData('success_message', lang('language_lang.deposit_success_message'));
					return redirect()->to('admin/history/deposit');
				} else {
					$session = \Config\Services::session();
					$session->setFlashData('error_message', lang('language_lang.deposit_error_message'));
					return redirect()->to('admin/finance/deposit');
				}
           	}
		}
		echo view('admin/finance/make_deposit',$this->data);
	}


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

		$myencrypt = new MyEncrypt;
		$historyid = $myencrypt->decode($id);       
        $condition = "cid = '".$historyid."'";
		$deposit_data = $this->common_model->GetRow('currency_pair',$condition);
		$market = $deposit_data->mark_curr;	
		$curr = $deposit_data->curid;	

		$condition = "market_type = '".$market."' and pair = '".$curr."' and status !='4'";
		$data = $this->common_model->RecordCount('exchange',$condition);

		if($data=="")
		{
			$delete_depositstatus = $this->db->query("delete from currency_pair where cid = '".$historyid."'");
			$session = \Config\Services::session();
			$session->setFlashData('success_message', lang('language_lang.market_default_success'));
			return redirect()->to('admin/finance/currencypairlist');
		}
		else
		{
			$session = \Config\Services::session();
			$session->setFlashData('error_message', lang('language_lang.market_default_error'));
			return redirect()->to('admin/finance/currencypairlist');
		}
	}

	
	public function paircurrency($id='')
	{

		$this->db = db_connect();
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$session = session();
		$this->form_validation = \Config\Services::validation();
		if($id)	
		{
			$myencrypt = new MyEncrypt;
			$id_val = $myencrypt->decode($id);
			$condition = "cid =".$id_val;
			$this->data['getpair'] = $this->common_model->GetRow('currency_pair',$condition);
			$this->data['id'] = $id;
			$this->data['cid'] = $id_val;
		}
		
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);

		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);

		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);

		$this->data['page_title'] = lang('language_lang.deposit_page_title');
		$this->data['module_name'] = 'finance';

		$condition = "market_currency ='1' and market_status ='1'";		
		$this->data['market_currency'] = $this->common_model->GetResults('coin_info',$condition);
  		$condition = "status ='1'";		
		$this->data['unmarket_currency'] = $this->common_model->GetResults('coin_info',$condition);
		$this->data['action'] =  'admin/finance/paircurrency';
		if($this->request->getPost())
		{
         $this->form_validation->setRule('select_payer',lang("language_lang.select_payer"),'required');
           if($this->request->getPost('ijd')=="")
         	{
	            $this->form_validation->setRule('select_receiver',lang("language_lang.select_pair"),'required'); 
	        }    

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

            	if($this->request->getPost('ijd')=="")
            	{
            		
	            	foreach($this->request->getPost('select_receiver') as $key => $value)
    	        	{

    	        		if($this->request->getPost('select_payer')!=$value)
    	        		{
    	        			$pairarr = array(
            				"curid" => $value,
            				"mark_curr" => $this->request->getPost('select_payer'),
            				"status" => '1'
            				);
            				$query_status = $this->db->table('currency_pair')->insert($pairarr);
            			}
            		}

            		if($query_status)
	            	{
						$session = \Config\Services::session();
						$session->setFlashData('success_message', lang('language_lang.add_currency_pair_success'));
						return redirect()->to('admin/finance/currencypairlist');
					}
					else
					{
					   $session = \Config\Services::session();
					   $session->setFlashData('error_message', lang('language_lang.add_currency_pair_failure'));
					   return redirect()->to('admin/finance/currencypairlist');
					}            		
            	}
            	else
            	{  
            		$myencrypt = new MyEncrypt;
					$id_val = $myencrypt->decode($this->request->getPost('ijd'));
						
					$pairarr = array(
            			"mark_curr" => $this->request->getPost('select_payer')
            		);

            		$query_status = $this->db->table('currency_pair')->where("cid = '".$id_val."'")->update($pairarr);

            		$recid 	= $this->request->getPost('recid');
            		$sendid = $this->request->getPost('select_payer');

                    $condition1 = "curid ='".$recid."' AND market_id ='".$sendid."'";
                    $row =$this->common_model->GetRow('currency_market',$condition1);
                        


            		/*$row='0';*/

            		if($row=='')
            		{
            		$pairarr1 = array(
            		"curid" => $recid,
            		"market_id" => $sendid,
            		"price" => $this->request->getPost('price'),
            		"price_usd" => $this->request->getPost('price_usd'),
            		"date" => date('Y-m-d H:i:s')
            		);
            		$query_status1 = $this->db->table('currency_market')->insert($pairarr1);	
            		}
            		else
            		{
            		$pairarr1 = array(
            		"curid" => $this->request->getPost('recid'),
            		"market_id" => $this->request->getPost('select_payer'),
            		"price" => $this->request->getPost('price'),
            		"price_usd" => $this->request->getPost('price_usd'),
            		"date" => date('Y-m-d H:i:s')
            		);
            		$query_status1 = $this->db->table('currency_market')->update($pairarr1);
             /*	echo $this->db->last_query();
                exit;  
             */
            		}
            		if($query_status)
            		{
						$session = \Config\Services::session();
						$session->setFlashData('success_message', lang('language_lang.edit_currency_pair_success'));
						return redirect()->to('admin/finance/currencypairlist');
					}
					else
					{
				   		$session = \Config\Services::session();
				   		$session->setFlashData('error_message', lang('language_lang.edit_currency_pair_failure'));
				   		return redirect()->to('admin/finance/currencypairlist');
					}            		            		

            	}	
           	}
		}
		echo view('admin/finance/paircurrency',$this->data);
	}

	
 

	public function edit_trader($id='')
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$myid=$id;
		if(isset($id))
		{
			$myencrypt = new MyEncrypt;
			$id = $myencrypt->decode($id);	
		}

		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);

		$this->data['page_title'] = lang('language_lang.deposit_page_title');
		$this->data['module_name'] = 'finance';
		$condition = "id ='".$id."'";
		$condition1 = "market_currency ='1' and market_status ='1'";
		$this->common_model = model('CommonModel');			
		$this->data['market_currency'] = $this->common_model->GetResults('coin_info',$condition1);		
		$this->data['up_id'] = $this->common_model->GetRow('trader',$condition);
		$condition = "status ='1'";		
		$this->data['trader'] = $this->common_model->GetResults('trader',$condition);
		$this->data['action'] =  base_url().'/admin/finance/edit_trader/'.$myid;
		$condition = "id ='".$id."'";
		$imag = $this->common_model->GetRow('trader',$condition);
		$name=$imag->trade_image;

		if($this->request->getPost())
		{
			$id=$this->request->getPost('id');
			$trade_date = $this->request->getPost('deposit_date');

			$validation =  \Config\Services::validation();
		
			
			$num1 =$this->request->getPost('margin_column_limit');
			
			for($i=0; $i < $num1; $i++) 
				{
					$validation->setRules([
					    'margincall_drop'.$i.'' => [
							'label' => 'Margincall Drop', 
							'rules' => 'trim|required|numeric'
							],
						'buyin_ratio_times'.$i.'' => [
						    'label' => 'Margin Buyin Ratio ', 
						    'rules' => 'trim|required|numeric'
						    ]
						]);
				}
							
			if($num >= 5)
			{
				for ($i=4; $i < $num1; $i++) 
				{ 
					$validation->setRule([ 
						'buyin_ratio_times1'.$i.'' => [
					        'label' => 'buyin_ratio_times1'.$i.'', 
					        'rules' => 'trim|required|numeric'
				        ]
				    ]);						
				}
			}

			
		if ($validation->withRequest($this->request)->run() == TRUE)
        {
            
			
            	$logo =$_FILES["trade_image"]["tmp_name"];
           if($logo!='')
           {	
	            if(isset($_FILES['trade_image']['tmp_name']) && $_FILES['trade_image']['size'] > 0) 
	            {

                  // img path
					$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');
                   
                   //uplode file
                     $img->move('./uploads/trader', $name);                 
			        
				}
			}
			else
			{
				$name=$imag->trade_image;

			}
				

				$num =$this->request->getPost('margin_column_limit');
				if($num!=0)
				{
					for($i=0; $i < $num; $i++) 
					{					
						$trade1[$i]=$_POST["margincall_drop".$i.""];
						if($trade1[$i]=='' && $trade1[$i]==0)
						{
							$this->db = db_connect();
							$session = session();
							$session->setFlashData('error_message','margin Call Drop Field Values missing');
								
							return redirect()->to('admin/finance/edit_trader/'.$myid);
						}

						$buyin_ratio_times[$i]=$_POST["buyin_ratio_times".$i.""];
						if($buyin_ratio_times[$i]=='' && $buyin_ratio_times[$i]==0)
						{
							$this->db = db_connect();
							$session = session();
							$session->setFlashData('error_message','Buyin Ratio Times Field Values missing');
								
							return redirect()->to('admin/finance/edit_trader/'.$myid);
						}
					}
						
					if($num >= 5)
					{
						$sub_position_callback=$this->request->getPost('sub_position_callback');
						if($sub_position_callback=='' && $sub_position_callback==0)
						{
							$session->setFlashData('error_message','Sub position callback value is missing');
							return redirect()->to('admin/finance/edit_trader/'.$myid);
						}
						for ($i=4; $i < $num; $i++) 
						{  
							$buyin_ratio_times1[$i]=$_POST["buyin_ratio_times1".$i.""];
							if($buyin_ratio_times1[$i]=='' && $buyin_ratio_times1[$i]==0)
						{
							$this->db = db_connect();
							$session = session();
							$session->setFlashData('error_message','Buyin Ratio Times Field Values missing');
								
							return redirect()->to('admin/finance/edit_trader/'.$myid);
						}
						}
						
						$trade2 =array(implode(',',$buyin_ratio_times),implode(',',$buyin_ratio_times1));						
					}
					else
					{							
						$trade2 = $buyin_ratio_times;												
					}
											
				}

				$tade1=implode(',',$trade1);
				$tade2=implode(',',$trade2);
				
				


				$update=array(
					"trade_mode" => $this->request->getPost('trade_mode'),
            		"coin_id" => $this->request->getPost('coin_id'),
                   
            		"stratgy" => $this->request->getPost('stratgy'),
            		"profit" => $this->request->getPost('profit'),
            		"duration" => $this->request->getPost('duration'),
            		
            		"admin_fee" => $this->request->getPost('admin_fee'),
            		"description" =>$this->request->getPost('description'),
            		"first_buy_amount" =>  $this->request->getPost('first_buy_amount'),
	            	"open_position_doubled" =>  $this->request->getPost('open_position_doubled'),
	            	"margin_column_limit" =>  $this->request->getPost('margin_column_limit'),
	            	"strategy_mode" =>  $this->request->getPost('strategy_mode'),
	            	"strategy_type" =>  $this->request->getPost('strategy_type'),
	            	"whole_profit_ratio" =>  $this->request->getPost('whole_profit_ratio'),
	            	"whole_profit_callback" =>  $this->request->getPost('whole_profit_callback'),	            	
	            	"address"		=>	$this->request->getPost('address'),
	            	"amount"		=>	$this->request->getPost('amount'),
	            	"facebook"			=> $this->request->getPost('facebook'),
	            	"twitter"			=> $this->request->getPost('twitter'),
	            	"youtube"			=> $this->request->getPost('youtube'),
	            	"telegram"			=> $this->request->getPost('telegram'),
	            	"trade_image"	=>	$name,
	            	"margincall_drop"	=>	$tade1,
	            	"buyin_ratio_times"	=>	$tade2,
	            	"sub_position_callback" => $sub_position_callback
					);
			
			$this->db = db_connect();
			$query_status = $this->db->table('trader')->where('id', $id)->update($update);
			$session = session();
			if($query_status)
			{
				$session->setFlashData('success_message', 'Trader Successfully updated');
				return redirect()->to('admin/finance/tradelist');
			}
			else
			{
				$session->setFlashData('error_message', 'Trader failed to update');
				return redirect()->to('admin/finance/tradelist');
			}
		}
		 else
		 {
		 	return redirect()->to('admin/finance/edit_trader/'.$myid);
		 }
		

		}
		$this->data['required_pairs'] = ['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['trade'] = $imag;
		echo view('admin/finance/edit_trader',$this->data);
	}

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

		$this->db = db_connect();
		$delete = $this->db->query("DELETE FROM trader where id = '".$id."'");
	
		$this->session = \Config\Services::session();
		if($delete)
		{	
			$this->session->setFlashData('success_message', lang('Trader Successfully Deleted'));
			return redirect()->to('admin/finance/tradelist');
		}
		else
		{
			
			$this->session->setFlashData('error_message', lang('Trader Cannot be Deleted'));
			return redirect()->to('admin/finance/tradelist');
		}
	}

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

		$this->db = db_connect();
		$delete = $this->db->query("UPDATE trader set status = 1 where id = '".$id."'");
	
		$this->session = \Config\Services::session();
		if($delete)
		{	
			$this->session->setFlashData('success_message', lang('Trader Updated Successfully'));
			return redirect()->to('admin/finance/pending_trade');
		}
		else
		{
			
			$this->session->setFlashData('error_message', lang('Trader Cannot be Updated'));
			return redirect()->to('admin/finance/pending_trade');
		}
	}

		public function changeCircleStatus() {
        $session = session();
        $this->db = db_connect();
		if($this->request->getPost('id')) {

			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($this->request->getPost('id'));
		
			$user_data = array(
				"status" => '0'
			);
			
			$update_status = $this->db->table('trader')->where('id',$uusersid)->update($user_data);
			
			if($update_status){
			$session->setFlashData('success_message', "Circle deactivated successfully");
				echo 1;
				// return redirect()->to('admin/users');
			} else {
				$session->setFlashData('error_message', "Circle deactivation failed");
				// return redirect()->to('admin/users');
				echo 1;
			}
		}
	}

public function changeCircleActiveStatus() {
$session = session();
        $this->db = db_connect();
		if($this->request->getPost('id')) {

			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($this->request->getPost('id'));
		
			$user_data = array(
				"status" => '1'
			);
			
			$update_status = $this->db->table('trader')->where('id',$uusersid)->update($user_data);
			
			if($update_status){
			$session->setFlashData('success_message', "Circle activated successfully");
				echo 1;
				// return redirect()->to('admin/users');
			} else {
				$session->setFlashData('error_message', "Circle activation failed");
				// return redirect()->to('admin/users');
				echo 1;
			}
		}
	}


public function changePromotionStatus() {
        $session = session();
        $this->db = db_connect();
		if($this->request->getPost('id')) {

			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($this->request->getPost('id'));
		
			$user_data = array(
				"status" => '0'
			);
			
			$update_status = $this->db->table('promotion')->where('id',$uusersid)->update($user_data);
			
			if($update_status){
			$session->setFlashData('success_message', "Promotion deactivated successfully");
				echo 1;
				// return redirect()->to('admin/users');
			} else {
				$session->setFlashData('error_message', "Promotion deactivation failed");
				// return redirect()->to('admin/users');
				echo 1;
			}
		}
	}

public function changePromotionActiveStatus() {
$session = session();
        $this->db = db_connect();
		if($this->request->getPost('id')) {

			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($this->request->getPost('id'));
		
			$user_data = array(
				"status" => '1'
			);
			
			$update_status = $this->db->table('promotion')->where('id',$uusersid)->update($user_data);
			
			if($update_status){
			$session->setFlashData('success_message', "Promotion activated successfully");
				echo 1;
				// return redirect()->to('admin/users');
			} else {
				$session->setFlashData('error_message', "Promotion activation failed");
				// return redirect()->to('admin/users');
				echo 1;
			}
		}
	}





	public function trader($id='')
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$db = \Config\Database::connect();
		$myencrypt = new MyEncrypt;
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);

		$this->data['page_title'] = lang('language_lang.deposit_page_title');
		$this->data['module_name'] = 'finance';
		$condition = "market_currency ='1' and market_status ='1'";	
		$this->common_model = model('CommonModel');	
		$this->data['market_currency'] = $this->common_model->GetResults('coin_info',$condition);
		$condition = "status ='1'";		
		$this->data['trader'] = $this->common_model->GetResults('trader',$condition);
		$this->data['action'] =  base_url().'/admin/finance/trader';
		if($this->request->getPost())
		{
			$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'
            ],
				'admin_fee' => [
                'label' => 'Admin fees (%)', 
                'rules' => 'trim|required|numeric'
            ],
            'coin_id' => [
                'label' => 'List Coins', 
                'rules' => 'trim|required'
            ],
            'duration' => [
                'label' => 'Duration(Days)', 
                'rules' => 'trim|required|numeric'
            ],
            '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'
            ],
            'amount' => [
                'label' => 'Amount', 
                'rules' => 'trim|required|numeric'
            ]
			]);

			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())
            {
            	//$logo = $_FILES['trade_image']['name'];
            	
            if(isset($_FILES['trade_image']['tmp_name']) && $_FILES['trade_image']['size'] > 0) 
            {
              // img path
					$uploads_dir = './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');
                   
                   //uplode file
                     $img->move('./uploads/trader', $name);    
				
			}

				$trade = array(
					"trade_mode"	   		=>  $this->request->getPost('trade_mode'),
            		"coin_id" 		   		=>  $this->request->getPost('coin_id'),
            		"stratgy" 		   		=>  $this->request->getPost('stratgy'),
            		"profit"		   		=>  $this->request->getPost('profit'),
            		"duration"		   		=>  $this->request->getPost('duration'),
            		"admin_fee"		   		=>  $this->request->getPost('admin_fee'),
            		"description" 	   		=>  $this->request->getPost('description'),
            		"first_buy_amount" 		=>  $this->request->getPost('first_buy_amount'),
	            	"open_position_doubled" =>  $this->request->getPost('open_position_doubled'),
	            	"margin_column_limit" 	=>  $this->request->getPost('margin_column_limit'),
	            	"strategy_mode" =>  $this->request->getPost('strategy_mode'),
	            	"strategy_type" =>  $this->request->getPost('strategy_type'),
	            	"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'),
	            	"address"				=>	$this->request->getPost('address'),
	            	"amount"				=>	$this->request->getPost('amount'),
	            	"facebook"				=>  $this->request->getPost('facebook'),
	            	"twitter"				=>  $this->request->getPost('twitter'),
	            	"youtube"				=>  $this->request->getPost('youtube'),
	            	"telegram"				=>  $this->request->getPost('telegram'),
	            	"trade_image"			=>	$name	            	
				);

            	$this->db = db_connect();
				$query_status1 = $this->db->table('trader')->insert($trade);
				$last_id = $this->db->insertID();

				$num =$this->request->getPost('margin_column_limit');
				if($num!=0)
				{
					for($i=1; $i <= $num; $i++) 
					{					
						$trade1[$i]=$_POST["margincall_drop".$i.""];
						$buyin_ratio_times[$i]=$_POST["buyin_ratio_times".$i.""];
					}
						
						if($num >= 5)
						{
							for ($i=5; $i <= $num; $i++) 
							{  
								$buyin_ratio_times1[$i]=$_POST["buyin_ratio_times1".$i.""];
							}
						
							$trade2 =array(implode(',',$buyin_ratio_times),implode(',',$buyin_ratio_times1));						
						}
						else
						{
							
							$trade2 = $buyin_ratio_times;												
						}
									
					
					
				}
				$tade1=implode(',',$trade1);
				$tade2=implode(',',$trade2);

				$query_status=$this->db->query("UPDATE trader SET margincall_drop='".$tade1."',buyin_ratio_times='".$tade2."' WHERE id='".$last_id."'");
				
				
								
            	$session = session();
            	if($query_status1)
            	{
            		$session->setFlashData('success_message', lang('language_lang.lbl_trade_success'));
					return redirect()->to('admin/finance/tradelist');
				}
				else
				{
					
					$session->setFlashData('error_message', lang('language_lang.lbl_trade_error'));
				   	return redirect()->to('admin/finance/tradelist');
				}            		            		

 
 	        }

        }

     $required_pairs = ['1INCH','ADA','AAVE','ATOM','ALGO','AION','AVAX','AKRO','ANT','APE','BAT','BTC','BCH','BNB','BTCST','BAKE','CRV','COMP','CAKE','COS','DOGE','DASH','DOT','ETH','EOS','ETC','FTM','FTT','FIL','GALA','GRT','GMT','HBAR','HOT','IOTA','ICP','IOST','JST','KAVA','KSM','LTC','LINK','LIT','LUNA','MANA','MATIC','MDX','NEO','OMG','ONT','QTUM','REEF','RSR','SUN','SHIB','SLP','SOL','SUSHI','SXP','TRX','THETA','TFUEL','UNI','VET','WRX','XRP','XMR','XEM','XLM','XTZ','YFI','YFII','ZEC','ZEN'];
		
		echo view('admin/finance/trader',$this->data);
	}
	public function trade_validuser()
	{

		$trade_mode = $this->request->getPost('trade_mode');
		if($trade_mode)
		{
            $condition = "trade_mode ='" . $trade_mode . "'";
			$tradename = $this->common_model->GetRow('trader', $condition);
			if($tradename){
                $json['valid'] = false;
			}
			else {
				$json['valid'] = true;
			}
		}
		else{
			$json['valid'] = true;
		}
		echo json_encode($json);

	}

	public function config_field0()
	{
		$id = service('request')->getPost('id');

		if($id=='')
		{

			$num = service('request')->getPost('number');

			if($num >= 5)
			{

				for ($i=5; $i <= $num; $i++) 
				{ 
				
					echo   "<div class='modal-form mb-4'>";
					echo    "<label class=''>The ".$i."th sub-position</label>";
					echo   "<div class='input-group'>";
					echo    "<input type='text' class='form-control mt-1' required='TRUE' id='field0' name='buyin_ratio_times1".$i."' disabled>";
					echo    "<span class='input-group-addon'>% </span> </div>";
					echo   "</div>";
					echo "<br>";

				}
			}
		   	else
		   	{
		   		echo "";
		   	}
	   }
	   else
	   {
			$this->db = db_connect();
			$qury = $this->db->query("SELECT * FROM trader WHERE id='".$id."'")->GetResult();
			$qry=$qury[0];
			$num = $qry->margin_column_limit;
						
			$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' required='TRUE' id='field0' name='buyin_ratio_times1".$i."' value=".$margn[$i]." disabled >";
					echo    "<span class='input-group-addon'>% </span> </div>";
					echo   "</div>";
					echo "<br>";

				}
			}
			else
		   	{
		   		echo "";
		   	}
		}


	}

	public function config_field1()
	{
		$id = service('request')->getPost('id');

		if($id=='')
		{
			$num = service('request')->getPost('number1');		

			for ($i=1; $i <= $num; $i++) 
			{ 
				
				echo   "<div class='modal-form mb-4'>";
				echo    "<label class=''>The ".$i."nd call</label>";
				echo   "<div class='input-group'>";
				echo    "<input type='text' class='form-control mt-1' required='TRUE' id='field".$i."' name='margincall_drop".$i."' disabled >";
				echo    "<span class='input-group-addon'>% </span> </div>";
				echo   "</div>";
				echo "<br>";
			}
		}
		else
		{
			$this->db = db_connect();
			$qury = $this->db->query("SELECT * FROM trader WHERE id='".$id."' ")->GetResult();
			$qry=$qury[0];
			$num = $qry->margin_column_limit;
			$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' name='margincall_drop".$i."' required='TRUE' id='field1' value=".$margin[$i]." disabled >";
				echo    "<span class='input-group-addon'>% </span> </div>";
				echo   "</div>";
				echo "<br>";
			}
			
		}

	}

	public function config_field2()
	{
		$id = service('request')->getPost('id');

		if($id=='')
		{

			$num = service('request')->getPost('number2');

			for ($i=1; $i <= $num; $i++) 
			{ 		
				echo   "<div class='modal-form mb-4'>";
				echo    "<label class=''>The ".$i."th order amount</label>";
				echo   "<div class='input-group'>";
				echo    "<input type='text' class='form-control mt-1' required='TRUE' id='field2' name='buyin_ratio_times".$i."' disabled >";
				echo    "<span class='input-group-addon'>%</span> </div>";
				echo   "</div>";
				echo "<br>";
		   }
	   }
		else
		{
			$this->db = db_connect();
			$qury = $this->db->query("SELECT * FROM trader WHERE id='".$id."' ")->GetResult();
			$qry=$qury[0];
			$num = $qry->margin_column_limit;
			$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' required='TRUE' id='field2' name='buyin_ratio_times".$i."' value=".$buyin[$i]." disabled>";
				echo    "<span class='input-group-addon'>%</span> </div>";
				echo   "</div>";
				echo "<br>";
		   }
			
		}

	}
	public function config_field3()
	{

		$num = service('request')->getPost('number');

		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' required='TRUE' id='field33' name='buyin_ratio_times1".$i."' disabled>";
				echo    "<span class='input-group-addon'>% </span> </div>";
				echo   "</div>";
				echo "<br>";
			}
		}
	   	else
	   	{
	   		echo "";
	   	}
   }

   public function config_field4()
	{
		
		$num = service('request')->getPost('number1');		
		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' required='TRUE' id='field11' name='margincall_drop".$i."' disabled >";
			echo    "<span class='input-group-addon'>% </span> </div>";
			echo   "</div>";
			echo "<br>";
		}
	}

	public function config_field5()
	{
		$num = service('request')->getPost('number2');
		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' required='TRUE' id='field22' name='buyin_ratio_times".$i."'disabled >";
			echo    "<span class='input-group-addon'>%</span> </div>";
			echo   "</div>";
			echo "<br>";
	   }
   }

	public function currencypairlist()
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->common_model = model('CommonModel');
		if($id)
		{
			$myencrypt = new MyEncrypt;
			$id_val = $myencrypt->decode($id);
			$condition = "uusersid =".$id_val;
			$this->data['member_name'] = $this->common_model->GetRow('uusers',$condition);
			$useridval = $this->common_model->GetRow('uusers',$condition);
			$this->data['flag']=1;
		}
		else
		{
			$this->data['flag']=0;
		}
		
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);

		$this->data['page_title'] = lang('language_lang.deposit_page_title');
		$this->data['module_name'] = 'finance';
		$condition = "market_currency ='1' and market_status ='1' ";		
		$this->data['market_currency'] = $this->common_model->Getcurrencypairname();
		echo view('admin/finance/currencypairlist',$this->data);
		
	}	


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

		if($id)
		{

			$myencrypt = new MyEncrypt;
			$id_val = $myencrypt->decode($id);
			$condition = "uusersid =".$id_val;
			$this->data['member_name'] = $this->common_model->GetRow('uusers',$condition);
			$useridval = $this->common_model->GetRow('uusers',$condition);
			$this->data['flag']=1;
		}
		else
		{
			$this->data['flag']=0;
		}
		$this->common_model = model('CommonModel');
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);
		$this->db = db_connect();
		$this->data['page_title'] = lang('language_lang.deposit_page_title');
		$this->data['module_name'] = 'finance';
		// $condition = "status ='1'";		
		$this->data['trader'] = $this->common_model->GetResults('trader',$condition);
		echo view('admin/finance/traderlist',$this->data);
		
	}	

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

		if($id)
		{

			$myencrypt = new MyEncrypt;
			$id_val = $myencrypt->decode($id);
			$condition = "uusersid =".$id_val;
			$this->data['member_name'] = $this->common_model->GetRow('uusers',$condition);
			$useridval = $this->common_model->GetRow('uusers',$condition);
			$this->data['flag']=1;
		}
		else
		{
			$this->data['flag']=0;
		}
		$this->common_model = model('CommonModel');
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);
		$this->db = db_connect();
		$this->data['page_title'] = lang('language_lang.deposit_page_title');
		$this->data['module_name'] = 'finance';
		// $condition = "status ='1'";		
		$this->data['trader'] = $this->common_model->GetResults('promotion',$condition);
		echo view('admin/finance/promotionlist',$this->data);
		
	}	

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

		if($id)
		{
			$myencrypt = new MyEncrypt;
			$id_val = $myencrypt->decode($id);
			$condition = "uusersid =".$id_val;
			$this->data['member_name'] = $this->common_model->GetRow('uusers',$condition);
			$useridval = $this->common_model->GetRow('uusers',$condition);
			$this->data['flag']=1;
		}
		else
		{
			$this->data['flag']=0;
		}
		$this->common_model = model('CommonModel');
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);
		$this->db = db_connect();
		$this->data['page_title'] = lang('language_lang.deposit_page_title');
		$this->data['module_name'] = 'finance';
		$condition = "status ='0'";		
		$this->data['trader'] = $this->common_model->GetResults('trader',$condition);
	
		

		echo view('admin/finance/pending_trade',$this->data);
		
	}

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

		if($id)
		{
			$myencrypt = new MyEncrypt;
			$id_val = $myencrypt->decode($id);
			$condition = "uusersid =".$id_val;
			$this->data['member_name'] = $this->common_model->GetRow('uusers',$condition);
			$useridval = $this->common_model->GetRow('uusers',$condition);
			$this->data['flag']=1;
		}
		else
		{
			$this->data['flag']=0;
		}
		$this->common_model = model('CommonModel');
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);
		$this->db = db_connect();
		$this->data['page_title'] = "Pending Withdraw";
		$this->data['module_name'] = 'finance';
		$condition = "type ='withdraw_request'";		
		$this->data['trader'] = $this->common_model->GetResults('history',$condition);
	
		

		echo view('admin/finance/pending_withdraw',$this->data);
		
	}				

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

		$this->benchmark->mark('package_start');
		$currency_info = defaultcurrency();

		$condition = "packageid ='" . $packageid . "'";
		$plans = $this->common_model->GetResults('plans', $condition);
		
		$json['plans'] = '';
		
		foreach ($plans as $plan) { 
			$min_amount = $currency_info->currency_symbol.''.number_format($plan->min_amount,$currency_info->deimal_point, '.', '');
			$max_amount = $currency_info->currency_symbol.''.number_format($plan->max_amount,$currency_info->deimal_point, '.', '');
			$rate =  number_format($plan->rate,$currency_info->deimal_point, '.', '').' %';
			$json['plans'] .= '<option value="'.$plan->planid.'">'.ucfirst($plan->plan_name).' - '.$min_amount.' - '.$max_amount.' - '.$rate.'</option>';
			
		}

		$json['compound'] = '';
		
		$this->db->where('packageid', $packageid);
		$this->db->select('compond_min, compond_max');
		$this->db->from('package');
		
		$query = $this->db->get();
		if ($query->num_rows()>0) {
			$package_compound =  $query->row();
			if($package_compound->compond_min!=$package_compound->compond_max || $package_compound->compond_max!=0) {
				$range = range($package_compound->compond_min,$package_compound->compond_max,5);
				foreach ($range as $cm) {
				  $json['compound'] .= '<option value="'.$cm.'">'.$cm.'% </option>';
				}
			} else {
				$json['compound'] .= '<option value="0">0</option>';
			}
		}
		
		echo json_encode($json);
		$this->benchmark->mark('package_end');
	}



	public function bonus($id='')
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->db = db_connect();
		$session = \Config\Services::session();
		$session = session();
		helper('text');
		$this->common_model = model('CommonModel');
		if($id){
			$myencrypt = new MyEncrypt;
			$id_val = $myencrypt->decode($id);
			$condition = "uusersid =".$id_val;
			$this->data['member_name'] = $this->common_model->GetRow('uusers',$condition);
			$useridval = $this->common_model->GetRow('uusers',$condition);
			$this->data['flag']=1;

		}
		else {
			$this->data['flag']=0;
		}

		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);        
		$this->data['module_name'] = 'finance';
        $this->data['uusers_list'] = $this->common_model->GetResults('uusers');
        
		$this->data['action'] =  'admin/finance/bonus';

        $condition = "status = '1' AND coin_symbol = 'USDT'";
		$this->data['all_active_coin'] = $this->common_model->GetResults('coin_info',$condition);

		// echo $this->db->last_query();
		// exit();

		if($this->request->getPost()) {
			$this->form_validation = \Config\Services::validation();
			// form validation
			$this->form_validation->setRule('select_coin', lang("language_lang.lbl_select_coin"), 'trim|required');
		 	$this->form_validation->setRule('description', lang("language_lang.description"), 'trim|required');
         	$this->form_validation->setRule('amount', lang("language_lang.amount"), 'trim|required');
            if($this->request->getPost('select_user') && $this->request->getPost('userlist')){
	         	$this->form_validation->setRule('select_user',lang("language_lang.bonus_usertype"),'required');
	         	$this->form_validation->setRule('userlist',lang("language_lang.bonus_select_user"),'required'); 
            }
         	// $this->form_validation->set_rules('payment',lang("language_lang.bonus_currency"),'required');

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

            	$url = 'bonuspenaltyhistory';
            	// sent mail to user
				$subject = 'Bonus Notification';
				$mailid = '12';
				$mail_subject_data = $this->common_model->getMailTemplate($mailid);
				
				$message  = str_replace('[AMT]', $this->request->getPost('amount'), $mail_subject_data->message);
				$message  = str_replace('[site_url]', $url, $message);
				
			    

            	if($this->request->getPost('userlist')){
                    $userlist = $this->request->getPost('userlist'); 

                    foreach ($userlist as $row => $value) {

                    	$user = $this->common_model->GetUser($value);
                    	
                    	$message  = str_replace('[NAME]', $user->fullname, $message);

						$bonus_data = array(
							"uusersid" 		=> $value,
							"currency"      => $this->request->getPost('select_coin'),
							"amount"		=>	$this->request->getPost('amount'),
							"type" 			=>  "bonus",
							"description" 	=> $this->request->getPost('description'),
							"date"     		=>  date("Y-m-d H:i:s"),
							"transactionid" => strtoupper(random_string('alnum', 16)),
							"user_group"    => $user->new_entry,
 							"status"		=> 1
						);
					
						$query_status = $this->db->table('history')->insert($bonus_data);
						
						if($mail_subject_data->status=='1'){

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

            	}	
            	else {

            		$myencrypt = new MyEncrypt;
			        $userlist = $myencrypt->decode($this->request->getPost('user1'));

            		$user = $this->common_model->GetUser($userlist);
                    $message  = str_replace('[NAME]', $user->fullname, $message);
            		
					$bonus_data = array(
						"uusersid" 		=> $userlist,
						"currency"      => $this->request->getPost('select_coin'),
						"amount"		=>	$this->request->getPost('amount'),
						"type" 			=>  "bonus",
						"description" 	=> $this->request->getPost('description'),
						"date"     		=>  date("Y-m-d H:i:s"),
						"transactionid" => strtoupper(random_string('alnum', 16)),
						"user_group"    => $user->new_entry,
						"status"		=> 1
					);
				
					$query_status = $this->db->table('history')->insert($bonus_data);
					
					 $mail_status = $this->sendmail($user->email, $user->fullname, $subject, $message);
				
            	}

                if($query_status) {
					$session = \Config\Services::session();
					$session->setFlashData('success_message', lang('language_lang.bonus_success_message'));
					return redirect()->to('admin/finance/bonus');
				} else {
					$session = \Config\Services::session();
					$session->setFlashData('error_message', lang('language_lang.bonus_error_message'));
					return redirect()->to('admin/finance/bonus');
				}
            }
			
		}
		echo view('admin/finance/bonus',$this->data);

	}

	public function penalty($id='')
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		helper('text');
		$this->db = db_connect();
		$session = \Config\Services::session();
		$session = session();
		$this->form_validation = \Config\Services::validation();
      $this->common_model = model('CommonModel');
		if($id)
		{
			$myencrypt = new MyEncrypt;
			$id_val = $myencrypt->decode($id);
			$condition = "uusersid =".$id_val;
			$this->data['member_name'] = $this->common_model->GetRow('uusers',$condition);
			$useridval = $this->common_model->GetRow('uusers',$condition);
			$this->data['flag']=1;
		}
		else
		{
			$this->data['flag']=0;
		}

		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);
        $this->data['module_name'] = 'finance';
        $this->data['uusers_list'] = $this->common_model->GetResults('uusers');
        
		$this->data['action'] = 'admin/finance/penalty';

		$condition = "status = '1' AND coin_symbol = 'USDT'";
		$this->data['all_active_coin'] = $this->common_model->GetResults('coin_info',$condition);
		
         
		if($this->request->getPost()) {
			
			// form validation
			$this->form_validation->setRule('select_coin', lang("language_lang.lbl_select_coin"), 'trim|required');
		 	$this->form_validation->setRule('description', lang("language_lang.description"), 'trim|required');
         	$this->form_validation->setRule('amount', lang("language_lang.amount"), 'trim|required');
         	if($this->request->getPost('select_user') && $this->request->getPost('userlist')){
	         	$this->form_validation->setRule('select_user',lang("language_lang.bonus_usertype"),'required');
	         	$this->form_validation->setRule('userlist',lang("language_lang.bonus_select_user"),'required'); 
            }
                
            if ($this->form_validation->withRequest($this->request)->run() == TRUE) {

            	$url = 'bonuspenaltyhistory';
            	// sent mail to user
				$subject = 'Penalty Notification';
				$mailid = '13';
				$mail_subject_data = $this->common_model->getMailTemplate($mailid);
				$message  = str_replace('[AMT]', $this->request->getPost('amount'), $mail_subject_data->message);
				$message  = str_replace('[site_url]', $url, $message);

				if($this->request->getPost('userlist')){
				    $userlist = $this->request->getPost('userlist');

					foreach ($userlist as $row => $value) {

						$user = $this->common_model->GetUser($value);
                    	$message  = str_replace('[NAME]', $user->fullname, $message);

						$penalty_data = array(
							"uusersid" => $value,
							"currency" => $this->request->getPost('select_coin'),
							"amount"	=>	$this->request->getPost('amount'),
							"type"   =>  "penalty",
							"description" => $this->request->getPost('description'),
							"date"     =>  date("Y-m-d h:i:sa"),
							"transactionid" => strtoupper(random_string('alnum', 16)),
							"user_group"    => $user->new_entry,
							"status"		=> 1
						);
					
						$query_status = $this->db->table('history')->insert($penalty_data);
						
						if($mail_subject_data->status=='1'){

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

						}
						
					}

			    } else {
            		$myencrypt = new MyEncrypt;
			        $userlist = $myencrypt->decode($this->request->getPost('user1'));

			        $user = $this->common_model->GetUser($userlist);
                    $message  = str_replace('[NAME]', $user->fullname, $message);

                    $penalty_data = array(
						"uusersid" => $userlist,
						"currency" => $this->request->getPost('select_coin'),
						"amount"	=>	$this->request->getPost('amount'),
						"type"   =>  "penalty",
						"description" => $this->request->getPost('description'),
						"date"     =>  date("Y-m-d H:i:s"),
						"transactionid" => strtoupper(random_string('alnum', 16)),
						"user_group"    => $user->new_entry,
						"status"		=> 1
					);

                   $query_status = $this->db->table('history')->insert($penalty_data);
					if($mail_subject_data->status=='1'){

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

               		}
                   

			    }

                if($query_status) {
					$session = \Config\Services::session();
					$session->setFlashData('success_message', lang('language_lang.penalty_success_message'));
					return redirect()->to('admin/finance/penalty');
				} else {
					$session = \Config\Services::session();
					$session->setFlashData('error_message', lang('language_lang.penalty_error_message'));
					return redirect()->to('admin/finance/penalty');
				}
           	}
			
		}
		echo view('admin/finance/penalty',$this->data);
	}

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

		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);
        $this->data['module_name'] = 'finance';
        $this->data['uusers_list'] = $this->common_model->GetResults('uusers');
        
		$this->data['action'] =  base_url().'admin/finance/fundtransfer';
		$transfer_data = $this->common_model->GetSettingall('transfer');

		foreach ($transfer_data as $row) {
			$this->data[$row->site_key] = $row->site_value;
		}
         
		if($this->request->getPost()) {
			// form validation
			$senderid = $this->request->getPost('select_payer');
         	$this->form_validation->set_rules('amount',lang("language_lang.amount"), 'trim|required|callback_check_transfer_amount');
                
            if ($this->form_validation->run() == TRUE) {

            	$transfer_data = $this->common_model->GetSettingall('transfer');
			    foreach ($transfer_data as $row) {
					$trdata[$row->site_key] = $row->site_value;
				}

				$tottransfer_amount = $this->request->getPost('amount');
				// $tot_transferfee = $this->request->getPost('transfee');

				$fee_percent = $trdata['transfer_fee'] * $tottransfer_amount;
	    		$final_value = $fee_percent / 100 ;

				if($trdata['transfer_min_fee'] <= $final_value) {
		    		$tot_transferfee = number_format($final_value, $currency_info->deimal_point, '.', '');
			    } else {
			    	$tot_transferfee = $this->data['transfer_min_fee'];
			    }

				$condition = 'uusersid = '."'".$this->request->getPost('select_payer')."'";
				$sender_name = $this->common_model->GetUsername('uusers',$condition);
				
				$condition1 = 'uusersid = '."'".$this->request->getPost('select_receiver')."'";
				$receiver_name = $this->common_model->GetUsername('uusers',$condition1);
			
				if($trdata['transfer_fee_payer'] == "payer") {

					$amount = $tottransfer_amount + $tot_transferfee;

					$fund_send = array(
						"uusersid" => $this->request->getPost('select_payer'),
						"amount"	=>	$amount,
						"type"   =>  "fund_send",
						"description" => "fund transferred to"." ".$receiver_name->username,
						"date"     =>  date("Y-m-d h:i:sa"),
						"transactionid" => strtoupper(random_string('alnum', 16))
					);
					

                   	$fund_received = array(
						"uusersid" => $this->request->getPost('select_receiver'),
						"amount"	=>	$this->request->getPost('amount'),
						"type"   =>  "fund_received",
						"description" => "fund received from"." ".$sender_name->username,
						"date"     =>  date("Y-m-d h:i:sa"),
						"transactionid" => strtoupper(random_string('alnum', 16))
					);
					

				}
				else {

					$amount = $tottransfer_amount - $tot_transferfee;
                    
					$fund_send = array(
						"uusersid" => $this->request->getPost('select_payer'),
						"amount"	=>	$this->request->getPost('amount'),
						"type"   =>  "fund_send",
						"description" => "fund transferred to"." ".$receiver_name->username,
						"date"     =>  date("Y-m-d h:i:sa"),
						"transactionid" => strtoupper(random_string('alnum', 16))
					);

                   	$fund_received = array(
						"uusersid" => $this->request->getPost('select_receiver'),
						"amount"	=>	$amount,
						"type"   =>  "fund_received",
						"description" => "fund received from"." ".$sender_name->username,
						"date"     =>  date("Y-m-d h:i:sa"),
						"transactionid" => strtoupper(random_string('alnum', 16))
					);

				}
					
              	$transfer_fees = array(
					"uusersid" => "0",
					"amount"	=>	$tot_transferfee,
					"type"   =>  "transfer_fee",
					"description" => "internal transfer fee",
					"date"     =>  date("Y-m-d h:i:sa"),
					"transactionid" => strtoupper(random_string('alnum', 16))
				);

				$query_status = $this->db->insert('history',$fund_send);
				$query_status = $this->db->insert('history',$fund_received);
				$query_status = $this->db->insert('history',$transfer_fees);

                if($query_status) {
					$session = \Config\Services::session();
					$session->setFlashData('success_message', lang('language_lang.fundtransfer_success_message'));
					return redirect()->to('admin/finance/fundtransfer');
				} else {
					$session = \Config\Services::session();
					$session->setFlashData('error_message', lang('language_lang.fundtransfer_error_message'));
					return redirect()->to('admin/finance/fundtransfer');
				}

           }
			
		}
		echo view('admin/finance/fundtransfer',$this->data);

	}

	public function list_user($id)
	{
		$this->db = db_connect();
		
		$session = \Config\Services::session();
		$this->common_model = model('CommonModel');
		$group=$this->request->getPost('group');

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

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

		$user_group = $get_admin->user_group;
		if($id != '4') {
	    	$condition = 'status = '."'".$id."'";
	    } else {
		  $condition = "status in('1','0')";
	    }
		if($group!='all')
		{
				$condition = 'new_entry = '."'".$group."'";
		}
		else
		{
			if($user_group=='1')
				$condition = "new_entry = '0'";
			else
				$condition = "new_entry ='1'";

		}

		$uusers_list = $this->common_model->GetResults('uusers',$condition);
		foreach ($uusers_list as $row) {
			echo "<option value='".$row->uusersid."'>".ucfirst($row->username)."</option>";
		}

	}

	public function list_user_new()
	{
		$this->db = db_connect();
		
		$session = \Config\Services::session();
		$this->common_model = model('CommonModel');
		$group=$this->request->getPost('group');

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

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

		$user_group = $get_admin->user_group;
		

		if($group!='all')
		{
				$condition = 'new_entry = '."'".$group."'";
		}
		else
		{
			if($user_group=='1')
				$condition = "new_entry = '0'";
			else if($user_group=='2')
				$condition = "new_entry ='1'";
            else
				$condition='';
		
		}

		echo "<option value=''>All</option>";
		$uusers_list = $this->common_model->GetResults('uusers',$condition);
		foreach ($uusers_list as $row) {
			echo "<option value='".$row->uusersid."'>".ucfirst($row->username)."</option>";
		}

	}


	

	function transationfee() {
		$currency_info = defaultcurrency();

		$amount_value = $this->request->getPost('amount');

		if($amount_value) {

			$transfer_data = $this->common_model->GetSettingall('transfer');
			foreach ($transfer_data as $row) {
				$trdata[$row->site_key] = $row->site_value;
			}
			
			$fee_percent = $trdata['transfer_fee'] * $amount_value;
    		$final_value = $fee_percent / 100 ;
    		if($trdata['transfer_min_fee'] <= $final_value) {
	    		echo number_format($final_value, $currency_info->deimal_point, '.', '');
		    } else {
		    	echo $trdata['transfer_min_fee'];
		    }
		}
	}

	function check_transfer_amount($str)
	{

		$transfer_data = $this->common_model->GetSettingall('transfer');
		foreach ($transfer_data as $row) {
			$trdata[$row->site_key] = $row->site_value;
		}

		if ($str < $trdata['transfer_min_amt'] || $str > $trdata['transfer_max_amt']) {

			$session = \Config\Services::session();
			$session->setFlashData('error_message', lang('language_lang.fundtransfer_error_message'));
	      	return false;
		}
		else{
			return true;
		}
	}

	function checkfee() {
		

		$currency_info = defaultcurrency();
		$amount_value = $this->request->getPost('amount');
		
		$sender_id  = $this->request->getPost('sender_id');

		if($amount_value) {
			$transfer_data = $this->common_model->GetSettingall('transfer');
			foreach ($transfer_data as $row) {
				$trdata[$row->site_key] = $row->site_value;
			}
			if($trdata['transfer_min_amt'] > 0 && $trdata['transfer_max_amt'] > 0){
				if ($amount_value < $trdata['transfer_min_amt'] || $amount_value > $trdata['transfer_max_amt']) {
					$json['valid'] = false;
					$json['message'] = "Transfter amount between ".$trdata['transfer_min_amt']." and ".$trdata['transfer_max_amt'];
					
				} else {
					$json['valid'] = true;
				}
			} else {
				if($trdata['transfer_max_amt'] == 0){
					if ($amount_value < $trdata['transfer_min_amt']) {
						$json['valid'] = false;
						$json['message'] = "Transfter amount must be more than ".$trdata['transfer_min_amt'];
						
					} else {
						$json['valid'] = true;
					}
				}
			}
			
		}

		$balance_amount = $this->check_balance($sender_id);
       
		$transfer_data = $this->common_model->GetSettingall('transfer');

		if($balance_amount) {

		    if(number_format($balance_amount,$currency_info->deimal_point, '.', '') < number_format($amount_value,$currency_info->deimal_point, '.', '')) {
		    	
		   		$json['valid'] = false;
		   		$json['message'] = "The sender have insufficient balance.";
		   	}

		} else {
			$json['valid'] = false;
		   	$json['message'] = "The sender have insufficient balance.";
		} 
	   	echo json_encode($json);
		

	}
	
	function checkbalance() {

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

			$currency_info = defaultcurrency();

			// if($this->request->getPost('id')){
			// 	$gateway_id = $this->request->getPost('id');
			// } else {
         	// 	$gateway_id = $this->request->getPost('payid');
         	// }
        	
			$sender_id  = $this->request->getPost('sender_id');
			$balance = $this->check_balance($sender_id);

			if($balance>0) {
				echo number_format($balance,$currency_info->deimal_point, '.', '');
			} else {
				echo number_format(0,$currency_info->deimal_point, '.', '');
			}
			if(isset($json)){
				echo json_encode($json);
			}
		}
	}
	
	private function check_balance($sender_id){
        
        $earnings_type  = "'interest', 'commissions', 'bonus', 'fund_received', 'release_deposit'";
        $expenses_type  = "'reinvest', 'withdrawal', 'withdraw_request', 'penalty', 'fund_send', 'withdraw_fee', 'transfer_fee'";

        if($sender_id) {

			// calculate user earnings 
	        $condition = "uusersid = '".$sender_id."' AND  type IN (".$earnings_type.")";
	        $earnings = $this->common_model->GetEarnings('history',$condition);

	        // calculate user expenses
	        $condition1 = "uusersid = '".$sender_id."' AND  type IN (".$expenses_type.")";
	        // $condition1 = 'uusersid ='."'".$sender_id."'".'AND payment_id ='."'".$gateway_id."'"."and (".$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;
			
		} else {
			return 0;
		}
	}

	function validamount($planid)
	{
		if($planid){

			$condition = "planid ='" . $planid . "'";
			$plans = $this->common_model->GetRow('plans', $condition);
			if($plans) {
				$currency_info = defaultcurrency();
				$amount = number_format($this->request->getPost('amount'), $currency_info->deimal_point, '.', '');;
				
				$min = number_format($plans->min_amount, $currency_info->deimal_point, '.', '');
				$max = number_format($plans->max_amount, $currency_info->deimal_point, '.', '');

				if($max==0){
					if($amount >= $min){
						$json['valid'] = true;
					} else {
						$json['valid'] = false;
					}
				} else {
					if($amount >= $min && $amount <= $max){
						$json['valid'] = true;
					} else {
						echo $amount;
						$json['valid'] = false;
					}
				}
				
			} else {
				$json['valid'] = false;
			}
			echo json_encode($json);
		} 	
	}

	public function minmax()
	{
		// pr($this->request->getPost())
		$json['valid'] = false;
		echo json_encode($json);
	}
	
	public function confirmpayout(){
		$myencrypt = new MyEncrypt;
		$historyid = $myencrypt->decode($this->request->getPost('id'));

		$condition = "historyid = '".$historyid."'";
		$history_data = $this->common_model->GetRow('history', $condition);

		$withdraw_data = array(
			'type' => "withdrawal"
		);
		$this->db->where('historyid',$historyid);
		$query_status = $this->db->update('history',$withdraw_data);
	}

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

		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);

		$this->data['page_title'] = lang('language_lang.pending_deposit_title');

		$this->data['module_name'] = 'finance';

		$condition = "history.type = 'deposit_req' AND history.is_delete = '0'";
		$this->data['history'] = $this->finance_model->GetTransactions($condition);

		// echo $this->db->last_query();
		// exit;		


		echo view('admin/finance/pendingdeposit',$this->data);
	}


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

		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);

		$this->data['page_title'] = lang('language_lang.pending_deposit_title');

		$this->data['module_name'] = 'finance';

		$condition = "history.type = 'deposit_req' AND history.is_delete = '0'";
		$this->data['history'] = $this->finance_model->GetTransactions($condition);

		// echo $this->db->last_query();
		// exit;		


		echo view('admin/finance/pendingdeposit',$this->data);
	}


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

		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);

		$this->data['page_title'] = lang('language_lang.pending_purchase_title');

		$this->data['module_name'] = 'finance';

		$condition = "deposit.description = 'purchase request' AND deposit.status= 'new'";
		$this->data['history'] = $this->finance_model->Getpurchase($condition);

		echo view('admin/finance/pendingpurchase',$this->data);
	}

	public function listing()
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->common_model = model('CommonModel');
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);

		$this->data['module_name'] = 'finance';
		$this->data['coin_info'] = $this->common_model->GetResults('coin_info');		
		echo view('admin/finance/list',$this->data);
	}

	 public function uploadFile($path, $image) {
		if ($image->isValid() && ! $image->hasMoved()) {
			$newName = $image->getRandomName();
			$image->move('./'.$path, $newName);
			return $image->getName();
		}
		return "Image error";
	}


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

		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->uri = service('uri');
		$this->form_validation = \Config\Services::validation();
		
		$session = session();
		$this->common_model = model('CommonModel');
		$this->db = db_connect();


		$id=$this->uri->getSegment(4);
		if($id)
		{
			$myencrypt = new MyEncrypt;
			$id = $myencrypt->decode($id);			
		}	


		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);

		$this->data['action'] = 'admin/finance/addlist';
		
		$this->data['module_name'] = 'finance';

		if($id!="")
		{	
			$condition = "coid = '".$id."'";  
			$this->data['coin_info'] = $this->common_model->GetRow('coin_info',$condition);
		}
		
		

		if($this->request->getPost())
		{
			$this->form_validation->setRule('github', lang('language_lang.lbl_coin_name'), 'trim');
			// $this->form_validation->setRule('coin_name', lang('language_lang.lbl_coin_name'), 'trim|required');
			// $this->form_validation->setRule('coin_symbol', lang('language_lang.lbl_coin_symbol'), 'trim|required');
			
			$favicon=$_FILES['coin_image']['tmp_name'];
			if($favicon!='')
			{
				$this->form_validation->setRule('coin_image', lang('language_lang.lbl_icon_picture'), 'trim|is_image[coin_image]');
			}
			
			$logo=$_FILES['whitepaper']['tmp_name'];
			if($logo!='')
			{
				$this->form_validation->setRule('whitepaper', lang('language_lang.lbl_whitepaper'), 'trim|ext_in[whitepaper,jpeg,jpg,png,gif,ico]|is_image[whitepaper]');
			}

			if($this->form_validation->withRequest($this->request)->run() == TRUE)
			{	
				$sitedata = array();

				if(isset($_FILES['coin_image']['tmp_name']) && $_FILES['coin_image']['size'] > 0)
				{
					$path = '/uploads/coins/';
					$file 			    = $this->request->getFile('coin_image');
					$upload_file 	    = $this->uploadFile($path, $file);
					// $tmp_name = $_FILES['coin_image']['tmp_name'];
					// $datez=strtotime(date("Y-m-d H:i:s"));         
			  //       $name = $datez.''.basename($_FILES['coin_image']['name']);
			  //       if(move_uploaded_file($tmp_name, "$uploads_dir/$name"))
			  //       {
					// 	$sitedata["coin_image"]	= $name;
						
			  //       }
					$sitedata["coin_image"] = $upload_file;
				}				

				$sitedata["uusersid"] = '0';

				if(isset($_FILES['whitepaper']['tmp_name']) && $_FILES['whitepaper']['size'] > 0)
				{
					$path = '/uploads';
					$file 			    = $this->request->getFile('whitepaper');
					$upload_file 	    = $this->uploadFile($path, $file);
					// $tmp_name = $_FILES["whitepaper"]["tmp_name"];
					
					// $datez=strtotime(date("Y-m-d H:i:s")); 
			  //       $name = $datez.''.basename($_FILES["whitepaper"]["name"]);
			  //       if(move_uploaded_file($tmp_name, "$uploads_dir/$name"))
			  //       {		        	
						$sitedata["whitepaper"]	= $upload_file;
			        // }
				}					
					
				if($this->request->getPost('coin_id')=="")					
				{
					$postget = array(
						"coin_name"   => $this->request->getPost('coin_name'),
						"coin_symbol" => $this->request->getPost('coin_symbol'),
						"contract" => $this->request->getPost('coin_contract'),
						"issue_date"  => date('Y-m-d',strtotime($this->request->getPost('issue_date'))),
						"issue_price" => $this->request->getPost('issue_price'),
						"coin_decimal"=> $this->request->getPost('coin_decimal'),
						"max_supply"  => $this->request->getPost('max_supply'),
						"circulate_supply" => $this->request->getPost('circulate_supply'),
						"website"  => $this->request->getPost('website'),
						"explorer" => $this->request->getPost('explorer'),
						"introduction" => $this->request->getPost('introduction'),
						"facebook" => $this->request->getPost('facebook'),
						"twitter" => $this->request->getPost('twitter'),
						"github"  => $this->request->getPost('github'),
						"telegram"=> $this->request->getPost('telegram'),
						"reddit"  => $this->request->getPost('reddit'),
						"transfer_fees"  => $this->request->getPost('transfer_fees'),
						"trade_fees"  => $this->request->getPost('trade_fees'),
						"min_withdraw"  => $this->request->getPost('min_withdraw'),
						"withdraw"=> $this->request->getPost('withdraw') ? '1' : '0',
						"deposit" => $this->request->getPost('deposit') ? '1' : '0',
						"trade"   => $this->request->getPost('trade') ? '1' : '0',
						"pay_mode"   => $this->request->getPost('pay_mode'),
						"pay_status"   => $this->request->getPost('pay_status'),
						"coin_type"   => $this->request->getPost('coin_type'),
						"buycount"   => $this->request->getPost('buycount'),
						"increase_percentage"   => $this->request->getPost('inc_per'),
						"sellcount"   => $this->request->getPost('sellcount'),
						"decrease_percentage"   => $this->request->getPost('dec_per'),
						"coins_per"   => $this->request->getPost('coins_per'),
						"arbit_status"   => $this->request->getPost('arbit_status'),
						"min_amt"   => $this->request->getPost('min_amt'),
						"max_amt"   => $this->request->getPost('max_amt'),
						"int_rate"   => $this->request->getPost('int_rate'),
						"duration"   => $this->request->getPost('duration'),
						"payout_peroid"   => $this->request->getPost('payout_peroid'),
						"ret_balance"   => $this->request->getPost('ret_balance'),
						"buyback"   => $this->request->getPost('buyback'),
						"buy_fees"   => $this->request->getPost('buy_fees'),
						"buydays"   => $this->request->getPost('buydays'),
						"market_status" =>'1',
						"status"=>'1'
					);
					$site_data = array_merge($sitedata, $postget);
					$update_status_logo = $this->db->table('coin_info')->insert($site_data);		
				}
				else
				{
					$postget = array(
						"coin_name"   => $this->request->getPost('coin_name'),
						"coin_symbol" => $this->request->getPost('coin_symbol'),
						"contract" => $this->request->getPost('coin_contract'),
						"issue_date"  => date('Y-m-d',strtotime($this->request->getPost('issue_date'))),
						"issue_price" => $this->request->getPost('issue_price'),
						"coin_decimal"=> $this->request->getPost('coin_decimal'),
						"max_supply"  => $this->request->getPost('max_supply'),
						"circulate_supply" => $this->request->getPost('circulate_supply'),
						"website"  => $this->request->getPost('website'),
						"explorer" => $this->request->getPost('explorer'),
						"introduction" => $this->request->getPost('introduction'),
						"facebook" => $this->request->getPost('facebook'),
						"twitter" => $this->request->getPost('twitter'),
						"github"  => $this->request->getPost('github'),
						"telegram"=> $this->request->getPost('telegram'),
						"reddit"  => $this->request->getPost('reddit'),
						"transfer_fees"  => $this->request->getPost('transfer_fees'),
						"trade_fees"  => $this->request->getPost('trade_fees'),
						"min_withdraw"  => $this->request->getPost('min_withdraw'),
						"withdraw"=> $this->request->getPost('withdraw') ? '1' : '0',
						"deposit" => $this->request->getPost('deposit') ? '1' : '0',
						"trade"   => $this->request->getPost('trade') ? '1' : '0',
						"pay_mode"   => $this->request->getPost('pay_mode'),
						"pay_status"   => $this->request->getPost('pay_status'),
						"coin_type"   => $this->request->getPost('coin_type'),
						"buycount"   => $this->request->getPost('buycount'),
						"increase_percentage"   => $this->request->getPost('inc_per'),
						"sellcount"   => $this->request->getPost('sellcount'),
						"decrease_percentage"   => $this->request->getPost('dec_per'),
						"coins_per"   => $this->request->getPost('coins_per'),
						"arbit_status"   => $this->request->getPost('arbit_status'),
						"min_amt"   => $this->request->getPost('min_amt'),
						"max_amt"   => $this->request->getPost('max_amt'),
						"int_rate"   => $this->request->getPost('int_rate'),
						"duration"   => $this->request->getPost('duration'),
						"payout_peroid"   => $this->request->getPost('payout_peroid'),
						"ret_balance"   => $this->request->getPost('ret_balance'),
						"buyback"   => $this->request->getPost('buyback'),
						"buy_fees"   => $this->request->getPost('buy_fees'),
						"buydays"   => $this->request->getPost('buydays')
					);
					$site_data = array_merge($sitedata, $postget);
					
					$update_status_logo = $this->db->table('coin_info')->where('coid',$this->request->getPost('coin_id'))->update($site_data);
				}
				
				if($update_status_logo)
				{
					$session = \Config\Services::session();
					$session->setFlashData('success_message', lang('language_lang.admin_list_add_success'));
					return redirect()->to('admin/finance/listing');
				}
				else
				{
					$session = \Config\Services::session();
					$session->setFlashData('error_message', lang('language_lang.admin_list_add_fail'));
					return redirect()->to('admin/finance/listing');
				}	
			}
		}
		// echo view('user/list',$this->data);		

		echo view('admin/finance/listadd',$this->data);
	}



	public function declinedeposit() {
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);

		$this->data['page_title'] = lang('language_lang.canceled_deposit_title');

		$this->data['module_name'] = 'finance';

		$condition = "history.type = 'deposit_req' AND history.is_delete = '1'";
		$this->data['history'] = $this->finance_model->GetTransactions($condition);

		echo view('admin/finance/canceldeposit',$this->data);
	}


	public function depositpay() 
	{
		
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);

		$this->data['page_title'] = lang('language_lang.pen_deposit_title');

		$this->data['module_name'] = 'finance';

		$condition = "history.type = 'deposit_req' AND history.is_delete = '1'";
		$this->data['history'] = $this->common_model->GetResults('deposit_address');

		echo view('admin/finance/depositpay',$this->data);
	}

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

		$myencrypt = new MyEncrypt;
		$historyid = $myencrypt->decode($this->request->getPost('id'));
		$hash=$this->request->getPost('hash');
		if($hash!='')
		{
			$condition = "id = '".$historyid."'";
			$history_data = $this->common_model->GetRow('deposit_address', $condition);
			$payment_id = $history_data->payment_id;
			$uusersid = $history_data->uusersid;
			$user = $this->common_model->GetUser($uusersid);
		    $useremail = $user->email; 
		    $fullname = $user->fullname;
		    $ac_mode=$history_data->ac_mode;
		    $coinid=$history_data->currency;
		    $condition = "coid ='".$coinid."'";
			$cointable = $this->common_model->GetRow('coin_info',$condition);
			$currency=$cointable->coin_symbol;
			$this->data['history']=$history_data;
			if($ac_mode=='1')
	    	{
		    	// payout is success
				$withdraw_data = array(
					'balance' => "0",
					'hash' =>$hash
					
				);
				$this->db->where('id',$historyid);
				$query_status = $this->db->update('deposit_address',$withdraw_data);

				$session = \Config\Services::session();
				$session->setFlashData('success_message', lang('language_lang.payout_method_success_message'));
				echo 1;
				
			}
		}
		else
		{
			$session = \Config\Services::session();
			$session->setFlashData('error_message', lang('language_lang.payout_method_error_message'));
			echo 0;
			
		}


	}


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

		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);

		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);

		$this->data['page_title'] = lang('language_lang.canceled_deposit_title');
		$this->data['module_name'] = 'finance';

		$condition = "market_currency = '1'";
		$this->data['coin_info'] = $this->common_model->GetResults('coin_info',$condition);
		echo view('admin/finance/market',$this->data);
	}

	public function Deleterequest($id='')
	{
		$this->db = db_connect();
	    $id = $this->request->uri->getSegment(4); 
	   
		$historyid = $id;       
        $condition = "historyid = '".$historyid."'";
		$delete_depositstatus = $this->db->query("delete from history where historyid='".$historyid."'");

		if($delete_depositstatus) {
			$session = \Config\Services::session();
			$session->setFlashData('success_message', lang('language_lang.pending_depo_delete_success_message'));
			return redirect()->to('admin/finance/pendingdeposit');
		} else {
			$session = \Config\Services::session();
			$session->setFlashData('error_message', lang('language_lang.pending_depo_delete_error_message'));
			return redirect()->to('admin/finance/pendingdeposit');
		}
	}


	public function Deletepurchase($id)
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$myencrypt = new MyEncrypt;
		$historyid = $myencrypt->decode($id);
        $condition = "depositid = '".$historyid."'";
		$this->db->query("delete from deposit where depositid='".$historyid."'");
		$session = \Config\Services::session();
		$session->setFlashData('success_message', lang('language_lang.pending_pur_delete_success_message'));	
		return redirect()->to('admin/finance/pendingpurchase');
	}

	public function Deletetrade($id)
	{
		$myencrypt = new MyEncrypt;
		$historyid = $myencrypt->decode($id);
        $condition = "cid = '".$historyid."'";
		$this->db->query("update exchange set status='4' where cid='".$historyid."'");
		$session = \Config\Services::session();
		$session->setFlashData('success_message', lang('language_lang.lbl_trade_success'));	
		return redirect()->to('admin/finance/trade');
	}


	public function Deletearbit($id)
	{
		$myencrypt = new MyEncrypt;
		$historyid = $myencrypt->decode($id);
        /*$condition = "cid = '".$historyid."'";
		$this->db->query("update exchange set status='4' where cid='".$historyid."'");*/

		$condition = "id = '".$historyid."'";
		$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->insert("history",$insert_data);

		}
		$session = \Config\Services::session();
		$session->setFlashData('success_message', lang('language_lang.lbl_arbit_success'));	
		return redirect()->to('admin/finance/arbit');
	}


	public function Deletebuy($id)
	{
		$myencrypt = new MyEncrypt;
		$historyid = $myencrypt->decode($id);
		$this->db->query("delete from exchange cid='".$history."'");
		$session = \Config\Services::session();
		$session->setFlashData('success_message', lang('language_lang.lbl_buyback_success'));	
		return redirect()->to('admin/finance/buybacklist');

	}


	public function approvebuy()
	{
		$id=$this->uri->segment(4);
		$hash=$this->uri->segment(5);
		$myencrypt = new MyEncrypt;
		$historyid = $myencrypt->decode($id);
		echo "update exchange set status='3',ret_amt='".$hash."' where cid='".$historyid."'";
		exit;
		$this->db->query("update exchange set status='3',ret_amt='".$hash."' where cid='".$historyid."'");
		$session = \Config\Services::session();
		$session->setFlashData('success_message', lang('language_lang.lbl_buyback_success'));
		return redirect()->to('admin/finance/buybacklist');
		
	}

	public function approvetrade($id)
	{
		
		// print_r($id);
		// exit();

		$myencrypt = new MyEncrypt;
		$historyid = $myencrypt->decode($id);
        
		// echo $historyid;
		// exit();


        $condition = "cid = '".$historyid."'";

		$this->db->query("update exchange set status='3' where cid='".$historyid."'");
		
		


		$session = \Config\Services::session();
		$session->setFlashData('success_message', lang('language_lang.lbl_trade_success'));	
		return redirect()->to('admin/finance/trade');
	}


	public function trade()
	{
	
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);
		$this->data['page_title'] = lang('language_lang.lb_trade_history');
		$this->data['type'] = true;
		$this->data['module_name'] = 'finance';
		$condition="type in('3','4') and status='1'";
		$this->data['history'] = $this->common_model->GetResults('exchange',$condition);

		echo view('admin/finance/trade',$this->data);
	}


	public function buybacklist()
	{
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);
		$this->data['page_title'] = lang('language_lang.lbl_buylist');
		$this->data['type'] = true;
		$this->data['module_name'] = 'finance';
		$condition="exchange_mode = '1'";
		$this->data['history'] = $this->common_model->GetResults('exchange',$condition);
		

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

		// echo $this->db->last_query();
		// exit();

		echo view('admin/finance/buybacklist',$this->data);
	}



	public function arbit()
	{
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);
		$this->data['page_title'] = lang('language_lang.menu_ex_aclist1');
		$this->data['type'] = true;
		$this->data['module_name'] = 'finance';
		$condition="";
		$this->data['history'] = $this->common_model->GetResults('arbit_fund',$condition);
		echo view('admin/finance/arbit',$this->data);
	}

	public function view_arbit_plan(){
		if($this->request->getPost('id')){
			$result = $this->common_model->get_plan_details($this->request->getPost('id'));
			$commission = explode('-', $result['commission']);
			if(!empty($result)){
				$template = "";
				 if($result['freelance_bonus_status'] == 1){
                $template .='<div class="col-lg-12 ">
                              <div class="form_block">
                                <label class="col-lg-5" >Prelaunch Bonus Percentage</label>
                                  <div class="col-lg-1"> : </div>
                                  <div class="col-lg-6">
                                   <label>'.$result['freelance_bonus_perc'].'<span style="color:blue;">%</span></label>
                                  </div>
                                </div>
                            <div style="clear:both;"><br></div>';
                        }else{
                        	$template .='<div class="col-lg-12 ">
                              <div class="form_block">
                                <label class="col-lg-5" >Prelaunch Bonus Percentage</label>
                                  <div class="col-lg-1"> : </div>
                                  <div class="col-lg-6">
                                   <label>Not Available</label>
                                  </div>
                                </div>
                            <div style="clear:both;"><br></div>';
                        }
                if($result['direct_bonus_status'] == 1){
                $template .='
                              <div class="form_block">
                                <label class="col-lg-5" >Direct Bonus Percentage</label>
                                  <div class="col-lg-1"> : </div>
                                  <div class="col-lg-6">
                                   <label>'.$result['direct_bonus_perc'].'<span style="color:blue;">%</span></label>
                                  </div>
                                </div>
                            <div style="clear:both;"><br></div>';
                        }else{
                        	$template .='
                              <div class="form_block">
                                <label class="col-lg-5" >Direct Bonus Percentage</label>
                                  <div class="col-lg-1"> : </div>
                                  <div class="col-lg-6">
                                   <label>Not Available</label>
                                  </div>
                                </div>
                            <div style="clear:both;"><br></div>';
                        }
                            $i=0;
                            if(!empty($commission)){
                            foreach ($commission as $key => $value) { $i++;
                            	 $template .='
                              <div class="form_block">
                                <label class="col-lg-5" >Level'.$i.' Commission (%)</label>
                                  <div class="col-lg-1"> : </div>
                                  <div class="col-lg-6">
                                   <label>'.$value.'<span style="color:blue;">%</span></label>
                                  </div>
                                </div>
                            <div style="clear:both;"><br></div>';
                            }}else{
                            	 $template .='
                              <div class="form_block">
                                <label class="col-lg-5" >Level Commission (%)</label>
                                  <div class="col-lg-1"> : </div>
                                  <div class="col-lg-6">
                                   <label>Not Available</label>
                                  </div>
                                </div>
                            <div style="clear:both;"><br></div>';
                            }                
			}
			$template .='</div>';
			print_r($template);
		}
	}

	public function viewarbit($id="")
	{
		$this->uri = service('uri');
		$secret = $id;
		$id=$this->uri->segment(4);
		$session->get('arbit_id',$id);	
		
		if($id)
		{
			$myencrypt = new MyEncrypt;
			$id = $myencrypt->decode($id);			
		}
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_finance')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.arbit')
		);
		$this->data['module_name'] = 'finance';
		$this->data['coin_id'] = $id;
		if($id!="")
		{	
			$condition = "coid = '".$id."'";
			$this->data['arbit_info'] = $this->common_model->GetResults('arbit_plans',$condition);
		}
		echo view('admin/finance/arbitview',$this->data);
	}

	public function view_arbit_level($arbit_info=""){
		   $template .= '<table id="support_table" class="table display product-overview border-none dataTable no-footer" style="width:70%;border:none !important;border-bottom:none !important;">
                  <thead>
                  <tr>
                    <th>Level</th>
                    <th style="padding-left:60px;">Commission (%)</th>
                    <th style="padding-left:40px;">Action</th>
                  </tr>
                  </thead><div id="dynamic_field" style="display: contents;">';

             if(isset($arbit_info)){
              $commission = explode('-', $arbit_info->commission);
              $a_num = 0;
              $update_num = $a_num +1;
              $a_num_count = count($commission);
              if(!empty($commission)){
                foreach ($commission as $key => $value) {
           $template .= '<tbody id="row'.$update_num.'">
      <tr style="border:none;"><input type="hidden" name="a_num_count" id="a_num_count" value="'.$a_num_count.'">
        <td width="31%">Level '.$update_num.'</td>
        <td> <input type="text" style="width:150px;" id="commission" class="form-control" name="commission[]" value="'.$commission[$a_num].'"> 
        </td>';
        if($a_num == 0){
        $template .='<td><a href="javascript:;" onclick="addEvent();" class="btn btn-primary" style="padding-left:37px;padding-right:37px;">Add</a></td>';
      }else{
        $template .='<td><a href="javascript:;" onclick="removeEvent('.$update_num.');" class="btn btn-primary" style="padding-left:37px;padding-right:37px;">Remove</a></td>';
      }
      $template .= '</tr>
    </tbody></div>';
  } $a_num++;
            }
             $template .='</table>';
          }
           else {
            $id = $arbit_info->id;
             $template .= '<input type="hidden" name="a_num_count" id="a_num_count" value="1"><tbody id="row1" >
      <tr style="border:none;">
        <td width="31%">Level 1</td>
        <td> <input type="text" style="width:150px;" id="commission" class="form-control" name="commission[]"> 
        </td>
        <td><a href="javascript:;" onclick="addEvent('.$id.');" class="btn btn-primary" style="padding-left:37px;padding-right:37px;">Add</a></td>
      </tr>
    </tbody>';
    $template .='</table>';
          }
          print_r($template);
	}

	public function addarbit($id="")
	{
		$secret = $this->input->get('var');
		$id=$this->uri->segment(4);
		$id1=$this->uri->segment(4);
		if($id)
		{
			$myencrypt = new MyEncrypt;
			$id = $myencrypt->decode($id);			
			$this->data['ip_coinid'] = $myencrypt->decode($id1);			
		}
		if($this->input->get('var'))
		{
			$myencrypt = new MyEncrypt;
			$this->data['ip_coinid'] = $myencrypt->decode($this->input->get('var'));	
			//$this->dat['ip_coinid']=$session->get('arbit_id');		
		}	
		$myencrypt = new MyEncrypt;
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_arbit')
		);
		
		$this->data['module_name'] = 'finance';
		$this->data['id'] = $id;

		if($id!="")
		{	
			$condition = "id = '".$id."'";  
			$this->data['arbit_info'] = $this->common_model->GetRow('arbit_plans',$condition);
		}else{
			$this->data['arbit_info'] = "";
		}
        
        if($this->data['arbit_info'] == "")			
		{
			$this->form_validation->set_rules('plan_name', lang('language_lang.lbl_plan_name'), 'trim|required');
			$this->form_validation->set_rules('amount', lang('language_lang.lbl_arbit_amount'), 'trim|required');
			$this->form_validation->set_rules('profit', lang('language_lang.lbl_arbit_profit'), 'trim|required');
			$this->form_validation->set_rules('duration', lang('language_lang.lbl_arbit_duration'), 'trim|required');
			$this->form_validation->set_rules('payout_peroid', lang('language_lang.lbl_arbit_payperiod'), 'trim|required');
			$this->form_validation->set_rules('freelance_status', lang('language_lang.lbl_freelance_status'), 'trim|required');
			$this->form_validation->set_rules('direct_status', lang('language_lang.lbl_direct_status'), 'trim|required');
			$this->form_validation->set_rules('level_comm_status', lang('language_lang.lbl_level_comm_status'), 'trim|required');
			if($this->form_validation->run() == TRUE)
			{
				
				

				$data_to_store['plan_name'] = $this->request->getPost('plan_name');
				//$data_to_store['coid'] = $this->request->getPost('coin_id');
				$data_to_store['coid'] = $myencrypt->decode($session->get('arbit_id'));
				
				$data_to_store['amount'] = $this->request->getPost('amount');
				$data_to_store['profit'] = $this->request->getPost('profit');
				$data_to_store['duration'] = $this->request->getPost('duration');
				$data_to_store['payout_peroid'] = $this->request->getPost('payout_peroid');
				if($this->request->getPost('freelance_status') == 1)
				{
					$data_to_store['freelance_bonus_perc'] = $this->request->getPost('freelance_bonus_perc');
				}
				if($this->request->getPost('direct_status') == 1)
				{
					$data_to_store['direct_bonus_perc'] = $this->request->getPost('direct_bonus_perc');
				}
				if($this->request->getPost('level_comm_status') == 1)
				{
					$data_to_store['commission'] = implode('-', $this->request->getPost('commission'));
				}
				$data_to_store['direct_bonus_status'] = $this->request->getPost('direct_status');
				$data_to_store['freelance_bonus_status'] = $this->request->getPost('freelance_status');
				$data_to_store['level_comm_status'] = $this->request->getPost('level_comm_status');
				$data_to_store['status'] = "1";
				$data_to_store['created_date'] = time();
				$db_duplicate = $this->common_model->get_arbit_duplicate($data_to_store);
				if($db_duplicate <= 0)
				{
					$update_status_logo = $this->db->insert('arbit_plans',$data_to_store);
					// echo $this->db->last_query();
					// exit();

					if($update_status_logo)
					{
						$session = \Config\Services::session();
						$session->setFlashData('success_message', lang('language_lang.admin_arbit_add_success'));
						return redirect()->to('admin/finance/viewarbit/'.$secret);
					}
					else
					{
						$session = \Config\Services::session();
						$session->setFlashData('error_message', lang('language_lang.admin_arbit_add_fail'));
						return redirect()->to('admin/finance/viewarbit/'.$secret);
					}		
				}
				else
				{
					$session = \Config\Services::session();
					$session->setFlashData('error_message',lang('language_lang.dup_arbit_insert'));
				}
			}
		}
		else
		{

			$this->form_validation->set_rules('plan_name', lang('language_lang.lbl_plan_name'), 'trim|required');
			$this->form_validation->set_rules('amount', lang('language_lang.lbl_arbit_amount'), 'trim|required');
			$this->form_validation->set_rules('profit', lang('language_lang.lbl_arbit_profit'), 'trim|required');
			$this->form_validation->set_rules('duration', lang('language_lang.lbl_arbit_duration'), 'trim|required');
			$this->form_validation->set_rules('payout_peroid', lang('language_lang.lbl_arbit_payperiod'), 'trim|required');
			$this->form_validation->set_rules('direct_status', lang('language_lang.lbl_direct_status'), 'trim|required');
			$this->form_validation->set_rules('level_comm_status', lang('language_lang.lbl_level_comm_status'), 'trim|required');
			if($this->form_validation->run() == TRUE)
			{

				

				$data_to_store['plan_name'] = $this->request->getPost('plan_name');
				//$data_to_store['coid'] = $this->request->getPost('coin_id');
				$data_to_store['coid'] = $myencrypt->decode($session->get('arbit_id'));
				$data_to_store['amount'] = $this->request->getPost('amount');
				$data_to_store['profit'] = $this->request->getPost('profit');
				$data_to_store['duration'] = $this->request->getPost('duration');
				$data_to_store['payout_peroid'] = $this->request->getPost('payout_peroid');
				if($this->request->getPost('freelance_status') == 1)
				{
					$data_to_store['freelance_bonus_perc'] = $this->request->getPost('freelance_bonus_perc');
				}
				if($this->request->getPost('direct_status') == 1)
				{
					$data_to_store['direct_bonus_perc'] = $this->request->getPost('direct_bonus_perc');
				}
				if($this->request->getPost('level_comm_status') == 1)
				{
					$data_to_store['commission'] = implode('-', $this->request->getPost('commission'));
				}
				$data_to_store['freelance_bonus_status'] = $this->request->getPost('freelance_status');
				$data_to_store['direct_bonus_status'] = $this->request->getPost('direct_status');
				$data_to_store['level_comm_status'] = $this->request->getPost('level_comm_status');
				$data_to_store['status'] = "1";
				$data_to_store['created_date'] = time();
				$db_duplicate = $this->common_model->get_arbit_duplicate($data_to_store);

				$this->db->where('id',$this->request->getPost('coin_id'));
				$update_status_logo = $this->db->update('arbit_plans',$data_to_store);
		    	if($update_status_logo)
				{
					$id1 = $session->get('arbit_id');	
					$session = \Config\Services::session();
					$session->setFlashData('success_message', lang('language_lang.admin_arbit_add_success'));
					return redirect()->to('admin/finance/viewarbit/'.$id1);
				}
				else
				{
					$id1 = $session->get('arbit_id');
					$session = \Config\Services::session();
					$session->setFlashData('error_message', lang('language_lang.admin_arbit_add_fail'));
					return redirect()->to('admin/finance/viewarbit/'.$id1);
				}		
				
			}
			else
			{

			}

				
		}
		echo view('admin/finance/arbitadd',$this->data);  
	}







	public function approverequest($id='')
	{
		$CommonModel = model('CommonModel');
        $this->common_model = model('CommonModel');
		$this->db = db_connect();
		$id = $this->request->uri->getSegment(4); 
	   
		
		$historyid = $id;
		$condition = "historyid = '".$historyid."'";
		$deposit = $this->common_model->GetRow('history',$condition);	
	

		$data = array(
			'type' => 'deposit',
			 'description' => 'deposit made successfully'
		);
       
		//$this->db->where('historyid',$historyid);
		//$this->db->update('history',$data);

		$query_status = $this->db->table('history')->where('historyid', $historyid)->update($data);

		$update_deposit='1';
		if($update_deposit) {

			

			$session = \Config\Services::session();
			$session->setFlashData('success_message', lang('language_lang.pendingdepapprove_success_message'));
			return redirect()->to('admin/finance/pendingdeposit');
		} else {
			$session = \Config\Services::session();
			$session->setFlashData('error_message', lang('language_lang.pendingdepapprove_error_message'));
			return redirect()->to('admin/finance/pendingdeposit');
		}

	}

	public function approvepurchase($id){

		$myencrypt = new MyEncrypt;
		$historyid = $myencrypt->decode($id);
		$condition = "depositid = '".$historyid."'";
		$deposit = $this->common_model->GetRow('deposit',$condition);
		$userid= $deposit->uusersid;

		$user = $this->common_model->GetUser($userid);

       	$refer_id=$user->referral_id;


       	$comm = new commission();
		$matrix_status = $comm->setbinarymatrix($userid,$refer_id);

		

		$user_data = array(
        	'reg_payment' => '1'
		);


        $this->db->where('uusersid',$userid);
		$update_user = $this->db->update('uusers',$user_data);

		$deposit_data = array(
        	'status' => 'active'
		);

		$this->db->where('depositid',$deposit->depositid);
		$update_deposit = $this->db->update('deposit',$deposit_data);

		if($update_deposit) 
		{
			$session = \Config\Services::session();
			$session->setFlashData('success_message', lang('language_lang.pendingpurpapprove_success_message'));
			return redirect()->to('admin/finance/pendingpurchase');
		} 
		else 
		{
			$session = \Config\Services::session();
			$session->setFlashData('error_message', lang('language_lang.pendingpurapprove_error_message'));
			return redirect()->to('admin/finance/pendingpurchase');
		}

	}

	public function Canceldeposit($id)
	{
		if($id) {

			$myencrypt = new MyEncrypt;
			$historyid = $myencrypt->decode($id);
	        
	        $condition = "historyid = '".$historyid."'";
			$deposit = $this->common_model->GetRow('history',$condition);
			
			$condition = "depositid = '".$deposit->depositid."' AND type = 'interest' ";
			$check_history = $this->common_model->GetResults('history', $condition);

			$deposit_data = $this->common_model->getDepositData($deposit->depositid);
			

			if(!$check_history && $deposit_data)  {
				
				if($deposit_data->rtn_principal_status == "1") 
				{
					
		            $return_amount = $deposit_data->amount * ($deposit_data->rtn_principal / 100 );

					$history_data = array(
			            "uusersid" 	=> $deposit_data->uusersid,
			            "amount"	=> $return_amount,
			            "type"		=> "release_deposit",
			            "description"	=> "Close deposit from admin",
			            "date"     =>  date('Y-m-d H:i:s'),
			            "payment_id"    =>  $deposit_data->payment_id,
			            "transactionid" => "TRAN".strtoupper(uniqid()),
			            "depositid" =>  $deposit_data->depositid
		        	);

					$query_status = $this->db->insert('history',$history_data);

					$close_deposit_data = array(
		                'run_date' =>  date('Y-m-d H:i:s'),
		                'status'  =>   "matured"
		            );
		            $close_deposit_data1 = array(
		                'is_delete'  =>   "1"
		            );
		            $this->db->where('depositid',$deposit_data->depositid);
		            $query_status = $this->db->update('deposit',$close_deposit_data);
		            $this->db->where('depositid',$deposit_data->depositid);

		            $query_status1 = $this->db->update('history',$close_deposit_data1);
		            
				} else {
					
					$history_data = array(
			            "uusersid" 	=> $deposit_data->uusersid,
			            "amount"	=> '0',
			            "type"		=> "release_deposit",
			            "description"	=> "Close deposit from admin",
			            "date"     =>  date('Y-m-d H:i:s'),
			            "payment_id"    =>  $deposit_data->payment_id,
			            "transactionid" => "TRAN".strtoupper(uniqid()),
			            "depositid" =>  $deposit_data->depositid
		        	);

					$query_status = $this->db->insert('history',$history_data);
					
					$close_deposit_data = array(
		                'run_date' =>  date('Y-m-d H:i:s'),
		                'status'  =>   "matured"
		            );
		            $close_deposit_data1 = array(
		                'is_delete'  =>   "1"
		            );
		            $this->db->where('depositid',$deposit_data->depositid);
		            $query_status = $this->db->update('deposit',$close_deposit_data);
		            $this->db->where('depositid',$deposit_data->depositid);

		            $query_status1 = $this->db->update('history',$close_deposit_data1);

		        
				}

				if($query_status) {
					$session = \Config\Services::session();
					$session->setFlashData('success_message', lang('language_lang.cancel_deposit_success_message'));
					return redirect()->to('admin/history/deposit');
				} else {
					$session = \Config\Services::session();
					$session->setFlashData('error_message', lang('language_lang.cancel_deposit_error_message'));
					return redirect()->to('admin/history/deposit');
				}

			} else {

				if($deposit_data) {

					$history_data = array(
			            "uusersid" 	=> $deposit_data->uusersid,
			            "amount"	=> $deposit_data->amount,
			            "type"		=> "release_deposit",
			            "description"	=> "Close deposit from admin",
			            "date"     =>  date('Y-m-d H:i:s'),
			            "payment_id"    =>  $deposit_data->payment_id,
			            "transactionid" => "TRAN".strtoupper(uniqid()),
			            "depositid" =>  $deposit_data->depositid
		        	);
					
					$query_status = $this->db->insert('history',$history_data);
					
					$close_deposit_data = array(
		                'run_date' =>  date('Y-m-d H:i:s'),
		                'status'  =>   "matured"
		            );
		            $this->db->where('depositid',$deposit_data->depositid);
		            $query_status = $this->db->update('deposit',$close_deposit_data);
		            $close_deposit_data1 = array(
		                'is_delete'  =>   "1"
		            );
		            $this->db->where('depositid',$deposit_data->depositid);

		            $query_status1 = $this->db->update('history',$close_deposit_data1);

					$session = \Config\Services::session();
					$session->setFlashData('error_message', lang('language_lang.cancel_deposit_error_message'));
					return redirect()->to('admin/history/deposit');
				} else {
							 $close_deposit_data1 = array(
		                'is_delete'  =>   "1"
		            );

			   		$this->db->where('depositid',$deposit->depositid);

		            $query_status1 = $this->db->update('history',$close_deposit_data1);
		          
					$session = \Config\Services::session();
					$session->setFlashData('success_message', lang('language_lang.cancel_deposit_success_message'));
					return redirect()->to('admin/history/deposit');
				}
			}
		}
		else
		{	      
			$session = \Config\Services::session();
			$session->setFlashData('error_message', lang('language_lang.cancel_deposit_error_message'));
			return redirect()->to('admin/history/deposit');
		}
	}

	
			

	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 changeStatus() {
		$this->db = db_connect();
		$session = \Config\Services::session();
		$session = session();

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

			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($this->request->getPost('id'));
		
			$user_data = array(
				"status" => '2'
			);
			$update_status = $this->db->table('coin_info')->where('coid',$uusersid)->update($user_data);

			if($update_status){
				$session = \Config\Services::session();
				$session->setFlashData('success_message', lang('language_lang.coin_default_success'));
				echo 1;
				// return redirect()->to('admin/users');
			} else {
				$session = \Config\Services::session();
				$session->setFlashData('error_message', lang('language_lang.coin_default_error'));
				// return redirect()->to('admin/users');
				echo 0;
			}
		}
	}	
	
	public function changemarket() {
		$session = \Config\Services::session();
		$session = session();
		$this->db = db_connect();

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

			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($this->request->getPost('id'));
		
			$user_data = array(
				"market_status" => '0'
			);
			$update_status = $this->db->table('coin_info')->where('coid',$uusersid)->update($user_data);
			if($update_status){
				$session = \Config\Services::session();
				$session->setFlashData('success_message', lang('language_lang.market_default_success'));
				echo 1;
				// return redirect()->to('admin/users');
			}
			else
			{
				$session = \Config\Services::session();
				$session->setFlashData('error_message', lang('language_lang.market_default_error'));
				// return redirect()->to('admin/users');
				echo 0;
			}
		}
	}	

	public function marketdelete($id="")
	{
		$session = \Config\Services::session();
		$session = session();
		$this->db = db_connect();
		$myencrypt = new MyEncrypt;
		$uusersid = $myencrypt->decode($id);	

		$user_data = array(
			"market_currency" => '0',
			"market_status" => '0'
		);
		


		$update_status = $this->db->table('coin_info')->where('coid',$uusersid)->update($user_data);

		if($update_status)
		{
			$session = \Config\Services::session();
			$session->setFlashData('success_message', lang('language_lang.market_default_success'));
			// echo 1;
			return redirect()->to('admin/finance/market');
		}
		else
		{
			$session = \Config\Services::session();
			$session->setFlashData('error_message', lang('language_lang.market_default_error'));
			// return redirect()->to('admin/users');
			return redirect()->to('admin/finance/market');
		}
	}

	public function arbit_plan_delete($id="")
	{
        $secret = $id;
		$myencrypt = new MyEncrypt;
		$id = $myencrypt->decode($id);	
		$update_status=$this->db->query("delete from arbit_plans where id='$id'");
		if($update_status)
		{
			$session = \Config\Services::session();
			$session->setFlashData('success_message', lang('language_lang.arbit_delete_default_success'));
			// echo 1;
			return redirect()->to('admin/finance/viewarbit/'.$secret);
		}
		else
		{
			$session = \Config\Services::session();
			$session->setFlashData('error_message', lang('language_lang.arbit_delete_default_error'));
			// return redirect()->to('admin/users');
			return redirect()->to('admin/finance/viewarbit/'.$secret);
		}
	}

	public function mark_delete($id="")
	{
		$this->db = db_connect();
		$session = \Config\Services::session();
		$session = session();
		$myencrypt = new MyEncrypt;
		$uusersid = $myencrypt->decode($id);	
		$update_status=$this->db->query("delete from coin_info where coid='$uusersid'");
		if($update_status)
		{
			$session = \Config\Services::session();
			$session->setFlashData('success_message', lang('language_lang.market_delete_default_success'));
			// echo 1;
			return redirect()->to('admin/finance/listing');
		}
		else
		{
			$session = \Config\Services::session();
			$session->setFlashData('error_message', lang('language_lang.market_delete_default_error'));
			// return redirect()->to('admin/users');
			return redirect()->to('admin/finance/listing');
		}
	}

	public function changemarketstatus()
	{
		$session = \Config\Services::session();
		$session = session();
		$this->db = db_connect();
		if($this->request->getPost('id')) {
			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($this->request->getPost('id'));
		
			$user_data = array(
				"market_status" => '1'
			);
			
			$update_status = $this->db->table('coin_info')->where('coid',$uusersid)->update($user_data);

			if($update_status){
				$session = \Config\Services::session();
				$session->setFlashData('success_message', lang('language_lang.market_default_success'));
				echo 1;
				// return redirect()->to('admin/users');
			} else {
				$session = \Config\Services::session();
				$session->setFlashData('error_message', lang('language_lang.market_delete_default_error'));
				// return redirect()->to('admin/users');
				echo 0;
			}
		}
	}	

	public function changepairstatus()
	{
		if($this->request->getPost('id')) {
			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($this->request->getPost('id'));
		
			$user_data = array(
				"status" => '1'
			);
			$this->db->where('cid',$uusersid);
			$update_status = $this->db->update('currency_pair',$user_data);

			
			if($update_status){
				$session = \Config\Services::session();
				$session->setFlashData('success_message', lang('language_lang.market_default_success'));
				echo 1;
				// return redirect()->to('admin/users');
			} else {
				$session = \Config\Services::session();
				$session->setFlashData('error_message', lang('language_lang.market_delete_default_error'));
				// return redirect()->to('admin/users');
				echo 0;
			}
		}
	}

	public function makepairinactive()
	{
		if($this->request->getPost('id')) {
			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($this->request->getPost('id'));
		
			$user_data = array(
				"status" => '0'
			);
			$this->db->where('cid',$uusersid);
			$update_status = $this->db->update('currency_pair',$user_data);
			if($update_status){
				$session = \Config\Services::session();
				$session->setFlashData('success_message', lang('language_lang.market_default_success'));
				echo 1;
				// return redirect()->to('admin/users');
			} else {
				$session = \Config\Services::session();
				$session->setFlashData('error_message', lang('language_lang.market_delete_default_error'));
				// return redirect()->to('admin/users');
				echo 0;
			}
		}
	}

	


	public function changeinStatus()
	{
		$this->db = db_connect();
		$session = \Config\Services::session();
		$session = session();
		if($this->request->getPost('id'))
		{
			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($this->request->getPost('id'));	
			$user_data = array(
				"status" => '1'
			);
			$update_status = $this->db->table('coin_info')->where('coid',$uusersid)->update($user_data);
			if($update_status)
			{
				$session = \Config\Services::session();
				$session->setFlashData('success_message', lang('language_lang.coin_default_success'));
				echo 1;
				// return redirect()->to('admin/users');
			}
			else
			{
				$session = \Config\Services::session();
				$session->setFlashData('error_message', lang('language_lang.coin_default_error'));
				// return redirect()->to('admin/users');
				echo 0;
			}
		}
	}

	public function addMarket()
	{
		$this->db = db_connect();
		$session = \Config\Services::session();
		$session = session();
		if($this->request->getPost('id'))
		{
			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($this->request->getPost('id'));	
			$user_data = array(
				"market_currency" => '1',
				"market_status" => '1'
			);
			$update_status = $this->db->table('coin_info')->where('coid',$uusersid)->update($user_data);
			if($update_status)
			{
			$session = \Config\Services::session();
			$session->setFlashData('success_message', lang('language_lang.add_market_success'));
				echo 1;
				// return redirect()->to('admin/users');
			}
			else
			{
				$session = \Config\Services::session();
				$session->setFlashData('error_message', lang('language_lang.add_market_failure'));
				// return redirect()->to('admin/users');
				echo 0;
			}
		}
	}			

	public function changeActiveStatus()
	{
		$session = \Config\Services::session();
		$session = session();
		$this->db = db_connect();
		if($this->request->getPost('id'))
		{
			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($this->request->getPost('id'));
			$user_data = array(
				"status" => '1'
			);
	
			$update_status = $this->db->table('coin_info')->where('coid',$uusersid)->update($user_data);
			if($update_status)
			{
				$session = \Config\Services::session();
				$session->setFlashData('success_message', lang('language_lang.coin_default_success'));
				// return redirect()->to('admin/users');
				echo 1;
			}
			else
			{
				$session = \Config\Services::session();
				$session->setFlashData('error_message', lang('language_lang.coin_default_error'));
				// return redirect()->to('admin/users');
				echo 0;
			}
		}		
	}

	function amount_check($str)
	{
		$currency_info = defaultcurrency();
		if(preg_match("/^[0-9.]+$/", $str)) {
			return true;
		} else {
			$this->form_validation->set_message('amount_check', '<p><em class="text-danger">'.lang("language_lang.amount_check").'</em></p>');
			return false;
		}
	}

	public function validate_favimage($str)
	{
		$this->form_validation = \Config\Services::validation();
		$this->load->library('upload');
		$path = './uploads/coins';
		$type = 'gif|jpg|png|jpeg';
		$max_width = '200';
		$max_height = '200';
		$allowed_mime_type_arr = array('jpeg','jpg','png','gif','ico');
		$mime=pathinfo($_FILES['coin_image']['name'], PATHINFO_EXTENSION);
		$mime=strtolower($mime);

        if(isset($_FILES['coin_image']['name']) && $_FILES['coin_image']['name']!="")
        {	
        	
            if(in_array($mime, $allowed_mime_type_arr))
            {
            	$this->upload->initialize($this->set_upload_options($path, $type, $max_width, $max_height));            	
            	if(!$this->upload->do_upload('coin_image'))
            	{		
            		$this->form_validation->setMessage('validate_favimage', '<p><em class="text-danger">'.$this->upload->display_errors().'</em></p>');
					return false;            		
             	}
             	else
             	{
             		unlink('uploads/coins/'.$this->upload->data('file_name'));
             		return true;
             	}
            }
            else
            {
              $this->form_validation->set_message('validate_favimage', '<p><em class="text-danger">Please select only jpeg/gif/jpg/png file.</em></p>');
                return false;
            }
        }
        else
        {
            $this->form_validation->set_message('validate_favimage', 'Please choose a file to upload.');
            return false;
        }
	}

	public function validate_image($str)
	{
		if($str)
		{
			$config['upload_path'] = './content/';
			$config['allowed_types'] = 'pdf';
			$config['encrypt_name'] = TRUE;
			$this->load->library('upload', $config);
			if ( ! $this->upload->do_upload('logo')) {
				$this->form_validation->set_message('validate_image', '<p><em class="text-danger">'.$this->upload->display_errors().'</em></p>');
				return false;
			} else {
			return true;
			}
		}
	}

	private function set_upload_options($path, $type, $max_width, $max_height)
	{   
	    //upload an image options
	    $config = array();
	    $config['upload_path'] = $path;
	    $config['allowed_types'] = $type;
	    $config['max_size'] 	= '0';
	    /*$config['max_width']    = $max_width;
	    $config['max_height']   = $max_height;*/
	    $config['encrypt_name'] = TRUE;
	    $config['overwrite']     = FALSE;
	    return $config;
	}



}

