<?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\Models\Commissions;
use App\Models\Rank_update;

class Users extends BaseController {

	/**
	* 
	* Start 
	* Create Date: 4 July, 2016
	* This controller to manage USER module.
	* Created saravanan.
	* @see http://zhyip.com/
	* Last Updated: 6 Jun, 2017
	* End
	* 
	*/

	public function __construct() {
        $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');
		}
		// admin login only
		if($session->get('admin_login')) {
			$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->finance_model = model('finance_model');
			$this->userdash_model = model('userdash_model');
			// form validation library
			// $this->load->library('form_validation');
			// $this->load->model('finance_model');
			// $this->load->model('userdash_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);	

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

	}

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

	// 
	private function isCookie($values) {
        $session = session();
		$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->set($array);

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

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

		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.users_page_text')
		);
		
		$this->data['module_name'] = 'user';
		//$this->data['users'] = $this->common_model->GetResults('uusers');
		$data['current_uri'] ="active";
        

        //$users_data = $this->common_model->GetResults('uusers');

		$users_data = $this->db->query("select * from uusers where new_entry='0'")->getResult();

		$this->data['users']=$users_data;
        if($users_data) {
	        foreach ($users_data as $row) {
	        	
	        	$balance[] = $this->check_balance($row->uusersid);
	        	$data[] = $row->uusersid;
	        }
	        $this->data['ava_balance'] = $balance;
	    }
        
        $data['current_uri'] = $uri->getSegment(3);
		echo view('admin/users/users',$this->data);

	}

	public function newusers()
	{
		$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.users_page_text')
		);
		
		$this->data['module_name'] = 'user';
		//$this->data['users'] = $this->common_model->GetResults('uusers');
		$data['current_uri'] ="active";
        
        //$users_data = $this->common_model->GetResults('uusers');

		$users_data = $this->db->query("select * from uusers where new_entry='1'")->getResult();

		$this->data['users']=$users_data;

        if($users_data) {
	        foreach ($users_data as $row) {
	        	
	        	$balance[] = $this->check_balance($row->uusersid);
	        	$data[] = $row->uusersid;
	        }
	        $this->data['ava_balance'] = $balance;
	    }
        
        $data['current_uri'] = $uri->getSegment(3);

		echo view('admin/users/users',$this->data);

	}


	public function pending()
	{
		$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.users_page_text')
		);
		
		$this->data['module_name'] = 'user';

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

		$rest=$this->db->query("select * from uusers where proof_verify!='1'");
		$user_det=$rest->getResult();	

		$this->data['users'] =$user_det;


		
		$this->data['current_uri'] = $uri->getSegment(3);



        $users_data = $this->common_model->GetResults('uusers');

        if($users_data) {
	        foreach ($users_data as $row) {
	        	
	        	$balance[] = $this->check_balance($row->uusersid);
	        	$data[] = $row->uusersid;
	        }
	        $this->data['ava_balance'] = $balance;
	    }


        
		echo view('admin/users/users',$this->data);

	}

  public function pending_activation()
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		// echo"<pre>";
		// print_r($session->get());
		// echo"</pre>";
		// die;
		$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.users_page_text')
		);
		
		$this->data['module_name'] = 'user';

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

		$rest=$this->db->query("select * from uusers");
		$user_det=$rest->getResult();



        $i = 0;
		foreach ($user_det as $key => $value) {
		$result = $this->db->query("select * from history where uusersid='".$value->uusersid."' and type='activation' and status = 1")->getRow();
           $active_det[$i] = $value;
        if($result->payment_id){
             $rankid = $this->db->query("select * from uusers_matrix where uusersid = '".$value->uusersid."'")->getRow()->rankid;
             $active_det[$i]->rankname = $this->db->query("select * from rewardsettings where id = '".$rankid."'")->getRow()->rank_name;
        }else{
            $active_det[$i]->rankname = "paid";
        }


		if($result){
             $active_det[$i]->activation= 1;
             if($result->payment_id)
             	$active_det[$i]->pin_activation = 1;
             else
             	$active_det[$i]->pin_activation = 0;
		}else{
			$active_det[$i]->activation= 0;
			$active_det[$i]->pin_activation = 0;
		}
		$i++;
		}

		

		$this->data['users'] =$active_det;


		
		$this->data['current_uri'] = $uri->getSegment(3);



        $users_data = $this->common_model->GetResults('uusers');
        $i=0;
        if($users_data) {
	        foreach ($users_data as $row) {
	        	
	        	$balance[] = $this->check_balance($row->uusersid);
	        	$data[] = $row->uusersid;
	        	$users_data[$i] = $row;
	        	$condition = "uusersid = '".$row->uusersid."' and type = 'activation'";
	        	$result = $this->common_model->GetRow('history',$condition);
	            if($result->payment_id){
                  $users_data[$i]->pin_account = 1;
	            }else{
	            	$users_data[$i]->pin_account = 0;
	            }
	        $i++;
	        }
	        $this->data['ava_balance'] = $balance;
	    }

	    $this->data['ranks'] = $this->db->query("select * from rewardsettings")->getResult();
        
		echo view('admin/users/users',$this->data);

	}

	public function pin_rankupgrade(){
		$session = session();
		$this->db = db_connect();
		$uusersid = $this->request->getPost('uusersid');
		$rank = $this->request->getPost('rank');
		$user_data = array(
				"rankid" => $rank
			);

			$condition = array (
				'uusersid' => $uusersid
			);
$update_status = $this->db->table('uusers_matrix')->where($condition)->update($user_data);
$update_status1 = $this->db->table('uusers')->where($condition)->update($user_data);
			
			if($update_status){
			$session->setFlashData('success_message', "Rank upgraded successfully");
				return redirect()->to('admin/users/pending_activation');
			} else {
				$session->setFlashData('error_message', "Rank upgraded failed");
				return redirect()->to('admin/users/pending_activation');
			}

	}

	public function dataview() {
		$this->data['users'] = $this->common_model->GetResults('uusers');
		echo view('admin/users/dataview',$this->data);
	}

	public function add($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->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.users_page_text')
		);
		$this->data['countries'] = $this->common_model->GetResults('country');
		$this->data['rewards'] = $this->common_model->GetResults('rewardsettings');
		$this->data['questions'] = $this->common_model->GetResults('securityquestion_control');

		$this->data['module_name'] = 'user';
		$this->data['action'] =  'admin/users/add';

		$condition = "payment_key in('status') AND payment_value = 'on'";

		$this->data['payment_list'] = $this->common_model->GetPaymentsName($condition);
		$payment_list = $this->common_model->GetPaymentsName($condition);

		$register_setting = $this->common_model->GetMultiSetting();

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

		if($id) {
			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($id);
			$userinfo=$this->common_model->GetUser($uusersid);
		

		$this->data['user'] = $this->common_model->GetUser($uusersid);


			$condition = "uusersid = '".$uusersid."'";
			$payment_data = $this->common_model->GetResults('uusers_payment', $condition);

			if($payment_data){
			
				foreach ($payment_data as $row) {
			   		$this->data['payment_data'][$row->payment_id] = $row->contents;
			    }
			}
		}


		if($this->request->getPost()) {
            $validation->setRules([
            'firstname' => ['label'=>lang("language_lang.lbl_first_name"),'rules'=>'trim|required|min_length[3]']
            ]);
			// $this->form_validation->set_rules('firstname', lang("language_lang.lbl_first_name"), 'trim|required|min_length[3]|alpha_dash');
			// $this->form_validation->set_rules('lastname', lang("language_lang.lbl_last_name"), 'trim|required|alpha_dash');

			if($this->request->getPost('id')) 
			{
			    
				$myencrypt = new MyEncrypt;
				$uusersid = $myencrypt->decode($this->request->getPost('id'));
				$userinfo=$this->common_model->GetUser($uusersid);
			
				/* $validation->setRules([
            'username' => ['label'=>lang("language_lang.lbl_user_name"),'rules'=>'trim|required|edit_uniques_user['.$uusersid.']'],
            'email' => ['email','rules'=>'trim|required|valid_email|edit_uniques_email['.$uusersid.']']
            ]);*/
            
            	$validation->setRules([
            'username' => ['label'=>lang("language_lang.lbl_user_name"),'rules'=>'trim|required'],
            'email' => ['email','rules'=>'trim|required|valid_email']
            ]);
            
                   
				
			} else {
			$validation->setRules([
            'username' => ['label'=>lang("language_lang.lbl_user_name"),'rules'=>'trim|required|is_unique[uusers.username]'],
            'password' => ['label'=>lang("language_lang.lbl_user_password"),'rules'=>'trim|required|matches[cpassword]'],
            'cpassword' => ['label'=>lang("language_lang.lbl_user_cpassword"),'rules'=>'trim|required'],
            'email' => ['label'=>lang("language_lang.lbl_user_email"),'rules'=>'trim|required|valid_email|is_unique[uusers.email]']
            ]);
				// $this->form_validation->set_rules('username', lang("language_lang.lbl_user_name"), 'trim|required|is_unique[uusers.username]');
				// $this->form_validation->set_rules('password', lang("language_lang.lbl_user_password"), 'trim|required|matches[cpassword]|xss_clean');
				// $this->form_validation->set_rules('cpassword', lang("language_lang.lbl_user_cpassword"), 'trim|required');
				// $this->form_validation->set_rules('email', lang("language_lang.lbl_user_email"), 'trim|required|valid_email|is_unique[uusers.email]');
			}

			// check form validate
			if ($validation->withRequest($this->request)->run() == TRUE) {
				if($this->request->getPost('id')) 
				{
				    
				  
				    
				    if(!empty($this->request->getPost('user_transfer')))
				    {
				        $user_transfer="1";
				    }
				    else
				    {
				        $user_transfer="0";
				    }
				    
				     if(!empty($this->request->getPost('user_withdraw')))
				    {
				        $user_withdraw="1";
				    }
				    else
				    {
				        $user_withdraw="0";
				    }
					$myencrypt = new MyEncrypt;
					$uusersid = $myencrypt->decode($this->request->getPost('id'));
					$fullname = $this->request->getPost('firstname')." ".$this->request->getPost('lastname');
					$useremail = $this->request->getPost('email');
					$userdata = array(
						"username"	    =>	strtolower($this->request->getPost('username')),
						"email"   =>  $this->request->getPost('email'),
						"country"	=>	$this->request->getPost('country'),
						"rankid"	=>	$this->request->getPost('rank'),
						"user_transfer"	=>	$user_transfer,
						"user_withdraw"	=>	$user_withdraw,
						"createdipaddr" => $_SERVER['REMOTE_ADDR']
					);
		
					
					$query_status = $this->db->table('uusers')->where('uusersid',$uusersid)->update($userdata);
					

            	// update security info
					$security_data = array(
						"uusersid"	=>	$uusersid,
						"security_question"	=>	$this->request->getPost('question'),
						"security_answer"	=>	$this->request->getPost('answer'),
					);
					$query_status = $this->db->table('uusers_security')->where('uusersid',$uusersid)->update($security_data);

					// sent mail to user
					$subject = 'Profile Updated';
					$mailid = '4';
					$mail_subject_data = $this->common_model->getMailTemplate($mailid);
					$message  = str_replace('[FIRSTNAME]', $fullname, $mail_subject_data->message);
					$message  = str_replace('#sitename', site_info_lang('site_name',$session->get('langid')), $message);
					
					if($mail_subject_data->status=='1'){
					
						$mail_status = $this->sendmail($useremail, $fullname, $subject, $message,$mail_subject_data->from_mail);
					}
					
				} else {
					$originalpwd = $this->request->getPost('password');
					$fullname = $this->request->getPost('firstname')." ".$this->request->getPost('lastname');
					$password = crypt(urlencode($this->request->getPost('password')),'');
					$useremail = $this->request->getPost('email');

				 	$userdata = array(
						"fullname"	=>	$fullname,
	                    "username"	    =>	strtolower($this->request->getPost('username')), 						
						"password"	=>	$password,
						"email"   =>  $this->request->getPost('email'),
						"country"	=>	$this->request->getPost('country'),
						"phone"	=>	$this->request->getPost('code')." ".$this->request->getPost('phone'),
						"status" => '1',
						"createdate" => date('Y-m-d H:i:s'),
						"createdipaddr" => $this->request->getIPAddress()
					);
					$query_status = $this->db->table('uusers')->insert($userdata);

					$lastuserid = $this->db->insertID();

					if($lastuserid) {

						if($this->request->getPost('payment') == '12') {

							$Beneficiary_Account_Number = $this->request->getPost('Beneficiary_Account_Number');
							$Beneficiary_Bank_Name = $this->request->getPost('Beneficiary_Bank_Name');
							$Routing_Transfer_Number_SWIFT_Code_BIC = $this->request->getPost('Routing_Transfer_Number_SWIFT_Code_BIC');
							$Bank_Address = $this->request->getPost('Bank_Address');
							$Bank_City = $this->request->getPost('Bank_City');
							$Bank_State = $this->request->getPost('Bank_State');
							$Bank_ZipCode = $this->request->getPost('Bank_ZipCode');
							$Bank_Country = $this->request->getPost('Bank_Country');

							$data = array($Beneficiary_Account_Number, $Beneficiary_Bank_Name, 
							$Routing_Transfer_Number_SWIFT_Code_BIC,$Bank_Address, $Bank_City, 
							$Bank_ZipCode, $Bank_State, $Bank_Country);

							$display_data = implode(',', $data);
							$builder = $this->db->table('payment_controls');

							$builder->select('*');
							$builder->where('payment_id',$this->request->getPost('payment'));
							$query = $builder->get();
						    $query2 = $query->getRow();

							$payment_data = array(
								"uusersid"	=>	$lastuserid,
								"payment_id"	=>	$this->request->getPost('payment'),
								"contents"	=>	$display_data,
								"payment_name" => $query2->payment_name
							);

							$query_status = $this->db->table('uusers_payment')->insert($payment_data);
						
						} 

						// update payment info
						foreach ($payment_info as $key => $value) {

							$builder = $this->db->table('payment_controls');
							$builder->select('*');
							$builder->where('payment_id',$key);
							$query = $builder->get();
						    $query2 = $query->getRow();

							$payment_data = array(
								"uusersid"	=>	$lastuserid,
								"payment_id"	=>	$key,
								"contents"	=>	$value,
								"payment_name" => $query2->payment_name
							);
						    
							$query_status = $this->db->table('uusers_payment')->insert($payment_data);

						}
						
						$transpin = crypt(urlencode($this->request->getPost('trans_pin')),'');

						// update security info
						$security_data = array(
							"uusersid"	=>	$lastuserid,
							"changeip"	=>	$this->request->getPost('change_ip'),
							"change_browser"	=>	($this->request->getPost('changebrowser')) ? 'enabled' : 'disabled',
							"security_question"	=>	$this->request->getPost('question'),
							"security_answer"	=>	$this->request->getPost('answer'),
							"trans_pin"	=> $transpin
						);
						$query_status = $this->db->table('uusers_security')->insert($security_data);
						
						// $this->load->library('Commission');
						$comm = new commission();
						$matrix_status = $comm->setforcematrix($lastuserid);
						
						$user = $this->common_model->GetUser($lastuserid);
						
						// sent mail to user
						$link = base_url();
						$subject = 'Account Activated Successfully';
						$mailid = '2';
						$mail_subject_data = $this->common_model->getMailTemplate($mailid);
						$message  = str_replace('[FIRSTNAME]', $user->fullname, $mail_subject_data->message);
						$message  = str_replace('[PASSWORD]', $originalpwd, $message);
						$message  = str_replace('[URL]', $link, $message);
						$message  = str_replace('[EMAIL]', $user->email, $message);
						$message  = str_replace('#sitename', site_info_lang('site_name',$session->get('langid')), $message);
						if($mail_subject_data->status=='1'){

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

				}

				if($query_status) {
				    
					$session->setFlashData('success_message', lang('language_lang.user_success_message'));
					if($userinfo->new_entry=='0')
					    return redirect()->to('admin/users');
					else
					    return redirect()->to('admin/newusers');
				} else {
					$session->setFlashData('error_message', lang('language_lang.user_error_message'));
					return redirect()->to('admin/users');
				}
			
			}
			
		}
		echo view('admin/users/createuser', $this->data);
	}

    public function changecountry(){
		$this->common_model = model('CommonModel');
		$iso2 = $this->request->getPost('id');
		$condition = "iso_2 = '".$iso2."'";
		$countries = $this->common_model->GetRow('country',$condition);
		if($countries!=''){
			echo $countries->CountryCode;
		}
		else{
			echo 0;
		}
	}
	
public function autocomplete()
	{
		$this->db = db_connect();
		
		$session = \Config\Services::session();
		$this->common_model = model('CommonModel');
		$group=$this->request->getPost('usergroup');
		$user_type = $this->request->getPost('user_type');
		$username=$this->request->getPost('bahasa');
		$condition='';
		if($user_type=='0')
		{
			 if($group!='')
			 {
				$condition = 'new_entry = '."'".$group."'";
			 }
			 
		}
		else
		{
			if($group!='')
			{
				$condition = 'new_entry = '."'".$group."'";
			}
			else
			{
				if($user_group=='0')
					$condition = "new_entry = '0'";
				else if($user_group=='1')
					$condition = "new_entry ='1'";
            	
			}
		
		}
		if($condition=='')
			 $condition =" username like '%$username%' ";
		else
			$condition ="$condition and username like '%$username%' ";

		
		/*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>";
		}*/
		$result = $this->common_model->GetResults('uusers',$condition);
		foreach($result as $row )
		{
			$response[] = array("value"=>$row->username,"label"=>$row->username);
		}       
		echo json_encode($response);      

	}

	/*function edit_uniques_user($str,$uusersid)
	{
		// echo $uusersid;exit;
		$this->db->select('username');
		$this->db->from('uusers');
		$this->db->where('uusersid !='.$uusersid);
		$this->db->where('username',$str);

		$query = $this->db->get();
		// echo $this->db->last_query();
		if ($query->num_rows()>0) {
			$this->form_validation->set_message('username_check', '<label class="validation-error-label">This invalid details of %s</label>');
			return false;
		}
		else{
			return true;
		}
	}

	function edit_uniques_email($str,$uusersid)
	{

		$this->db->select('email');
		$this->db->from('uusers');
		$this->db->where('uusersid !='.$uusersid);
		$this->db->where('email',$str);

		$query = $this->db->get();
		if ($query->num_rows()>0) {
			$this->form_validation->set_message('username_check', '<label class="validation-error-label">This invalid details of %s</label>');
			return false;
		}
		else{
			return true;
		}
	}*/
	
	function email_check($str,$uusersid)
	{

		$this->db->select('email');
		$this->db->from('uusers');
		$this->db->where('uusersid !='.$uusersid);
		$this->db->where('email',$str);

		$query = $this->db->get();
		if ($query->num_rows()>0) {
			$this->form_validation->setMessage('username_check', '<label class="validation-error-label">This invalid details of %s</label>');
			return false;
		}
		else{
			return true;
		}
	}

	public function sendmail($useremail, $fullname, $subject, $message,$from_mail) {

		// $this->load->library('My_PHPMailer');
		$session = session();
		$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);
        // print_r($mail);exit;
        if(!$mail->Send()) {
        	// return $mail->ErrorInfo;
        	return false;
        } else {
            return true;
        }
	}

	public function delete($id) {
        $session = session();
		$myencrypt = new MyEncrypt;
		$uusersid = $myencrypt->decode($id);
		$this->db = db_connect();

		// remove user master table
		
		$delete_status1 = $this->db->table('uusers')->where('uusersid',$uusersid)->delete();

		// remove user payment
		$delete_status = $this->db->table('uusers_payment')->where('uusersid',$uusersid)->delete();

		// remove user security
		$delete_status = $this->db->table('uusers_security')->where('uusersid',$uusersid)->delete();

		
		$delete_status = $this->db->table('history')->where('uusersid',$uusersid)->delete();
		$delete_status = $this->db->table('deposit')->where('uusersid',$uusersid)->delete();
		$delete_status = $this->db->table('ticket_conversation')->where('uusersid',$uusersid)->delete();
		$delete_status = $this->db->table('tickets')->where('uusersid',$uusersid)->delete();

		

		if($delete_status1) {
			$session->setFlashData('success_message', lang('language_lang.user_remove_success_message'));
			return redirect()->to('admin/users');
		} else {
			$session->setFlashData('error_message', lang('language_lang.user_remove_error_message'));
			return redirect()->to('admin/users');
		}

	}

	public function changeStatus() {
$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" => '2'
			);
			
			$update_status = $this->db->table('uusers')->where('uusersid',$uusersid)->update($user_data);
			
			if($update_status){
			$session->setFlashData('success_message', lang('language_lang.users_default_success'));
				echo 1;
				// return redirect()->to('admin/users');
			} else {
				$session->setFlashData('error_message', lang('language_lang.users_default_error'));
				// return redirect()->to('admin/users');
				echo 1;
			}
		}
	}

	public function changeActiveStatus() {
	
        $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('uusers')->where('uusersid',$uusersid)->update($user_data);
			
			if($update_status){
				$session->setFlashData('success_message', lang('language_lang.users_default_success'));
				// return redirect()->to('admin/users');
				echo 1;
			} else {
				$session->setFlashData('error_message', lang('language_lang.users_default_error'));
				// return redirect()->to('admin/users');
				echo 1;
			}
		}
	}

		public function changeBotStatus() {
        $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',
				"payment_id" => $this->request->getPost('status')
			);

			$condition = array (
				'uusersid' => $uusersid,
				 'type' => 'activation',
			);

			if($this->request->getPost('status'))
				$message = "Pin account bot deactivated successfully";
			else
				$message = "Bot deactivated successfully";
			
			$update_status = $this->db->table('history')->where($condition)->update($user_data);
			
			if($update_status){
			$session->setFlashData('success_message', $message);
				echo 1;
				// return redirect()->to('admin/users');
			} else {
				$session->setFlashData('error_message', "Bot deactivation failed");
				// return redirect()->to('admin/users');
				echo 0;
			}
		}
	}

	public function changeActiveBotStatus() {

        $session = session();
        $this->db = db_connect();
		if($this->request->getPost('id')) {
			
			
			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($this->request->getPost('id'));
			
			$condition = array (
				'uusersid' => $uusersid,
				 'type' => 'activation'
			);
			$get_status = $this->db->table('history')->where($condition)->get()->getRow();

			

			

			if($get_status){

            $user_data = array(
				"status" => '1',
				"payment_id" => $this->request->getPost('status'),
				"date" => date('Y-m-d h:i:s', strtotime($date. ' + 365 days'))
			);

			$update_status = $this->db->table('history')->where($condition)->update($user_data);

			}
			else{
				

    // String of all alphanumeric character
    $str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  
    // Shuffle the $str_result and returns substring
    // of specified length
    $tnxid =  substr(str_shuffle($str_result), 0, 10);

        $str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  
    // Shuffle the $str_result and returns substring
    // of specified length
    $address =  '0x'.substr(str_shuffle($str_result), 0, 30);


    $tradSets = $this->common_model->GetResults('adminsettings','');

    $date = date('Y-m-d h:i:s',time());


			    $transactionid = "ACT-".$tnxid; 
                if (!$get_status) {

                     $historydata = array(
                        'uusersid' => $uusersid,
                        'amount' => $tradSets[0]->activation_cost,
                        'btc_amount' => $tradSets[0]->activation_cost,
                        'type' => 'Activation',
                        'payment_id' => $this->request->getPost('status'),
                        'description' => 'Member pay for activation',
                        'date' => date('Y-m-d h:i:s', strtotime($date. ' + 365 days')),
                        'transactionid' => $transactionid,
                        'address' => $address,
                        'status' => 1 
                    );

                    

                    $db      = \Config\Database::connect();
                    $history = $db->table('history');
                    $update_status = $history->insert($historydata);

                   
                 
                    $rewardsettings = $this->db->table('rewardsettings');
                    $rewardsettings = $rewardsettings->where('id','4')->get()->getRow();

                    
                    $rank_id =  $rewardsettings->id;

                    $rank_data = array(
                        'rankid' => $rank_id
                    );

                    $uusers = $this->db->table('uusers_matrix');
                    $uusers = $uusers->where('uusersid',$uusersid)->update($rank_data);
                  
                    $uusers = $this->db->table('uusers');
                    $uusers = $uusers->where('uusersid',$uusersid)->update($rank_data);
                 
                    if ($uusers) {

                        $Rank_update = new Rank_update();

                        $Rank_update = $Rank_update->rank_update($uusersid,$tradSets[0]->activation_cost);
                    
                    	if($this->request->getPost('status') == 0){
                    	$Commissions = new Commissions();

                        $description = ' for activation';

                        $amount = $tradSets[0]->activation_cost;

                        $update_status1 = $Commissions->index($uusersid,$amount,$description);
                        }
                       
                
                        // $description = ' for profit';

                        // $Teamreward_provide = $Commissions->teamreaward_check($pay_address->userid,$recvied,$description);
                    }
			}
		}

		    if($this->request->getPost('status'))
				$message = "Pin account bot activated successfully";
			else
				$message = "Bot activated successfully";
			
			
			if($update_status){
				$session->setFlashData('success_message', $message);
				// return redirect()->to('admin/users');
				echo 1;
			} else {
				$session->setFlashData('error_message', "Bot activation failed");
				// return redirect()->to('admin/users');
				echo 1;
			}
		}
	}

	public function view($id) {
		$this->finance_model = model('finance_model');
		$this->userdash_model = model('userdash_model');
		if($id) {
			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($id);
			$this->data['uusersid'] = $uusersid;

			$earnings_type  = "'interest', 'commissions', 'bonus', 'fund_received', 'release_deposit'";
            $expenses_type  = "'reinvest', 'withdrawal', 'withdraw_request', 'penalty', 'fund_send', 'withdraw_fee', 'transfer_fee'";

            date_default_timezone_set("EST");
			$wdate = date('Y-m-d',strtotime('monday this week'));
			$tuesdate = date('Y-m-d',strtotime('tuesday this week'));
			$weddate = date('Y-m-d',strtotime('wednesday this week'));
			$thudate = date('Y-m-d',strtotime('thursday this week'));
			$fridate = date('Y-m-d',strtotime('friday this week'));
			$satdate = date('Y-m-d',strtotime('saturday this week'));
			$sundate = date('Y-m-d',strtotime('sunday this week'));

	            // calculate user earnings 
	        $mon_condition = "uusersid = '".$uusersid."' AND type IN (".$earnings_type.") AND DATE(date)='$wdate'";
	        $this->data['mon_earnings'] = $this->common_model->GetEarnings('history',$mon_condition);
	        $mon_earnings = $this->common_model->GetEarnings('history',$mon_condition);

	        $tues_condition = "uusersid = '".$uusersid."' AND type IN (".$earnings_type.") AND DATE(date)='$tuesdate'";
	        $this->data['tues_earnings'] = $this->common_model->GetEarnings('history',$tues_condition);
	        $tues_earnings = $this->common_model->GetEarnings('history',$tues_condition);

	        $wed_condition = "uusersid = '".$uusersid."' AND type IN (".$earnings_type.") AND DATE(date)='$weddate'";
	        $this->data['wed_earnings'] = $this->common_model->GetEarnings('history',$wed_condition);
	        $wed_earnings = $this->common_model->GetEarnings('history',$wed_condition);

	        $thurs_condition = "uusersid = '".$uusersid."' AND type IN (".$earnings_type.") AND DATE(date)='$thudate'";
	        $this->data['thur_earnings'] = $this->common_model->GetEarnings('history',$thurs_condition);
	        $thur_earnings = $this->common_model->GetEarnings('history',$thurs_condition);

	        $fri_condition = "uusersid = '".$uusersid."' AND type IN (".$earnings_type.") AND DATE(date)='$fridate'";
	        $this->data['fri_earnings'] = $this->common_model->GetEarnings('history',$fri_condition);
	        $fri_earnings = $this->common_model->GetEarnings('history',$fri_condition);

	        $sat_condition = "uusersid = '".$uusersid."' AND type IN (".$earnings_type.") AND DATE(date)='$satdate'";
	        $this->data['sat_earnings'] = $this->common_model->GetEarnings('history',$sat_condition);
	        $sat_earnings = $this->common_model->GetEarnings('history',$sat_condition);

	        $sun_condition = "uusersid = '".$uusersid."' AND type IN (".$earnings_type.") AND DATE(date)='$sundate'";
	        $this->data['sun_earnings'] = $this->common_model->GetEarnings('history',$sun_condition);
	        $sun_earnings = $this->common_model->GetEarnings('history',$sun_condition);


	         // calculate user expenses 
	        $monex_condition = "uusersid = '".$uusersid."' AND type IN (".$expenses_type.") AND DATE(date)='$wdate'";
	        $this->data['mon_expenses'] = $this->common_model->GetEarnings('history',$monex_condition);
	        $mon_expenses = $this->common_model->GetEarnings('history',$monex_condition);

	        $tuesex_condition = "uusersid = '".$uusersid."' AND type IN (".$expenses_type.") AND DATE(date)='$tuesdate'";
	        $this->data['tues_expenses'] = $this->common_model->GetEarnings('history',$tuesex_condition);
	        $tues_expenses = $this->common_model->GetEarnings('history',$tuesex_condition);

	        $wedex_condition = "uusersid = '".$uusersid."' AND type IN (".$expenses_type.") AND DATE(date)='$weddate'";
	        $this->data['wed_expenses'] = $this->common_model->GetEarnings('history',$wedex_condition);
	        $wed_expenses = $this->common_model->GetEarnings('history',$wedex_condition);

	        $thursex_condition = "uusersid = '".$uusersid."' AND type IN (".$expenses_type.") AND DATE(date)='$thudate'";
	        $this->data['thur_expenses'] = $this->common_model->GetEarnings('history',$thursex_condition);
	        $thur_expenses = $this->common_model->GetEarnings('history',$thursex_condition);

	        $friex_condition = "uusersid = '".$uusersid."' AND type IN (".$expenses_type.") AND DATE(date)='$fridate'";
	        $this->data['fri_expenses'] = $this->common_model->GetEarnings('history',$friex_condition);
	        $fri_expenses = $this->common_model->GetEarnings('history',$friex_condition);

	        $satex_condition = "uusersid = '".$uusersid."' AND type IN (".$expenses_type.") AND DATE(date)='$satdate'";
	        $this->data['sat_expenses'] = $this->common_model->GetEarnings('history',$satex_condition);
	        $sat_expenses = $this->common_model->GetEarnings('history',$satex_condition);

	        $sunex_condition = "uusersid = '".$uusersid."' AND type IN (".$expenses_type.") AND DATE(date)='$sundate'";
	        $this->data['sun_expenses'] = $this->common_model->GetEarnings('history',$sunex_condition);
	        $sun_expenses = $this->common_model->GetEarnings('history',$sunex_condition);
	       

	        $mon_Earnings = ($mon_earnings->earnamt) ? $mon_earnings->earnamt : '0';
        	$mon_Expenses = ($mon_expenses->earnamt) ? $mon_expenses->earnamt : '0';
        	$this->data['mon_AvailableBalance'] = $mon_Earnings - $mon_Expenses;

        	$tues_earnings = ($tues_earnings->earnamt) ? $tues_earnings->earnamt : '0';
        	$tues_expenses = ($tues_expenses->earnamt) ? $tues_expenses->earnamt : '0';
        	$this->data['tues_AvailableBalance'] = $tues_earnings - $tues_expenses;

        	$wed_earnings = ($wed_earnings->earnamt) ? $wed_earnings->earnamt : '0';
        	$wed_expenses = ($wed_expenses->earnamt) ? $wed_expenses->earnamt : '0';
        	$this->data['wed_AvailableBalance'] = $wed_earnings - $wed_expenses;

        	$thur_earnings = ($thur_earnings->earnamt) ? $thur_earnings->earnamt : '0';
        	$thur_expenses = ($thur_expenses->earnamt) ? $thur_expenses->earnamt : '0';
        	$this->data['thur_AvailableBalance'] = $thur_earnings - $thur_expenses;

        	$fri_earnings = ($fri_earnings->earnamt) ? $fri_earnings->earnamt : '0';
        	$fri_expenses = ($fri_expenses->earnamt) ? $fri_expenses->earnamt : '0';
        	$this->data['fri_AvailableBalance'] = $fri_earnings - $fri_expenses;

        	$sat_earnings = ($sat_earnings->earnamt) ? $sat_earnings->earnamt : '0';
        	$sat_expenses = ($sat_expenses->earnamt) ? $sat_expenses->earnamt : '0';
        	$this->data['sat_AvailableBalance'] = $sat_earnings - $sat_expenses;

        	$sun_earnings = ($sun_earnings->earnamt) ? $sun_earnings->earnamt : '0';
        	$sun_expenses = ($sun_expenses->earnamt) ? $sun_expenses->earnamt : '0';
        	$this->data['sun_AvailableBalance'] = $sun_earnings - $sun_expenses;
	        
	       
			
			$this->data['user'] = $this->common_model->GetUser($uusersid);

			$this->data['balance'] = $this->check_balance($uusersid);

			$condition4 = "payment_key in('status') AND payment_value = 'on'";
		    $this->data['payment_list'] = $this->common_model->GetPaymentsName($condition4);

		    $paymentlogo_condition = "payment_key in('logo','status')";
		    $payment_data_list = $this->common_model->GetPaymentsName($paymentlogo_condition);
		    $pay_array = array();
				$pay_array1['payment_name'] = '';
				foreach ($payment_data_list as $row) {
					
					if($row->payment_name!=$pay_array1['payment_name']){
						$pay_array1['payment_name'] = $row->payment_name;	
						$pay_array1['payment_logo'] = $row->payment_value;	
					} 
					else {
						$pay_array1['payment_status'] = $row->payment_value;
						$pay_array1['payment_id'] = $row->payment_id;
						$pay_array[]= $pay_array1;
					}
			
				}

		    $this->data['payment_data_list'] = $pay_array;


		    $condition = "uusersid = '".$uusersid."'";
		    $result = $this->common_model->GetRow('uusers',$condition);
		    $payment_data = $this->common_model->GetResults('uusers_payment', $condition);
           
		    $condition6 = "iso_2 = '".$result->country."'";
		   
		    $this->data['countries'] = $this->common_model->GetRow('country',$condition6);

		    $access_condition = "uusers_id = '".$uusersid."'";
		   
		    $this->data['lastaccess'] = $this->common_model->GetResults('uusers_online',$access_condition);

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

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

		    $condition_mature = "history.type = 'release_deposit' and history.uusersid = '".$uusersid."' AND history.is_delete = '0'";
		    $this->data['mature_deposit'] = $this->finance_model->GetTransactions($condition_mature);

		    $condition2 = "history.type = 'deposit' and history.uusersid = '".$uusersid."' AND history.is_delete = '0'";
		    $this->data['deposit'] = $this->finance_model->GetTransactions($condition2);

		    $condition3 = "history.type IN ('withdrawal') and history.uusersid = '".$uusersid."' AND history.is_delete = '0'";
		    $this->data['payout'] = $this->finance_model->GetTransactions($condition3);

		    $condition3 = "history.type IN ('withdraw_request') and history.uusersid = '".$uusersid."' AND history.is_delete = '0'";
		    $this->data['pending_payout'] = $this->finance_model->GetTransactions($condition3);


		    $this->data['all_transaction'] = $this->common_model->GetResults('history',$condition);
            
            $last_condition = "uusersid = '".$uusersid."' ORDER BY `historyid` desc LIMIT 0,6";
		    $this->data['all_lasttransaction'] = $this->common_model->GetResults('history',$last_condition);

		    $earnings_condition = "type IN ('interest', 'commissions') AND";
		    $earnings_condition .= " uusersid = '".$uusersid."'";
		    $this->data['tot_earn'] = $this->userdash_model->MyHistoryData1($earnings_condition);


		    $deposit_condition = "uusersid = '".$uusersid."' AND type IN ('deposit', 'reinvest')";
		    $this->data['total_deposit'] = $this->userdash_model->MyHistoryData1($deposit_condition);

		   

		    $interest_condition = "uusersid = '".$uusersid."' AND type IN ('interest')";
		    $this->data['tot_interest'] = $this->userdash_model->MyHistoryData1($interest_condition);

		    $payout_condition = "uusersid = '".$uusersid."' AND type IN ('withdrawal')";
		    $this->data['total_payouts'] = $this->userdash_model->MyHistoryData1($payout_condition);

		    $pending_payout_condition = "uusersid = '".$uusersid."' AND type IN ('withdraw_request')";
		    $this->data['total_pending_payouts'] = $this->userdash_model->MyHistoryData1($pending_payout_condition);

		    $fund_send_condition = "uusersid = '".$uusersid."' AND type IN ('fund_send')";
		    $this->data['total_fund_send'] = $this->userdash_model->MyHistoryData1($fund_send_condition);

		    $fund_received_condition = "uusersid = '".$uusersid."' AND type IN ('fund_received')";
		    $this->data['total_fund_received'] = $this->userdash_model->MyHistoryData1($fund_received_condition);

		    $bonus_condition = "uusersid = '".$uusersid."' AND type IN ('bonus')";
		    $this->data['total_bonus'] = $this->userdash_model->MyHistoryData1($bonus_condition);

		    $penaly_condition = "uusersid = '".$uusersid."' AND type IN ('penalty')";
		    $this->data['total_penalty'] = $this->userdash_model->MyHistoryData1($penaly_condition);

		    $reff_condition = "referral_id = '".$uusersid."'";
		    $this->data['total_sponser'] = $this->userdash_model->MySponserCount($reff_condition);

		    $reff_comm_condition = "uusersid = '".$uusersid."' AND type IN ('commissions')";
		    $this->data['total_ref_comm'] = $this->userdash_model->MyHistoryData1($reff_comm_condition);

		    $reff_condition1 = "referral_id = '".$uusersid."' AND status='1'";
		    $this->data['active_sponser'] = $this->userdash_model->MySponserCount($reff_condition1);

		    $reff_condition2 = "referral_id = '".$uusersid."' AND status='0'";
		    $this->data['inactive_sponser'] = $this->userdash_model->MySponserCount($reff_condition2);
		    
            
		    $this->data['ref_name'] = $this->userdash_model->MySponsersLevel($reff_condition);
            
            // foreach ($ref_name as $row) {
            // 	$referral_name[] = $row->fullname;
            // 	$status[] = $row->status;
            // }
            // $this->data['referrals_full'] = $referral_name;
            // $this->data['referral_status'] = $status;

		    $this->data['sponser_level'] = $this->downlines($uusersid, '0');

			if($payment_data!=''){ 
				foreach ($payment_data as $row) {
					$this->data['payment_data'][$row->payment_id] = $row->contents;
				}
			}
			$this->data['breadcrumbs'] = array();

			$this->data['breadcrumbs'][] = array(
				'text' => lang('language_lang.text_home'),
				'href' => base_url('admin')
			);
			
			$this->data['module_name'] = 'user';
	        
			echo view('admin/users/profile',$this->data);
		} else {
			return redirect()->to('admin/users');
		}
	}


	public function verify($id="") 
	{
		$session = session();
		if($id || $this->request->getPost()) 
		{
			$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.users_page_text')
		);
		$this->data['countries'] = $this->common_model->GetResults('country');
		$this->data['questions'] = $this->common_model->GetResults('securityquestion_control');

		$this->data['module_name'] = 'user';
		$this->data['action'] =  'admin/users/verify';
			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($id);
			$this->data['user'] = $this->common_model->GetUser($uusersid);
			$this->data['uusersid'] = $uusersid;
			$this->data['module_name'] = 'user';
	        if($this->request->getPost('id')) {
	        	$id=$this->request->getPost('id');

	        	$app=$this->request->getPost('user_change_payment');
	        	if($app=='on')
	        		$status='1';
	        	else
	        		$status='2';

				$this->db->query("update uusers set proof_verify='$status' where uusersid='$id'");
				$session->setFlashData('success_message', lang('language_lang.users_default_success'));
				return redirect()->to('admin/users');
				
	        }
			echo view('admin/users/verify',$this->data);
		}
		else
		{
			return redirect()->to('admin/users');
		}
	}


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

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

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

        
        /*$earnings_type  = "'interest', 'commissions', 'bonus', 'fund_received', 'release_deposit'";
        $expenses_type  = "'reinvest', 'withdrawal', 'withdraw_request', 'penalty', 'fund_send', 'withdraw_fee', 'transfer_fee'";

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

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

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

        $Earnings = ($earnings->earnamt) ? $earnings->earnamt : '0';
        $Expenses = ($expenses->earnamt) ? $expenses->earnamt : '0';
        $AvailableBalance = $Earnings - $Expenses;
        
        return ($AvailableBalance) ? $AvailableBalance : '0';*/
        $usd_balance=$this->balance_check($userid,'1');
     

		$btc_balance=$this->balance_check($userid,'2');

		$eth_balance=$this->balance_check($userid,'3');




        
        $earnings_type  = "'interest', 'commissions', 'bonus', 'fund_received', 'Lending Matured'";
        $expenses_type  = "'reinvest', 'withdrawal', 'withdraw_request', 'penalty', 'fund_send', 'withdraw_fee', 'transfer_fee'";

        if($userid) {

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

	        // calculate user expenses
	        $condition1 = "uusersid = '".$userid."' 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;
	        
	        if($AvailableBalance<0)
	        	$AvailableBalance=0;*/

	        $balance=$usd_balance+$eth_balance+$btc_balance+$Earnings-$Expenses;
	        //return $AvailableBalance;
	        return $balance;
			
		} else {
			return 0;
		}
		

	}

	private function balance_check($sender_id,$currency)
	{
		/*$currency_info = defaultcurrency();
		$dep=$this->db->query("select sum(amount) as amt from history where type='deposit' and uusersid='$sender_id' and currency='$currency'");
		$dep_amt=$dep->getResult();
		$deposit_amt=$dep_amt[0]->amt;

		$dep=$this->db->query("select sum(curr_amt) as amt from tokens where type='buy' and uuserid='$sender_id' and currency='$currency'");
		$dep_amt=$dep->getResult();
		$with_amt=$dep_amt[0]->amt;

		$dep=$this->db->query("select sum(curr_amt) as amt from tokens where type='sell' and uuserid='$sender_id' and currency='$currency'");
		$dep_amt=$dep->getResult();
		$buy_amt=$dep_amt[0]->amt;
		$balance=$deposit_amt+$buy_amt-$with_amt;
		if($balance<0)
			$balance='0';

		$currency_check=$currency_info->currency_unit;
		
		if($currency=='1')
			$curr="usd";
		else if($currency=='2')
			$curr=="btc";
		else
			$curr="ETH";

		if(strtolower($currency_check)==strtolower($curr))
		{
			$amount=$balance;

		}
		else
		{
			$currency_check=strtolower($currency_check);
			$curr=strtolower($curr);
			$url = "https://api.cryptonator.com/api/ticker/".$curr."-".$currency_check;
          	$json = file_get_contents($url);
          	$data_api = json_decode($json, TRUE);
          	$data_amts=number_format($data_api['ticker']['price'],6);
          	$amount=$data_amts*$balance;

		}*/

		//return $amount;

	}

	public function resetpassword($id) {
		$this->db = db_connect();
		$session = session();
		$this->common_model = model('CommonModel');
		if($id) {
			$myencrypt = new MyEncrypt;
			$uusersid = $myencrypt->decode($id);
			$user = $this->common_model->GetUser($uusersid);

			$slug = md5($user->uusersid . $user->email . time());
			$reset_data =  array(
				'forgotpwd_authcode' => $slug
				// 'password' => ''
			);
			
			$update_status = $this->db->table('uusers_security')->where('uusersid',$user->uusersid)->update($reset_data);

			if($update_status) {
				$link = base_url('login/activate/'.$slug);

				// $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($mail_data['admin_email'], site_info_lang('site_name',$session->get('langid')));  
		        $mail->AddReplyTo($mail_data['admin_email'],site_info_lang('site_name',$session->get('langid')));
		        
		        $mailid = '18';
		        $mail_subject_data = $this->common_model->getMailTemplate($mailid);
				$message  = str_replace('[FIRSTNAME]', $user->fullname, $mail_subject_data->message);
				$message  = str_replace('[URL]', $link, $message);
				$message  = str_replace('#sitename', site_info_lang('site_name',$session->get('langid')), $message);
				
		        $mail->Subject    = "Reset password";
		        $mail->msgHTML($message);
		        $mail->AltBody    = "Your Password has been reseted Successfully";
		        
		        $mail->AddAddress($user->email, $user->fullname);
		        
		        if(!$mail->Send()) {
		            $session->setFlashData('error_message', $mail->ErrorInfo);
					return redirect()->to('admin/users');
		        } else {
		            // $data["message"] = "Message sent correctly!";
		            $session->setFlashData('success_message', lang('language_lang.reset_user_success_message'));
					return redirect()->to('admin/users');
		        }

				// $session->setFlashData('success_message', lang('language_lang.reset_user_success_message'));
				// return redirect()->to('admin/users');
			}

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

	public function bonus()
	{
         
		if($this->request->getPost()) {

			$user_id = $this->request->getPost('id');

			$myencrypt = new MyEncrypt;
			$id_val = $myencrypt->decode($user_id);
			
			// form validation
			 $validation->setRules([
            'description' => ['label'=>lang("language_lang.description"),'rules'=>'trim|required'],
            'amount' => ['label'=>lang("language_lang.amount"),'rules'=>'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 ($validation->withRequest($this->request)->run() == TRUE) {

            	$bonus_data = array(
					"uusersid" 		=> $id_val,
					"amount"		=>	$this->request->getPost('amount'),
					"type" 			=>  "bonus",
					"description" 	=> $this->request->getPost('description'),
					"date"     		=>  date("Y-m-d h:i:sa"),
					"transactionid" => strtoupper(random_string('alnum', 16))
				);
			
				$query_status = $this->db->table('history')->insert($bonus_data);

                if($query_status) {
					$session->setFlashData('success_message', lang('language_lang.bonus_success_message'));
					return redirect()->to('admin/users');
				} else {
					$session->setFlashData('error_message', lang('language_lang.bonus_error_message'));
					return redirect()->to('admin/users');
				}
            }
			
		} else {
			return redirect()->to('admin/users');
		}

	}

	public function penalty()
	{
         
		if($this->request->getPost()) {

			$user_id = $this->request->getPost('id');

			$myencrypt = new MyEncrypt;
			$id_val = $myencrypt->decode($user_id);
			
			// form validation
		 	$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->form_validation->run() == TRUE) {

            	$penalty_data = array(
					"uusersid" => $id_val,
					"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))
				);
			
				$query_status = $this->db->insert('history',$penalty_data);

                if($query_status) {
					$session->setFlashData('success_message', lang('language_lang.penalty_success_message'));
					return redirect()->to('admin/users');
				} else {
					$session->setFlashData('error_message', lang('language_lang.penalty_error_message'));
					return redirect()->to('admin/users');
				}
           	}
			
		}  else {
			return redirect()->to('admin/users');
		}
		
	}

	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"
		            );
		            $this->db->where('depositid',$deposit_data->depositid);
		            $query_status = $this->db->update('deposit',$close_deposit_data);
		            
				} 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"
		            );
		            $this->db->where('depositid',$deposit_data->depositid);
		            $query_status = $this->db->update('deposit',$close_deposit_data);
		        
				}

				if($query_status) {
					$session->setFlashData('success_message', lang('language_lang.cancel_deposit_success_message'));
					echo 1;
				} else {
					$session->setFlashData('error_message', lang('language_lang.cancel_deposit_error_message'));
					echo 0;
				}

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

					$session->setFlashData('error_message', lang('language_lang.cancel_deposit_error_message'));
					echo 1;
				} else {
					$session->setFlashData('error_message', lang('language_lang.cancel_deposit_error_message'));
					echo 0;
				}
			}

		} else {
			$session->setFlashData('error_message', lang('language_lang.cancel_deposit_error_message'));
			return redirect()->to('admin/history/deposit');
		}
		
	}

	public function Deleterequest($id){

		$myencrypt = new MyEncrypt;
		$historyid = $myencrypt->decode($id);
        
        $condition = "historyid = '".$historyid."'";
		$deposit_data = $this->common_model->GetRow('history',$condition);


		$this->db->where('historyid',$historyid);
		$delete_depositstatus = $this->db->delete('history');

		$this->db->where('depositid',$deposit_data->depositid);
		$delete_depositstatus = $this->db->delete('deposit');

		if($delete_depositstatus) {
			$session->setFlashData('success_message', lang('language_lang.pending_depo_delete_success_message'));
			echo 1;
		} else {
			$session->setFlashData('error_message', lang('language_lang.pending_depo_delete_error_message'));
			echo 0;
		}
		
	}

	public function approverequest($id){

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

		$condition = "historyid = '".$historyid."'";
		$deposit = $this->common_model->GetRow('history',$condition);
		
		$data = array(
			'type' => 'deposit'
		);
        $vue = $this->db->table('history');
		$vue->where('historyid',$historyid);
		$vue->update($data);

		$deposit_data = array(
        	'status' => 'active'
		);
        $builder = $this->db->table('deposit');
        $builder->where('depositid',$deposit->depositid);
		$update_deposit = $builder->update($deposit_data);

		if($update_deposit) {
			$this->load->library('Commission');
			$comm = new commission();
			$this->commission->Commission_calc($deposit->uusersid);
			$session->setFlashData('success_message', lang('language_lang.pendingdepapprove_success_message'));
			echo 1;
		} else {
			$session->setFlashData('error_message', lang('language_lang.pendingdepapprove_error_message'));
			echo 0;
		}

	}
	public function login($id) 
	{
		$session = session();
		$this->common_model = model('CommonModel');
		$this->finance_model = model('finance_model');
		$this->userdash_model = model('userdash_model');
		$myencrypt = new MyEncrypt;
		$select_userid = $myencrypt->decode($id);
        $languageid = ($session->get('user_langid')) ? $session->get('user_langid'): '1';
		$this->data['user'] = $this->common_model->GetUser($select_userid);
		$usersid = $this->db->query("SELECT * FROM uusers WHERE uusersid=$select_userid")->getResult();
		$users_id=$usersid[0];
		if($users_id) 
		{
			$array = array(
				"uusersid" => $users_id->uusersid,
				"exchange" =>'1',
				"user_login" => 1
			);
			$session = \Config\Services::session();
			Session()->set($array);
			$lastaccess = array(
					"uusers_id" => $users_id->uusersid, 
                    "uusers_ip" => $_SERVER['REMOTE_ADDR'],
                    "lastaccess"   => date('Y-m-d H:i:s'),
                    "user_type" => "users"
				);
				$this->db = db_connect();
				$insert_status = $this->db->table('uusers_online')->insert($lastaccess);

				$logincount = array(
					'uuser_login_count'  => '0'
				);
				$this->db = db_connect();
				$query_status = $this->db->table('uusers_security')->where('uusersid', $users_id->uusersid)->update($logincount);
				$condition = "language_name = '".$this->request->getPost('usrlang')."'";
				$act_lang_data = $this->common_model->GetRow("language_controls",$condition);
				//$this->db->where('uusersid',$result->uusersid);
				//$update_status = $this->db->update('uusers_security',$logincount);
                $session->set($array);

                $successlogin = array(
        		'uuserid' => $users_id->uusersid,
        		'ip_address' => $_SERVER['REMOTE_ADDR'],
        		'pages'	=> basename($_SERVER['REQUEST_URI']),
        		'datatime' => date('Y-m-d H:i:s'),
        		'status' => 'success',
        		'language' => $act_lang_data->language_id
        		);
        		//$this->db->insert('login_ip',$successlogin);                 	                  
                if(session()->get('user_last_page'))
				{
					//redirect(session()->get('user_last_page'));
					return redirect()->to('user/dashboard');
				}
				else
				{
					return redirect()->to('user/dashboard');	
				}
		}

		
	}

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

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

}

