<?php
namespace App\Controllers\User;
use App\Views;
use App\Models\CommonModel;
use App\Helpers\site_helper;
use App\Libraries\MyEncrypt;
use App\Libraries\PHPMailer;  
use App\Libraries\My_PHPMailer;
use PHPMailer\PHPMailer\Exception;
use App\Libraries\mathcaptcha;
use App\Models\Strategy;
use App\Models\Strategythird;
use App\Models\Subbin_Strategy;
use Binance;
use App\Models\Commissions;
use App\Models\Rank_update;
use App\Libraries\WalletCoreAPI;
use App\Libraries\Google_authendicator;
error_reporting(0);

class Login extends BaseController {
/**
* 
* Start 
* Create Date: 29 July, 2016
* This controller to manage user login.
* Created karthiga.
* @see http://zhyip.com/
* Last Updated: 29 July, 2016
* End
* 
*/

public function __construct() {
$this->db = db_connect();
$this->session = session();
$myencrypt = new MyEncrypt(true);
$this->common_model = model('CommonModel');
helper('site_helper');
$this->form_validation = \Config\Services::validation();


$status = site_info('site_status');
if($status!='on') {
return redirect()->to('offline');
} 


// form validation library

// custom encryption
// library('MyEncrypt');
}

public function check(){
	// $private_key = "vXzdGnL7Ce4W8QNAaRjpUmElVqbh1Txr";
	// $public_key = "46eed5e5719670719913280eea6f18a4";
	// $amount = 5;
	// $currency = "USDTTRC";
	// $ipn_url = "TRADINGBOT";
	// $address = "TPkkSbX4SvgRJGfNjzH26HhdpCELRugSEz";

	//  $walletcore = new WalletCoreAPI();
 //     $walletcore->Setup($private_key,$public_key);
 //     $result = $walletcore->CreateWithdrawal($amount,$currency,$address,$ipn_url);
 //     echo"<pre>";
 //     print_r($result);
 //     echo"</pre>";
 //     die;
	echo view('user/check');
}

public function okex_check(){
	// $private_key = "vXzdGnL7Ce4W8QNAaRjpUmElVqbh1Txr";
	// $public_key = "46eed5e5719670719913280eea6f18a4";
	// $amount = 5;
	// $currency = "USDTTRC";
	// $ipn_url = "TRADINGBOT";
	// $address = "TPkkSbX4SvgRJGfNjzH26HhdpCELRugSEz";

	//  $walletcore = new WalletCoreAPI();
 //     $walletcore->Setup($private_key,$public_key);
 //     $result = $walletcore->CreateWithdrawal($amount,$currency,$address,$ipn_url);
 //     echo"<pre>";
 //     print_r($result);
 //     echo"</pre>";
 //     die;
	echo view('user/okex_check');
}

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


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

public function removeuser()
{
	$this->db = db_connect();
	$find_user=$this->db->query("select * from uusers ")->getResult();
	foreach ($find_user as $users) 
	{
		if($users->email=='')
		{

			$this->db->query("update uusers set referral_id='1' where referral_id='".$users->uusersid."'");

			$this->db->query("delete from uusers where uusersid='".$users->uusersid."'");

			echo '<pre>';
			print_r($users);
			echo '</pre>';
		}
		
	
	}
}
public function depositverify()
{
    $data = file_get_contents('php://input');
    $jsonData = json_decode($data, true);
    $this->db = db_connect();
    
    
	$lastaccess = array(
		"payment" => $_SERVER['REQUEST_METHOD'], 
		"post_content" =>  json_encode($jsonData, JSON_PRETTY_PRINT),
		"datetime"   => date('Y-m-d H:i:s')
	);
	$this->db = db_connect();
	$insert_status = $this->db->table('ipn_process')->insert($lastaccess);
    echo "success";
    
    
}


public function index()
{
$session = \Config\Services::session();
$this->common_model = model('CommonModel');

/* if check IP is blocked */

//$blocked_list = Checkip();

// if($blocked_list) {
// return redirect()->to('');
// }

if(!session()->get('user_login')) 
{

$user_data = $this->common_model->GetSettingall('user');

if($user_data) {
foreach ($user_data as $row) {
$usersettings[$row->site_key] = $row->site_value;
}
}

$site_data = $this->common_model->GetSettingall('login');

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


if($logindata['log_allow_user'] == '0') {
$session->setFlashData('disable_notification_message', lang('language_lang.lbl_diable_login'));
//return redirect()->to('login');
}

$this->data['login'] = $logindata;

/* post data */
if($this->request->getPost())
{





$email = $this->request->getPost('username');
$result = $this->common_model->getUsersid($this->request->getPost('username'));


/* check user */
if($result)
{
$condition = "uusersid = '".$result->uusersid."'";
$user_authlimit = $this->common_model->GetRow('uusers_security',$condition); 
if($user_authlimit || 1){
$count = $user_authlimit->uuser_login_count;
$us_data = authentication_loginlimit();
} else {
$count = 0;
}

/*check with authentication limit */
if($us_data <= $count && $us_data != '0') {
$session->setFlashData('error_message', lang("language_lang.login_authlimit_exced"));
return redirect()->to('login');
}
else
{


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

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

/*if($logindata['log_captcha_status'] == 'on'){
	

	$this->form_validation->setRules([
	'g-recaptcha-response' =>[
	'label' => 'password', 
	'rules' => 'required'
	],

	'password' => [
	'label' => 'password', 
	'rules' => 'trim|required'
	],
	'username' => [
	'label' => 'username', 
	'rules' => 'trim|required'
	]
	]);

}
else
{
*/

	$this->form_validation->setRules([

	'password' => [
	'label' => 'password', 
	'rules' => 'trim|required'
	],
	'username' => [
	'label' => 'username', 
	'rules' => 'trim|required'
	]
	]);

/*}*/


if ($this->form_validation->withRequest($this->request)->run()) 
{
	// $result = $this->common_model->getUserpassword($this->request->getPost('username'));
	
	   $hashed_password = $result->password;

	   //echo $hashed_password;
	   //exit();

	/* password verify */

		$condition = "language_name = '".$this->request->getPost('usrlang')."'";
        $act_lang_data = $this->common_model->GetRow("language_controls",$condition);

        if($act_lang_data) 
        {
            session()->set('user_lang', $act_lang_data->language_name);
            session()->set('user_langid', $act_lang_data->language_id);
        }

		if ($hashed_password == md5($this->request->getPost('password')))
		{
			$get_code=$result->invitation_code;

			
			if($get_code=='')
			{

				$slug=$this->invitation_code_update($result->uusersid);
				$reset_data =  array(
					'invitation_code' => $slug
				);

				$builder = $this->db->table('uusers');
				$builder->where('uusersid',$result->uusersid);
				$update_status = $builder->update($reset_data);
				
			}

			
			/* user not in-active or suspend */
			if($result->status != '1') 
			{
				$session->setFlashData('error_message', lang("language_lang.login_inactive_errormsg"));
				return redirect()->to('login');
			}

			/* check email confirm code */
			if($logindata['log_email_verify'] == 'on')
			{
				helper('text');
				$emailconfirm = random_string('numeric', 16);
				$otp_code = random_string('numeric', 6);
				$email_verify = array(
					'email_confirm_code'  => $emailconfirm,
					'otp_code'  => $otp_code
				);
				//$this->db->where('uusersid',$result->uusersid);
				//$update_status = $this->db->update('uusers_security',$email_verify);
				$this->db = db_connect();
				$update_status = $this->db->table('uusers_security')->where('uusersid', $result->uusersid)->update($email_verify);

				if($update_status)
				{
					$link = base_url().'user/login/emailconfirm/'.$emailconfirm;

					$mailid = "25";
					$mail_subject_data = $this->common_model->getMailTemplate($mailid);
					$message  = str_replace('[FIRSTNAME]', $result->username, $mail_subject_data->message);
					$message  = str_replace('[CODE]', $otp_code, $message);
					$message  = str_replace('[URL]', $link, $message);
					$message  = str_replace('#sitename', site_info_lang('site_name',session()->get('langid')), $message);
					
					$subject = "Confirmation code";
					
					/*if($mail_subject_data->status=='1')
					{
					}*/
					$this->sendmail($result->email, $result->username, $subject, $message,$mail_subject_data->from_mail);

					$array = array(
						"tmp_id" => $result->uusersid
					);
					session()->set($array);

					$session->setFlashData('success_message', lang('language_lang.email_confirm_succ'));
					return redirect()->to('login');
				} else {
					$session->setFlashData('error_message', lang('language_lang.email_confirm_err').$mail->ErrorInfo);
					return redirect()->to('login');
				}
			} 
			/* Two factor */
			else if($usersettings['user_enable_twofactor_auth'] == 'on' &&  $result->twofactor_status == '1')
			{


				$google2fa = new Google_authendicator();
				// secret key
				$secret = $google2fa->createSecret();
				if($secret)
				{

				$get_code=$google2fa->getCode($secret);

				if($get_code)
				{

				$profile_image = array(
				"google_authendicatecode"=>$get_code
				);

				$update = $this->db->table('uusers')->where('uusersid',$result->uusersid)->update($profile_image);


				if($update)
				{

				$condition = "uusersid = '".$result->uusersid."'";
				$fetch_members=$this->common_model->GetRow('uusers', $condition);  
				$site_data = $this->common_model->GetSiteSettings('site');

				$username=$fetch_members->fullname;
				$site_name = $site_data[1]->site_value;
				$secret_key=$fetch_members->twofactor_secret_key;

				$get_qrcode=$google2fa->getQRCodeGoogleUrl($username,$site_name,$secret_key);
				if($get_qrcode)
				{
				$this->data['qr_code']  = $get_qrcode;				
				}

				$this->data['memberid'] = $result->uusersid;
				$this->data['codess']  = $get_code;
				$this->data['email'] = $result->email;

				$twofactor = array(
				"tmp_id" => $result->uusersid
				);
				session()->set($twofactor);
				// return redirect()->to('verify');

				echo view('user/verify',$this->data);
				exit();
				}
				}
				}
				
				
			}
			else 
			{

				/* check transaction pin status */
				if($logindata['log_transaction_pin'] == 'on'){
					$array = array(
						"tmp_id" => $result->uusersid
					);
					session()->set($array);
					return redirect()->to('transpin');

				} else {

					/* update user datas */
					$array = array(
						"user_logged_in" => TRUE,
						"uusersid" => $result->uusersid,
						"exchange" =>1,
						"user_login" => TRUE
					);

					$sitedata = array(
						"online" => "1",
						"loginipaddr" => $_SERVER['REMOTE_ADDR'],
						"lastlogin"   => date('Y-m-d H:i:s')
					);
					$this->db = db_connect();
					$query_status = $this->db->table('uusers')->where('uusersid', $result->uusersid)->update($sitedata);
					//$this->db->where('uusersid',$result->uusersid);
					//$update_status = $this->db->update('uusers', $sitedata);
					

					$lastaccess = array(
						"uusers_id" => $result->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', $result->uusersid)->update($logincount);
					//$this->db->where('uusersid',$result->uusersid);
					//$update_status = $this->db->update('uusers_security',$logincount);
					session()->set($array);

					$successlogin = array(
					'uuserid' => $result->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
					{
						session()->set('isLoggedIn','1');
               
						return redirect()->to('user/dashboard');	
					}
				}
    
 			}

		} 
		else 
		{

			/* login and then set user auth count 0 */
			$us_data = authentication_loginlimit();

			if($us_data != '0')
			{
				$count_down = $count+1;
				$countvalue = array(
					"uuser_login_count" => $count_down
				);
				$this->db = db_connect();
				$query_status = $this->db->table('uusers_security')->where('uusersid', $result->uusersid)->update($countvalue);
				//$this->db->where('uusersid',$result->uusersid);
				//$update_status = $this->db->update('uusers_security', $countvalue);
			}

			$failogin = array(
					'uuserid' => $result->uusersid,
					'ip_address' => $_SERVER['REMOTE_ADDR'],
					'pages'	=> basename($_SERVER['REQUEST_URI']),
					'datatime' => date('Y-m-d H:i:s'),
					'status' => 'fail',
					'language' => $act_lang_data->language_id
					);

			//$this->db->insert('login_ip',$failogin);                               
			$session->setFlashData('error_message', lang("language_lang.login_errormsg"));
			return redirect()->to('login');
		}

	} 

	}
}
else
{

$failogin = array(
	'uuserid' => $result->uusersid,
	'ip_address' => $_SERVER['REMOTE_ADDR'],
	'pages'	=> basename($_SERVER['REQUEST_URI']),
	'datatime' => date('Y-m-d H:i:s'),
	'status' => 'fail',
	'language' => $this->request->getPost('usrlang')
);

//$this->db->insert('login_ip',$failogin);
$session->setFlashData('error_message', lang("language_lang.login_errormsg"));
return redirect()->to('login');
}

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

} 
else 
{
	
	



return redirect()->to('user/dashboard');
}

}


public function invitation_code_update()
{
	$this->db  = \Config\Database::connect();
	$code = $this->invitation_code();
	$res = $this->db->query("SELECT * from uusers where invitation_code = '".$code."'")->getNumRows();
	if($res > 0)
		$this->invitation_code_update();
	else
		return $code;
}


public function invitation_code()
{

	$cde='0123456789abcdeghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

	$invite=substr(str_shuffle(str_repeat($cde, 7)), 0, 7);

	return $invite;

}

public function validuser()
{
	$getPost_usrname = $this->request->getPost('username');
    	if($getPost_usrname)
		{
    		$condition = "username ='" . $getPost_usrname . "'";
    		$uname = $this->common_model->GetRow('uusers', $condition);
    		if($uname){
    			$flag=1;
    		}
    		else {
    			$flag=0;
    		}
    	}
    	else
		{
    		$flag=0;
    	}
    	echo $flag;

}





public function auth_verify()
{


	$this->db = db_connect();
	$this->session = \Config\Services::session();
	$this->common_model = model('CommonModel');

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

	$condition = "uusersid = '".$memberid."'";
	$fetch_members = $this->common_model->GetRow('uusers', $condition);     
	$secret_key=$fetch_members->twofactor_secret_key;

	$verify_code=$this->request->getPost('otp_code');

    $flag = 0;

	if($verify_code=="")
	{
	$flag=1;
	$this->session->setFlashData('error_message',"Please Enter the Verfication Code");
	}

	if($flag!=1)
	{

	$google2fa = new Google_authendicator();
	$Resultcheck = $google2fa->verifyCode($secret_key, $verify_code, 3);

	if($Resultcheck)
	{

	$condition = "uusersid = '".$memberid."'";
	$result = $this->common_model->GetRow('uusers', $condition);     

	/* update user datas */
	$array = array(
	"user_logged_in" => TRUE,
	"uusersid" => $result->uusersid,
	"user_login" => TRUE
	);

	$sitedata = array(
	"online" => "1",
	"loginipaddr" => $_SERVER['REMOTE_ADDR'],
	"lastlogin"   => date('Y-m-d H:i:s')
	);
	$this->db = db_connect();
	$query_status = $this->db->table('uusers')->where('uusersid', $result->uusersid)->update($sitedata);
	//$this->db->where('uusersid',$result->uusersid);
	//$update_status = $this->db->update('uusers', $sitedata);


	$lastaccess = array(
	"uusers_id" => $result->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', $result->uusersid)->update($logincount);
	//$this->db->where('uusersid',$result->uusersid);
	//$update_status = $this->db->update('uusers_security',$logincount);
	session()->set($array);

	$successlogin = array(
	'uuserid' => $result->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
	);

    // return redirect()->to('user/dashboard');
	$data['result'] = 'ok';
	$data['message'] =  "Valid";
	echo json_encode($data);

	}
	else
	{
	// $this->session->setFlashData('error_message',"Sorry Invalid Verfication Code");
	// return redirect()->to('login');
	$data['result'] = 'notok';
	$data['message'] =  "Sorry Invalid Verfication Code";
	echo json_encode($data);
	}
	}


}


public function result_chk()	
{
$this->load->view('user/result_check');	
}



public function loadview()
{
$this->load->view('user/loadview');	

}

public function referrence()
{
$this->load->view('user/referrence');	
}


/* logout function */
public function logout() {
$this->session = session();
$this->session->remove('user_logged_in');
$this->session->remove('uusersid');
$this->session->remove('user_login');
$this->session->remove('exchange');
$this->session->remove('isLoggedIn');
// $this->session->sess_destroy();
return redirect()->to('login');
}


public function emailconfirm(){
helper('text');
$hash = $this->uri->segment(4);
$condition = "email_confirm_code = '".$hash."'";
$confirm_found = $this->common_model->GetRow('uusers_security',$condition);
if($confirm_found && $hash!='') {
$this->data['security'] = $confirm_found;
$this->data['action'] = base_url().'user/login/emailconfirmupdate';
$this->load->view('user/emailconfirmcode',$this->data);	
}
else {
return redirect()->to('login');
}

}
public function transpin(){
$this->load->view('user/transpin');
}

public function verify(){

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



$this->form_validation->set_rules('twofactor','twofactor', 'trim|required|numeric');
if($this->form_validation->run() == TRUE)
{



$query=$this->db->query("select * from arm_members where MemberId='".$this->session->userdata('twofactor')."'")->row();

$authenticator = new Google_authendicator();
$otp = $this->input->post('twofactor');
$secret=$query->twofactor_secret_key;
$tolerance = 2;
$checkResult = $authenticator->verifyCode($secret,$otp,$tolerance);

if ($checkResult) {


$result=$this->db->query("select * from arm_members where MemberId='".$this->session->userdata('twofactor')."'")->row();

$userarray = array(
"UserId" => $result->MemberId,
"LoginDate" => date('Y-m-d H:i:s'),
"LoggedIn" => '1',
"admin_user"=>'0',
"ip_address"=>$_SERVER['REMOTE_ADDR']
);

$array = array(
"logged_in" => TRUE,
"full_name" => $result->FirstName.' '.$result->MiddleName.''.$result->LastName,
"MemberID" => $result->MemberId,
"ReferralName"=>$result->ReferralName,
"Email" => $result->Email
);
$this->session->set_userdata($array);
redirect('user/dashboard');	


}else{

$this->session->set_flashdata('error_message','Invalid Otp');

}


}

}

echo view('user/verify');
}


public function loaddata(){
$this->load->view('user/loaddata1');
}

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

public function chart(){
$this->load->view('user/chart');
}


public function verification(){

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

$condition = "uusersid = '".$this->request->getPost('tmp_id')."'";
$hashedpass = $this->common_model->GetRow('uusers_security',$condition);
$otp_password = $hashedpass->otp_code;


if ($otp_password == $this->request->getPost('otp_code')) {

$array = array(
"user_logged_in" => TRUE,
"uusersid" => $this->request->getPost('tmp_id'),
"user_login" => TRUE
);
session()->set($array);
$this->session->unset_userdata('tmp_id');

$lastaccess = array(
"uusers_id" => $this->request->getPost('tmp_id'), 
"uusers_ip" => $_SERVER['REMOTE_ADDR'],
"lastaccess"   => date('Y-m-d H:i:s'),
"user_type" => "users"
);
$insert_status = $this->db->insert('uusers_online', $lastaccess);

$empty_two_factor = array(
"otp_code" => ''
);
$insert_status = $this->db->insert('uusers_security', $empty_two_factor);

$sitedata = array(
"online" => "1",
"loginipaddr" => $_SERVER['REMOTE_ADDR'],
"lastlogin"   => date('Y-m-d H:i:s')
);

$this->db->where('uusersid',$result->uusersid);
$update_status = $this->db->update('uusers', $sitedata);

if(session()->get('user_last_page'))
{
redirect(session()->get('user_last_page'));
} 
else 
{
return redirect()->to('dashboard');	
}
}
else
{
$session->setFlashData('error_message', lang("language_lang.otp_code_error"));
return redirect()->to('verify');
}
} 
else {
return redirect()->to('login');
}*/

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

$authenticator = new PHPGangsta_GoogleAuthenticator();
$otp = $this->request->getPost('otp_code');

$condition = "uusersid = '".$this->request->getPost('tmp_id')."'";
$hashedpass = $this->common_model->GetRow('uusers',$condition);
$secret = $hashedpass->secret_key;

//$secret = session()->get('secret');
$tolerance = 2;
$checkResult = $authenticator->verifyCode($secret,$otp,$tolerance);        		    		

if($checkResult) {

$array = array(
"user_logged_in" => TRUE,
"uusersid" => $this->request->getPost('tmp_id'),
"user_login" => TRUE
);
session()->set($array);
$this->session->unset_userdata('tmp_id');
$this->session->unset_userdata('otp_code');
$this->session->unset_userdata('secret');

$lastaccess = array(
"uusers_id" => $this->request->getPost('tmp_id'), 
"uusers_ip" => $_SERVER['REMOTE_ADDR'],
"lastaccess"   => date('Y-m-d H:i:s'),
"user_type" => "users"
);
$insert_status = $this->db->insert('uusers_online', $lastaccess);

$empty_two_factor = array(
"otp_code" => ''
);
$insert_status = $this->db->insert('uusers_security', $empty_two_factor);

$sitedata = array(
"online" => "1",
"loginipaddr" => $_SERVER['REMOTE_ADDR'],
"lastlogin"   => date('Y-m-d H:i:s')
);

$this->db->where('uusersid',$result->uusersid);
$update_status = $this->db->update('uusers', $sitedata);

$successlogin = array(
'uuserid' => $result->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('dashboard');	
} 
else 
{
return redirect()->to('dashboard');	
}
}
else
{
$session->setFlashData('error_message', lang("language_lang.otp_code_error"));
return redirect()->to('verify');
}
} 
else {
return redirect()->to('login');
}

}

public function wallet_connect(){
	echo view('walletconnect-test/index');
}

public function traspinupdate(){

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

$condition = "uusersid = '".$this->request->getPost('tmp_id')."'";
$hashedpass = $this->common_model->GetRow('uusers_security',$condition);
$hashed_password = $hashedpass->trans_pin;

if ($hashed_password == crypt(urlencode($this->request->getPost('trans_pin')), $hashed_password)) {

$array = array(
"user_logged_in" => TRUE,
"uusersid" => $this->request->getPost('tmp_id'),
"user_login" => TRUE
);
session()->set($array);
$this->session->unset_userdata('tmp_id');

$lastaccess = array(
"uusers_id" => $this->request->getPost('tmp_id'), 
"uusers_ip" => $_SERVER['REMOTE_ADDR'],
"lastaccess"   => date('Y-m-d H:i:s'),
"user_type" => "users"
);
$insert_status = $this->db->insert('uusers_online', $lastaccess);

$successlogin = array(
'uuserid' => $result->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('dashboard');	
} else {
return redirect()->to('dashboard');	
}

}
else
{
$session->setFlashData('error_message', lang("language_lang.trans_pin_error"));
return redirect()->to('transpin');
}
}
else {
return redirect()->to('login');
}

}
public function emailconfirmupdate(){

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

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


// $hash = $this->uri->segment(4);
$condition = "email_confirm_code = '".$this->request->getPost('hash')."' AND otp_code = '".$this->request->getPost('email_code')."'";
$confirm_found = $this->common_model->GetRow('uusers_security',$condition);	

if($confirm_found)
{
$email_verify_code = array(
'email_confirm_code'  => '',
'otp_code' => ''
);
$this->db->where('uusersid',$confirm_found->uusersid);
$update_status = $this->db->update('uusers_security',$email_verify_code);

if($logindata['log_transaction_pin'] == 'on' && $usersetting['user_enable_twofactor_auth']!='on'){
$array = array(
"tmp_id" => $confirm_found->uusersid
);
session()->set($array);

return redirect()->to('user/login/transpin');
}
else if($logindata['log_transaction_pin'] != 'on' && $usersetting['user_enable_twofactor_auth'] =='on' && $confirm_found->two_factor=='enabled')
{

$array = array(
"tmp_id" => $confirm_found->uusersid
);
session()->set($array);

return redirect()->to('verify');

}
else{ 
/* update user datas */
$array = array(
"user_logged_in" => TRUE,
"uusersid" => $confirm_found->uusersid,
"user_login" => TRUE
);

$sitedata = array(
"online" => "1",
"loginipaddr" => $_SERVER['REMOTE_ADDR'],
"lastlogin"   => date('Y-m-d H:i:s')
);


$this->db->where('uusersid',$confirm_found->uusersid);
$update_status = $this->db->update('uusers', $sitedata);

$lastaccess = array(
"uusers_id" => $confirm_found->uusersid, 
"uusers_ip" => $_SERVER['REMOTE_ADDR'],
"lastaccess"   => date('Y-m-d H:i:s'),
"user_type" => "users"
);
$insert_status = $this->db->insert('uusers_online', $lastaccess);

$logincount = array(
'uuser_login_count'  => '0'
);
$this->db->where('uusersid',$confirm_found->uusersid);
$update_status = $this->db->update('uusers_security',$logincount);

session()->set($array);

$successlogin = array(
'uuserid' => $confirm_found->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('dashboard');	
} else {
return redirect()->to('dashboard');	
}
// return redirect()->to('user/user');
}
}
else{
$session->setFlashData('error_message', lang("language_lang.email_confirm_mismatch"));
return redirect()->to('user/login/emailconfirm/'.$hash);
}

}

function captcha_check($str)
{
$this->form_validation = \Config\Services::validation();
$this->load->library('recaptcha');
$response = $this->recaptcha->verifyResponse($str);
if (isset($response['success']) and $response['success'] === true) {
return true;  
}
else
{	
$this->form_validation->set_message('captcha_check', ucwords(lang('language_lang.cap_err')));
return false;
}
}


public function username_check($str)
{
$this->db->select('username');
$this->db->from('uusers');
$this->db->where('username',$str);

$query = $this->db->get();
if ($query->num_rows()>0)
return true;
else{
$this->form_validation->set_message('username_check', '<p style="padding-left: 15px;" class="text-danger">'.lang('language_lang.login_name_err').'</p>');
return false;
}

}

public function activate() {

$hash = $this->request->uri->getSegment(2);
$condition = "forgotpwd_authcode = '".$hash."'";
$userfound = $this->common_model->GetRow('uusers_security',$condition);


if($userfound && $hash!='') {
$myencrypt = new MyEncrypt;
$this->data['reset_id'] = $myencrypt->encode($userfound->uusersid);
$this->data['action'] = base_url().'user/login/resetupdate';
echo view('user/activate_password',$this->data);
} else {
return redirect()->to('user/login');
}

}

public function resetupdate()
{

	if($this->request->getPost())
	{
		$session = session();
		$myencrypt = new MyEncrypt;
		$uusersid = $myencrypt->decode($this->request->getPost('reset_id'));

		
		$condition = "uusersid = '".$uusersid."'";
		$userfound = $this->common_model->GetRow('uusers_security',$condition);
		if($userfound) 
		{
			
				$password = md5($this->request->getPost('password'));
				$userdata = array(
				'forgotpwd_authcode' => '',
				'uuser_login_count'  => '0'
				);

				$this->builder = $this->db->table('uusers_security');
				$this->builder->where('uusersid',$userfound->uusersid);
				$update_status = $this->builder->update($userdata);

				$passwddata = array(
				'password' => $password
				);
				$this->builder = $this->db->table('uusers');
				$this->builder->where('uusersid',$userfound->uusersid);
				$update_status1 = $this->builder->update($passwddata);

				if($update_status && $update_status1) {
				$forgotpwd_authcode = array(
				'forgotpwd_authcode'  => ''
				);

				$this->builder = $this->db->table('uusers_security');
				$this->builder->where('uusersid',$userfound->uusersid);
				$update_status = $this->builder->update($forgotpwd_authcode);
				$session->setFlashData('success_message', lang('New password updated. Please login to continue'));
				return redirect()->to('user/login');
				} 
				else 
				{
					$session->setFlashData('error_message', "Reset password request failed. please try again later");
					return redirect()->to('reset');
				}
			}
		echo view('user/activate_password');
	}
}

public function validcode(){
// $condition = "email_confirm_code = '".$this->request->getPost('email_code')."'";
$condition = "otp_code = '".$this->request->getPost('email_code')."'";
$confirm_found = $this->common_model->GetRow('uusers_security',$condition);

if($confirm_found){
$json['valid'] = true;
}
else {
$json['valid'] = false;
}	
echo json_encode($json);
}

public function reg_activate(){
$hash = $this->uri->segment(4);
$condition = "activation_code = '".$hash."'";
$act_found = $this->common_model->GetRow('uusers_security',$condition);
if($act_found && $hash!=''){
$status_data =  array(
'status' => '1'
);	
$this->db->where('uusersid',$act_found->uusersid);
$update_status = $this->db->update('uusers',$status_data);

$act_pin =  array(
'activation_code' => ''
);
$this->db->where('uusersid',$act_found->uusersid);
$update_status = $this->db->update('uusers_security',$act_pin);
$session->setFlashData('success_message', lang('language_lang.account_activ_success'));
return redirect()->to('user/login');
}
else{
$session->setFlashData('error_message', lang('language_lang.account_activ_error'));
return redirect()->to('user/login');
}
}



public function reset() {

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

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

			$resetmail = $this->request->getPost('username');
			
		    $session = session();

			$validation->setRules([
				'username' => [ "label" =>'username', "rules" => 'trim|required|checkusername_forgot[$resetmail]']
				]);

			// check form validate
			if ($validation->withRequest($this->request)->run() == TRUE) {
				$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;
				}
		
				$condition = "email = '".$resetmail."'";
				$user = $this->common_model->GetRow('uusers', $condition);
				$slug = md5($user->uusersid . $user->email . time());
				$reset_data =  array(
					'forgotpwd_authcode' => $slug
				);

				$builder = $this->db->table('uusers_security');
				$builder->where('uusersid',$user->uusersid);
				$update_status = $builder->update($reset_data);
				
				if($update_status || 1) {
					$link = base_url().'/activate/'.$slug;
					$mailid = '18';
			        $mail_subject_data = $this->common_model->getMailTemplate($mailid);
					$message  = str_replace('[FIRSTNAME]', $user->username, $mail_subject_data->message);
					$message  = str_replace('[URL]', $link, $message);
					$message  = str_replace('#adminemail', $mail_data['admin_email'], $message);
					$message  = str_replace('#sitename', site_info_lang('site_name',session()->get('langid')), $message);
                     
					$subject    = "Reset password";
					/*$this->sendmail($user->email, $user->username, $subject, $message,
			    	$mail_subject_data->from_mail);*/
			    	
			    	$this->sendmail1($user->email, $user->username, $subject, $message,
			$mail_subject_data->from_mail);
			
			    	$session->setFlashData('success_message', lang('language_lang.reset_password_success_message'));
					return redirect()->to(base_url('reset'));
				} else {
					$session->setFlashData('error_message', lang('language_lang.error').$mail->ErrorInfo);
					return redirect()->to(base_url('reset'));
				}
			}
			else
			{
				$session->setFlashData('error_message', 'Given Email ID not exists');
				return redirect()->to(base_url('reset'));
				
			}
			
		} 
		echo view('user/forgotpassword');
	}


	public function testmail()
	{	
			$resetmail='palani@arminfotech.us';
			$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;
			}
		
			$condition = "email = '".$resetmail."'";
			$user = $this->common_model->GetRow('uusers', $condition);
			$slug = md5($user->uusersid . $user->email . time());
			$link = base_url().'/activate/'.$slug;
			$mailid = '18';
			$mail_subject_data = $this->common_model->getMailTemplate($mailid);
			$message  = str_replace('[FIRSTNAME]', $user->username, $mail_subject_data->message);
			$message  = str_replace('[URL]', $link, $message);
			$message  = str_replace('#adminemail', $mail_data['admin_email'], $message);
			$message  = str_replace('#sitename', site_info_lang('site_name',session()->get('langid')), $message);
				
			$subject    = "Reset password";

			
			$this->sendmail1($user->email, $user->username, $subject, $message,
			$mail_subject_data->from_mail);
			

	}

	function sendmail1($useremail, $fullname, $subject, $message,$from_mail) {

		echo $useremail;
		$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->SMTPDebug = 2;  
		$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->SMTPOptions = array(
			'ssl' => array(
				'verify_peer' => false,
				'verify_peer_name' => false,
				'allow_self_signed' => true
			)
		);
		}
		
		
		$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);
		
		echo '<pre>';
		print_r($mail);
		echo '</pre>';
		if(!$mail->Send()) {
		 echo "Mail Error";

		 echo 'Mailer error: ' . $mail->ErrorInfo;
		} else {
			
			echo "Mail Sent";
		}
	}


 function refersh(){

$this->mathcaptcha->init();
$math_captcha_question = $this->mathcaptcha->get_question();
$this->load->helper('captcha');
$img_name = time().'.jpg';
$img_path = 'captcha/';
$im = imagecreate('150', '50');
$text = array(245,171,53);
$bg_color   = imagecolorallocate ($im, 34, 49, 63);
$text_color = imagecolorallocate ($im, 255, 255, 255);	
ImageFilledRectangle($im, 0, 0, 150, 50, $bg_color);   
$cap = imagestring($im, 12, 45, 18, $math_captcha_question, $text_color);
$cp = ImageJPEG($im, $img_path.$img_name);
$this->data['ur'] = $img_path.$img_name;

echo base_url().$this->data['ur'];
}

function _check_math_captcha($str) {

if( $str == session()->get('mathcaptcha_answer'))
{
return TRUE;
}
else
{
$this->form_validation->set_message('_check_math_captcha', '<small class="help-block">'.lang('language_lang.cap_err').'</small>');
return FALSE;
}
}

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

public function cron(){

	$this->db      = \Config\Database::connect();

	
	$row = $this->db->table('ipn_process')->where("payment='cron_test'")->get()->getRow();


	if(!empty($row)){
		$value = floatval($row->post_content) + 1;
		$this->db->table("ipn_process")->update(['post_content' => $value]);
	}

	$Strategy = new Strategy;


$get_users = $Strategy->first_strategy();
	$manual_result = $Strategy->manual_strategy();


	return  json_encode($get_users);
}

public function cron2(){

	$this->db      = \Config\Database::connect();

	$Strategy = new Subbin_Strategy;

	$get_users = $Strategy->subbin_strategy();


	return  json_encode($get_users);
}

public function cron3(){

	$this->db      = \Config\Database::connect();

	$Strategythird = new Strategythird;

	$get_users = $Strategythird->third_strategy();


	return  json_encode($get_users);
}

   public function spil_chk($spilover,$table,$memberid)
    {
    	$this->db = db_connect();
        $find_next=$this->db->query("select * from $table where uusersid='".$spilover."'")->getRow();
        if($find_next)
        {
            $spilloverid=$find_next->uusersid;
            $spilover=$find_next->spillover_id;  

            if($spilloverid > 0)
            {
                $members_cnt=$find_next->members_cnt;
                
                if($members_cnt=='' || $members_cnt=='0')
                {
                    $member_ads=$memberid;
                }
                else
                {
                    $member_ads=$members_cnt.",".$memberid; 
                }
                $this->db->query("update $table set members_cnt='".$member_ads."' where uusersid='".$spilloverid."'");
                $this->spil_chk($spilover,$table,$memberid);
            }
        }
    }





	/*public function invitation_code_update($value){
		$this->db  = \Config\Database::connect();
		  if($value->invitation_code == "" || $value->invitation_code == 0){
                 	$code = $this->invitation_code();
          
                 	$res = $this->db->query("SELECT * from uusers where invitation_code = '".$code."'")->getNumRows();
                 	
                 	if($res == 0){
                 		$this->db->table('uusers')->set('invitation_code',$code)->where('uusersid',$value->uusersid)->update();
                 	}
                 }
                 $res = $this->db->query("SELECT * from uusers where uusersid = '".$value->uusersid."'")->getRow();
                    if($res->invitation_code == "")
                    $this->invitation_code_update($value);
                    else
                    	return true;
                
	}*/


	public function global_divide(){  //global dividend commission
		$db = db_connect();
		$session = session();
		$Commissions = new Commissions;
		$last_rank = $db->table('rewardsettings')->orderBy('id','DESC')->get()->getRow();
		$users = $db->table('uusers_matrix')->where('rankid',$last_rank->id)->get()->getResult();
		$last_month_records = $db->query("select SUM(amount) as company_profit from history
     where type='admin_id_reward' and month(date)=month(now())-1")->getRow();
		$admin_settings = $db->table('adminsettings')->orderBy('id','DESC')->get()->getRow();
		$global_share = $admin_settings->global_dividend;
		$amount = $last_month_records->company_profit * ( $global_share / 100);
		
		foreach ($users as $key => $value) {
			$duplicate_entry = $db->query("SELECT * FROM history WHERE type='commissions' and description LIKE '%Global dividend%' and uusersid='".$value->uusersid."' and MONTH(date) = MONTH(CURRENT_DATE()) AND YEAR(date) = YEAR(CURRENT_DATE())")->getRow();
			if($duplicate_entry == "" || $duplicate_entry == 0)
			$profit_provide = $Commissions->global_reward($value->uusersid,$amount);
		}
	}

public function get_response($url)
{
    $curl = curl_init();
    curl_setopt_array($curl, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => [
    "Accept: application/json"
    ],
  ]);
  $response = curl_exec($curl);
  return $response;
}

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


public function trade_fill_check(){
    $this->session = session();
	$this->db  = \Config\Database::connect();
	$sell_status1 = array(
		'type' => 2,
		'status' => 0
	);

	$ci_session_clear = $this->db->query("DELETE from ci_sessions where timestamp < now() - interval 1 DAY");

  
		
	$sell_status = $this->db->table('api_trade_history')->where($sell_status1)->get()->getResult();
	echo"<pre>";
	print_r($sell_status);
	echo"</pre>";
	$result = $this->db->table('uusers as t1,history as t2')->select('t1.uusersid as userid')->distinct('uusersid')->where('t2.uusersid = t1.uusersid')->where('t2.type','activation')->where('t2.status',1)->get()->getResult();

	$recvied = "";
	if($result){
		foreach ($result as $key => $value) {
		//	$Rank_update = new Rank_update();
               //  $Rank_update = $Rank_update->rank_check($value->userid);
                 $asset_balance = gas_wallet_bal($value->userid);
                  $tradSets = $this->common_model->GetResults('adminsettings','');
                  $tradSet = $tradSets[0];
                  $gas_fee=$tradSet->min_fuel;
                 
                $trades = $this->db->query("Select * from trade_process where uusersid = '".$value->userid."' and trade_status != 2")->getNumRows();
                 if($asset_balance < $gas_fee && $trades) {
                 	$duplicate_entry = $this->db->table('notification_table')->where('uusersid',$value->userid)->like('message','Gas wallet')->like('created_date',date('Y-m-d'))->get()->getRow();
                 if(empty($duplicate_entry)){
                 	$notification = array(
						'uusersid' => $value->userid, 
						'message'  => 'Gas wallet Low fuel. Please top fuel Minimum:'.$gas_fee.'USDT for without trade stop functionality',
						'created_date' => date('Y-m-d H:i:s')
					);
					$this->db->table('notification_table')->insert($notification);
                 }
             }
                 if($asset_balance < 15 && $trades) {
                 	// $duplicate_entry = $this->db->query("Select * from notification_table where uusersid = '".$value->userid."' and created_date  > DATE(now())")->getRow();
                 	$duplicate_entry1 = $this->db->table('notification_table')->where('uusersid',$value->userid)->like('message','Low balance')->like('created_date',date('Y-m-d'))->get()->getRow();
                 	if(!empty($duplicate_entry1)){
                 	$notification = array(
						'uusersid' => $value->userid, 
						'message'  => 'The platform balance is insufficient 15, please supplement in time. If it is lower than 5USDT, the policy will be stopped',
						'created_date' => date('Y-m-d H:i:s')
					);
					//$this->db->table('notification_table')->insert($notification);
					$site_data = $this->common_model->GetSettingall('email');
			        if($site_data) {
			            foreach ($site_data as $row) {
			                $admin_email[$row->site_key] = $row->site_value;
			            }
			        } 
			        if($admin_email['admin_email'])
			        {
			            $from_mail=$admin_email['admin_email'];
			        }else{
			            $from_mail = "support@trading.com";
			        }
                    $this->db = db_connect();
                    $email = $this->db->query("Select * from uusers where uusersid = '".$value->userid."'")->getRow();
                    $trades = 1;

                    if($email && $trades)
                    {
                    	$sub = 'Low Asset Balance';
                    	$mailid = '1';
                    	$mail_subject_data = $this->common_model->getMailTemplate($mailid);
                    	$message = "<p>Hello ".$email->fullname.",
                <br />
            &nbsp;</p>
            
            <p>Your Asset Balance is too low. Please recharge your asset to avoid inactive bot process. Because, Bot does not tak e any trade below 5 USDT. </p>
            
            <p>&nbsp;</p>
            
            <p>Your Current Asset Balance : ".$asset_balance." </p>
            
            <p>&nbsp;</p>
            
            <p>&nbsp;</p>
            
            
            
            <p>&nbsp;</p>";
                    	$mail=$this->sendmail($email->email,$message,$sub,$mail_subject_data->from_mail);
            				    }
                             }    
            		}
            	}
            }


	$pay_details = $this->db->query('select * from uusers_address order by id asc')->getResult();

	
	foreach ($pay_details as $key => $cust_det) {
		    $address=trim($cust_det->address);
		  
           	$get_response = $this->get_response('https://apilist.tronscan.org/api/account?address='.$address);
          
           	// $get_response = $this->get_response('https://apilist.tronscan.org/api/token_trc20/transfers?&start=0&contract_address='.$address);
			$response=json_decode($get_response); 
	
			
			$get_response1=$this->get_response('https://apilist.tronscan.org/api/transaction?sort=-timestamp&count=true&start=0&address='.$address);
			$response1=json_decode($get_response1);
	
			foreach ($response->trc20token_balances as $key => $value) {
				if($value->tokenAbbr == 'USDT' && $value->tokenType == 'trc20'){
                     $amount1 =$value->balance;
					 $amount=$value->balance/1000000;
                     $data=$response1->data[$key];
			         $hash=$data->hash;
	
			   $deposit_counts = $this->db->query('select SUM(amount) as amount from history where uusersid="'.$cust_det->uusersid.'" and transhash="'.$address.'"')->getRow();
			 
			    if($deposit_counts->amount == 0 || $deposit_counts->amount == ""){
			      	$uusersid=$cust_det->uusersid;
		            	$deposit_data = array(
                        'uusersid' => $uusersid,
                        'amount'  => $amount,
                        'type'  => 'deposit', 
                        'description'  => 'deposit',
                        'date'  => date('Y-m-d H:i:s'),
                        'currency' => 1,
                        'transhash' => $address,
                        'transactionid' => $hash
                    );
					if($amount > 0) { 
					$this->db->table('history')->insert($deposit_data); 
					$notification = array(
					'uusersid' => $uusersid, 
					'message'  => 'Recharge has arrived',
					'created_date' => date('Y-m-d H:i:s')
					);
					$this->db->table('notification_table')->insert($notification);
					}
			    }else{
					if($deposit_counts->amount > 0 && intval($deposit_counts->amount) != $amount && intval($deposit_counts->amount) < $amount){
						$uusersid = $cust_det->uusersid;
		            	$deposit_data = array(
                        'uusersid' => $uusersid,
                        'amount'  => $amount - $deposit_counts->amount,
                        'type'  => 'deposit', 
                        'description'  => 'deposit',
                        'date'  => date('Y-m-d H:i:s'),
                        'currency' => 1,
                        'transhash' => $address,
                        'transactionid' => $hash
                         );
		            	$confirm_amt = $amount - $deposit_counts->amount;
		            	if($confirm_amt > 0) {
					    $this->db->table('history')->insert($deposit_data); 
					    $notification = array(
						'uusersid' => $uusersid, 
						'message'  => 'Recharge has arrived',
						'created_date' => date('Y-m-d H:i:s')
					    );
					$this->db->table('notification_table')->insert($notification);
				}
				    }
				}
			}
	}
}

 


	
	for ($i=0; $i <count($sell_status) ; $i++) { 


	
		$userid_bind_process = $this->db->table('bind_process')->where('uusersid',$sell_status[$i]->uuserid)->get()->getRow();
		$key = $userid_bind_process->api_key;
		$secret = $userid_bind_process->secret_key;
		// $api = new Binance\API($key,$secret);
		// $account = $api->accountStatus();
		if($account['sapi']['code'] != "-2008" && $account['sapi']['code'] != "-1022" || $account['sapi']['code'] != '-2015' || 1) { 
		// $order_status = $api->orderStatus($sell_status[$i]->pair,$sell_status[$i]->order_id);
		// echo"<pre>";
		// print_r($order_status);
		// echo"</pre>";
		if ($order_status['status'] == 'FILLED' || 1) {
			$avg_price = $sell_status[$i]->comm_price;
			$profit_price = $sell_status[$i]->avg_price;
			$order_id  = $sell_status[$i]->order_id;
			$Commissions = new Commissions;
			$userid = $sell_status[$i]->uuserid;
			$id = $sell_status[$i]->id;
			$amount = $avg_price;
			$description = ' for sell profit';
			$trade_process_id = $sell_status[$i]->trade_process_id;

        $from_uusers = $this->db->table('uusers')->where('uusersid',$userid)->get()->getRow();
		$from_uusers_mail = $from_uusers->email;
		 // $this->session = session();
         $this->session->set('usermail',$from_uusers_mail);
         $this->session->set('fuel_amount',$amount);
         $this->session->set('missing_comm',0);
         $this->session->set('total_comm',0);
         $this->session->set('same_rank4',0);

         		$uusers_matrix = $this->db->table('uusers_matrix');
		$uusers_matrix =  $uusers_matrix->where('uusersid',$userid)->get()->getRow();
		
		$referral_id = $uusers_matrix->referral_id;
		$user_rank = $uusers_matrix->rankid;


		$uusers = $this->db->table('uusers')->where('uusersid',$userid)->get()->getRow();
		$usermail = $uusers->email;

		$referral_matrix = $this->db->table('uusers_matrix');
		$referral_matrix =  $referral_matrix->where('uusersid',$referral_id)->get()->getRow();
		$referral_id = $referral_matrix->uusersid;

		$referral_rank = $referral_matrix->rankid;


		if(empty($referral_rank))
			$referral_rank = '4';
        
		$rewardsettings = $this->db->table('rewardsettings');
		$rewardsettings =  $rewardsettings->where('id',$referral_rank)->get()->getRow();
		// Direct commission check

		$commission = $amount * $rewardsettings->direct_push_award / 100;
		if($commission > 0)
		{
		//$this->directcommission($referral_id,$commission,$description,$usermail);
		}

	    //reward_activation check
		$reward_activation_check = explode(',', $rewardsettings->reward_profit);
        
        //remove direct activation
        //$reward_level = array_shift($reward_activation_check);
        
        //check array count
        $reward_count = count($reward_activation_check);

        //check activation type
        $activation_type = $rewardsettings->activation_type;

         // $this->session = session();
           
        echo"<pre>";
        print_r("amount ".$amount);
        echo"</pre>";

            if($amount > 0){ 
			$profit_provide =  $Commissions->trading_profit_commission($referral_id,$description,'0',$usermail,$activation_type,$reward_activation_check,$amount,$referral_rank,$user_rank,$order_id);
		    }
			for($i=0; $i<=11; $i++){
			$this->session->remove('same_rank'.$i);
			}

			$this->session->remove('usermail');
			$this->session->remove('fuel_amount');
			$this->session->remove('missing_comm');
			$this->session->remove('total_comm');
			$profit_provide = $Commissions->strategy_check($userid,$profit_price,$trade_process_id,$order_id,$id);
			$res_out = $this->db->table('api_trade_history')->set('status','1')->where('id',$id)->update();
		
		}
	}
	}

}


public function verifyregcode()
{

$this->session = \Config\Services::session();
$this->db = db_connect();
$this->common_model = model('CommonModel');

$email = $this->request->getPost('email');
$result = $this->common_model->getUsersid($this->request->getPost('email'));

$otp = $result->twofactor_secret_key;

$message = "Your Google Authenticator Security Key Is" . $otp;
$sub = "Forgot Security Key";


$site_data = $this->common_model->GetSettingall('email');

if($site_data) {

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

} 
if($admin_email['admin_email'])
{
$from_mail=$admin_email['admin_email'];
}else{
$from_mail = "support@trading.com";
}

if($email)
{
$sub = 'Forgot Security Key';
$mailid = '33';
$mail_subject_data = $this->common_model->getMailTemplate($mailid);
$message  = str_replace('[OTP]', $otp, $mail_subject_data->message);
$message  = str_replace('#sitename', site_info_lang('site_name',$this->session->get('langid')), $message);
$mail=$this->sendmail($email,$email,$sub,$message,$mail_subject_data->from_mail);



$mail=1;

if($mail)
{
$json['message'] = "Security Key send to your Email.";
}
}
else
{        	
$json['message'] = "Cannot Send Security Key to your Email.";
}

echo json_encode($json['message']);
}



 public function sendmail($useremail,$message, $subject,$from_mail) {
        $this->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;
    	}

    	$message  = str_replace('#adminemail', $mail_data['admin_email'], $message);

    	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->SMTPOptions = array(
				'ssl' => array(
					'verify_peer' => false,
					'verify_peer_name' => false,
					'allow_self_signed' => true
				)
			); 
    	}

    	$mail->SetFrom($from_mail, site_info_lang('site_name',$this->session->get('langid')));  
    	$mail->AddReplyTo($from_mail,site_info_lang('site_name',$this->session->get('langid')));

    	$mail->Subject = $subject;
    	$mail->msgHTML($message);
    	$mail->AddAddress($useremail, $useremail);

    	if(!$mail->Send()) {
    		return false;
    	} else {
    		return true;
    	}
    }


}

