<?php

namespace App\Controllers\User;
use App\Views;
use App\Models\CommonModel;
use App\Helpers\site_helper;
use App\Libraries\MyEncrypt;
use App\Libraries\My_PHPMailer;
use App\Libraries\PHPMailer; 
use App\Libraries\mathcaptcha;
use App\Libraries\Google_authendicator;
error_reporting(0);


class UserSettings extends BaseController
{
public function __construct(){
date_default_timezone_set('Asia/Singapore');
// $CommonModel = new CommonModel();
$this->session = session();
$CommonModel = model('CommonModel');
}
public function index() {
$this->db = db_connect();
$myencrypt = new MyEncrypt(true);
$this->common_model = model('CommonModel');
$this->finance_model = model('finance_model');
$this->userdash_model = model('userdash_model');
$session = \Config\Services::session();
$validation = \Config\Services::validation();
$uri = service('uri');
if(!($session->get('user_login') || $session->get('admin_login')))
{			
return redirect()->to('login');
}
$this->indexpage();
}

public function indexpage() {
$CommonModel = model('CommonModel');

$condition = "payment_key in('logo','status')";
$payment_data_list = $CommonModel->GetPaymentsName($condition);
$site_data = $CommonModel->GetSettingall('infobox');
if($site_data) {

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

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

$site_lang_data = $CommonModel->GetSiteSettings('site');

if($site_lang_data){	
$site_data = array_merge($site_data, $site_lang_data);
}

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


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

$get_details = $this->db->query("SELECT * from uusers where uusersid ='".$this->session->get('uusersid')."'")->getRow();
$rankid = $this->db->query("SELECT * from uusers_matrix where uusersid ='".$this->session->get('uusersid')."'")->getRow();
if(!empty($rankid->rankid))
$rank = $this->db->query("SELECT * from rewardsettings where id ='".$rankid->rankid."'")->getRow();
else
$rank = $this->db->query("SELECT * from rewardsettings where id ='4' ")->getRow();

$this->data['nice_name'] = $get_details->fullname;
$this->data['user_email'] = $get_details->email;
$this->data['user_profile'] = $get_details->profile;
$this->data['invitation_code'] = $get_details->invitation_code;
$this->data['rank'] = $rank->rank_name;

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

public function pro_update()
{

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

if($this->request->getMethod('post'))
{

if(isset($_FILES['file_profile']['tmp_name']) && $_FILES['file_profile']['size'] > 0) {

$uploads_dir = './content/site';
$tmp_name = $_FILES["file_profile"]["tmp_name"];

$name = basename($_FILES['file_profile']['name']);
$img = $this->request->getFile('file_profile');

//uplode file
if($img->move('./content/site', $name)){

// delete existing file
if(isset($site_data['site_logo'])){
unlink('./content/site/'.$site_data['site_logo']);
}

$profile_image = array(
"profile"	=>	$name
);

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

if($update_status)
{
$this->session->setFlashData('success_message', 'Profile update SuccessFully..');
return redirect()->to('/user/settings');	
}
else
{
$this->session->setFlashData('error_message', 'Profile update Faild!!');
return redirect()->to('/user/settings');
}

}
else
{
echo 'error';
}

}
}


}



public function verifyregcode5()
{


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

$this->db = db_connect();

$get_mail = $this->db->query("SELECT * from uusers where uusersid ='".$this->session->get('uusersid')."'")->getRow();
$email = $get_mail->email;

$referral1=$this->db->query("SELECT * FROM uusers WHERE email='".$email."'");
$row=$referral1->getRow();

$referal_id=$row->uusersid;
$otp = rand(100000, 999999); //generates random otp

//$_SESSION['session_otp'] = $otp;
$message = "Your one time email verification code is" . $otp;

if($this->request->getPost('sub')==2)
{
$sub = "Update Transaction Password Email verification";

$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 = '".$email."'";
$user = $this->common_model->GetRow('uusers', $condition);

if($user) {

$mailid = '21';
$mail_subject_data = $this->common_model->getMailTemplate($mailid);
$message  = str_replace('[FIRSTNAME]', $user->fullname, $mail_subject_data->message);
$message  = str_replace('[OTP]', $otp, $message);
$message  = str_replace('#adminemail', $mail_data['admin_email'], $message);
$message  = str_replace('#sitename', site_info_lang('site_name',$this->session->get('langid')), $message);
$subject    = "Change Transaction Pin Email verification";

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

}
}
if($this->request->getPost('sub')==1)
{
//$sub = "Change Password Email verification";

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

$fullname = $check->fullname;
$useremail = $check->email;
// sent mail to user
$sitename = site_info_lang('site_name',$this->session->get('langid'));
$subject = 'Change Password Email verification';
$mailid = '20';
$mail_subject_data = $this->common_model->getMailTemplate($mailid);
$message  = str_replace('[FIRSTNAME]', $fullname, $mail_subject_data->message);
$message  = str_replace('[OTP]', $otp, $message);
$message  = str_replace('#sitename',$sitename , $message);
$mail_status = $this->sendmail($useremail, $fullname, $subject, $message,$mail_subject_data->from_mail);

}

$this->session->set('email',$email);
$this->session->set('otp',$otp);

$this->db = db_connect();
$table='admin';
$condition = "id = '1'";
$admin_email= $this->common_model->GetResults($table,$condition);


if($admin_email)
{
$from_mail=$admin_email->email;
}

// $mail=$this->sendmail($email,$message,$sub,$from_mail);
$mail=1;
if($mail)
{
$data=array(
"pw_otp" => $otp
);

$this->db = db_connect();
$query_status =   $this->db->table('uusers')->where('email',$email)->update($data);
$json['message'] = "OTP send to your Email.";
}

else
{        	
$json['message'] = "Cannot Send OTP.";

}

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


public function verifyotp5()
{
$this->session = session();
$code=$this->request->getPost('pw_email');
$otp=$this->session->get('otp');


if($code==$otp)
{
$json['valid'] = true;
}
else
{
$json['valid'] = false;
}

echo json_encode($json);

}

public function verifyotp4()
{
$this->session = session();
$code=$this->request->getPost('tpw_code');
$otp=$this->session->get('otp');


if($code==$otp)
{
$json['valid'] = true;
}
else
{
$json['valid'] = false;
}

echo json_encode($json);

}

public function validemail(){
$getPost_email = $this->request->getPost('email');
if($getPost_email){
$condition = "email ='" . $getPost_email . "'";
$uemail = $this->common_model->GetRow('uusers', $condition);
if($uemail){
$json['valid'] = true;
}
else {
$json['valid'] = false;
}
}
else{
$json['valid'] = true;
}
echo json_encode($json);
}


public function changePwd()
{
$this->session = session();

$otp = $this->request->getPost('pw_email');


$this->db = db_connect();

$get_mail = $this->db->query("SELECT * from uusers where uusersid ='".$this->session->get('uusersid')."'")->getRow();
$c_otp = $get_mail->pw_otp;

if($otp == $c_otp)
{

$cpassword = $this->request->getPost('cpassword5');
$password  = $this->request->getPost('password5');

if($cpassword==$password)
{

$passwords=crypt(urlencode($this->request->getPost('password5')),'');

$data=array(
"password" => $passwords
);


$this->db = db_connect();
$query_status =   $this->db->table('uusers')->where('uusersid',$this->session->get('uusersid'))->update($data);

if($query_status)
{
$this->session->setFlashData('success_message', 'Password update SuccessFully..');
return redirect()->to('/user/settings');	
}
else
{
$this->session->setFlashData('error_message', 'Password update Faild ..');
return redirect()->to('/user/settings');	
}

}

}
else
{
$this->session->setFlashData('error_message', 'Incurrect  OTP Plsease Try Again! ..');
return redirect()->to('/user/settings');	
}

}

//change transaction passwrod

public function changeTpwd()
{
$this->session = session();

$otp = $this->request->getPost('tpw_code');


$this->db = db_connect();

$get_mail = $this->db->query("SELECT * from uusers where uusersid ='".$this->session->get('uusersid')."'")->getRow();
$c_otp = $get_mail->pw_otp;

if($otp == $c_otp)
{

$cpassword = $this->request->getPost('tpassword4');
$password  = $this->request->getPost('ctpassword4');

if($cpassword==$password)
{

$passwords=crypt(urlencode($this->request->getPost('tpassword4')),'');

$data=array(
"trans_pin" => $passwords
);

$this->db = db_connect();
$query_status =   $this->db->table('uusers_security')->where('uusersid',$this->session->get('uusersid'))->update($data);

if($query_status)
{
$this->session->setFlashData('success_message', 'Transactin Password update SuccessFully..');
return redirect()->to('/user/settings');	
}
else
{
$this->session->setFlashData('error_message', 'Transactin Password update Faild ..');
return redirect()->to('/user/settings');	
}

}

}
else
{
$this->session->setFlashData('error_message', 'Incurrect  OTP Plsease Try Again! ..');
return redirect()->to('/user/settings');	
}



}



/*----------------------------verify password section start ----------------------------------------*/


public function verify_passwordauth()
{

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

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

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


/* Two factor */
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');
// $this->common_model->GetRow("uusersid='".$this->session->get('uusersid')."'","uusers");
$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['email'] = $result->email;
$this->data['codess']  = $get_code;

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

$this->data['action'] = base_url('/password_authverify');

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

}
}
}

}
else
{
echo view('user/change_password');
}

}



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


public function password_authverify()
{

$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)
{
$data['result'] = 'ok';
$data['message'] =  "Valid";
echo json_encode($data);
}
else
{
$data['result'] = 'notok';
$data['message'] =  "Sorry Invalid Verfication Code";
echo json_encode($data);
}
}


}
/*-----------------------------verify password section end --------------------------------------------*/



/*----------------------------------------- mail send otp  -----------------------------------------*/

public function verifyregcode()
{

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


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

$otp = rand(100000, 999999); 


$message = "Your one time email verification code is " . $otp;
$sub = "Email verification";

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

$this->session->set('otp',$otp);
$this->db = db_connect();


$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 = 'Email verification code for Disable Two Factor';
$mailid = '34';
$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,$message,$sub,$mail_subject_data->from_mail);
$mail=1;

if($mail)
{

$data=array(
"pw_otp" => $otp
);

$this->db = db_connect();
$query_status =   $this->db->table('uusers')->where('email',$email)->update($data);

$json['message'] = "OTP send to your Email.".$otp;
}

}
else
{   

$json['message'] = "Cannot Send OTP.".$otp;

}

// echo $otp;
echo json_encode($json['message']);


}


public function verifyotp()
{

// $otp=$this->session->get('otp');

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

$memberid =$this->session->get('uusersid');

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

$flag = 0;

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


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)
{
$json['valid'] = true;

}
else
{
$json['valid'] = false;
}
}



echo json_encode($json);

}


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

$condition = "settings_name = 'email'";
$email_setting_data = $this->common_model->GetSettingall_lang($condition);

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

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

} else {

$mail = new PHPMailer();
$mail->IsSMTP(); 
$mail->SMTPAuth   = TRUE; 
$mail->SMTPSecure = $mail_data['smtp_type'];  
$mail->Host       = $mail_data['smtp_hostname'];      
$mail->Port       = $mail_data['smtp_portno'];                   
$mail->Username   = $mail_data['smtp_username'];  
$mail->Password   = $mail_data['smtp_password'];   
}

$mail->SetFrom($from_mail, site_info_lang('site_name',session()->get('langid')));  
$mail->AddReplyTo($from_mail,site_info_lang('site_name',session()->get('langid')));
$message  = str_replace('#adminemail', $from_mail, $message);



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

$mail->AddAddress($useremail, $fullname);


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

/*----------------------------------------- mail send otp end -----------------------------------------*/

/*----------------------------------------- Check Package value -----------------------------------------*/


public function check_pack()
{

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

$pack_id=$this->request->getPost('pool_pack');
$pack_amount=$this->request->getPost('pool_amt');

$buy_bal = curbalance($uusersid);
$balance = str_replace(",","", $buy_bal);


$invest_pool_pack = $this->db->table('package_settings')->where('id',$pack_id)->get()->getRow();

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

$check_tradepool_fee_format = $this->db->table('site_controls')->where('settings_name','pool_invest')->where('site_key', 'robot_fee_format')->get()->getRow();


$check_tradepool_fee = $this->db->table('site_controls')->where('settings_name','pool_invest')->where('site_key', 'robot_fee')->get()->getRow();

$invest_pool_pack_count = $this->db->table('history')->where('type','pool_invest')->where('uusersid', $uusersid)->get()->getNumRows();

if($check_tradepool_fee_format->site_value=='on')
{   

if($invest_pool_pack_count <= 0)
{
$pack_amounts = $check_tradepool_fee->site_value;
}
else
{
$pack_amounts = 0;
}

}
else
{
$pack_amounts = $check_tradepool_fee->site_value;
}

$all_amount = $pack_amounts + $pack_amount;

if($all_amount <= $balance)
{
$flag = 0;
}
else
{
// $flag = 1;
// $message = "Insufficient Balance";

// $json['valid'] = false;
// $json['message'] = $message;

// echo json_encode($json);
// exit();    
}


if($invest_pool_pack)
{

$flag = 1;

if($pack_amount <= $invest_pool_pack->max_amt  &&  $pack_amount >= $invest_pool_pack->min_amt)
{
$flag = 0;
}
else
{
$flag = 1;
$message = "Please Check Minimum and Maximum Amount..";
}




if($flag==0)
{
$json['valid'] = true;
$json['message'] = "";
}
else
{
$json['valid'] = false;
$json['message'] = $message;
}

}
else
{
$json['valid'] = false;
$json['message'] = "Please select Package...";
}

echo json_encode($json);

}


/*----------------------------------------- Check Package end -----------------------------------------*/


/*-----------------------------------------  Pool Trading investment ----------------------------------*/

public function pool_trading_invest()
{


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


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

$uusersid = $this->session->get('uusersid');
$buy_bal = curbalance($uusersid);
$balance = str_replace(",","", $buy_bal);


$pack_id=$this->request->getPost('pool_invest_pack');
$pack_amount=$this->request->getPost('pool_invest_amount');



$invest_pool_pack_count = $this->db->table('history')->where('type','pool_invest')->where('uusersid', $uusersid)->get()->getNumRows();

$check_tradepool_fee_format = $this->db->table('site_controls')->where('settings_name','pool_invest')->where('site_key', 'robot_fee_format')->get()->getRow();

$check_tradepool_fee = $this->db->table('site_controls')->where('settings_name','pool_invest')->where('site_key', 'robot_fee')->get()->getRow();


if($check_tradepool_fee_format->site_value=='on')
{   

if($invest_pool_pack_count <= 0)
{
$pack_amounts = $check_tradepool_fee->site_value;
}
else
{
$pack_amounts = 0;
}

}
else
{
$pack_amounts = $check_tradepool_fee->site_value;
}

$all_amount = $pack_amounts + $pack_amount;

// check balance 

if($all_amount <= $balance)
{
$flag = 0;
}
else
{

$flag = 1;

$json['result'] = 'notok';
$json['message'] ="Insufficient Balance";

echo json_encode($json);
exit();    
}

// cehck balance end

$invest_pool_pack = $this->db->table('package_settings')->where('id',$pack_id)->get()->getRow();

// check package invest  amount 

if($invest_pool_pack)
{

$flag = 1;

if($pack_amount <= $invest_pool_pack->max_amt  &&  $pack_amount >= $invest_pool_pack->min_amt)
{
$flag = 0;
}
else
{
$flag = 1;

$json['result'] = 'notok';
$json['message'] ="Please Check Minimum and Maximum Amount..";

echo json_encode($json);
exit();   

}

}
else
{

$flag = 1;

$json['result'] = 'notok';
$json['message'] ="Please Select Package...";

echo json_encode($json);
exit();   

}

$str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$tnxid =  substr(str_shuffle($str_result), 0, 10);
$transactionid = "PTI-".$tnxid; 





$deposit_data = array(
'uusersid' => $uusersid,
'planid' => $pack_id,
'btc_amount' => $pack_amount,
'amount'     => $pack_amount,
'transhash' =>  $transactionid,
'payment_id' => 0,
'coin_id' =>0,
'confirmation'=>0,
'currency' =>1,
'compound' =>$pack_amount,
'description' => 'Member pay for Pool Trading Investment',
'invest_date' =>   date('Y-m-d h:i:s', time()),
'mature_date' =>   date('Y-m-d h:i:s', strtotime($date. ' + '.$invest_pool_pack->duration.' days')),
'run_date'    =>   date('Y-m-d h:i:s', strtotime($date. ' + 1 days')),
'status' => 'active', 
'ac_mode' => 1,
);

$builder = $this->db->table('deposit');
$builder->insert($deposit_data);
$deposit_id =  $this->db->insertID();

$historydata1 = array(
'uusersid' => $uusersid,
'amount' => $pack_amount,
'btc_amount' => $pack_amount,
'depositid'  => $deposit_id,
'type' => 'pool_invest',
'from_email' => $user_mail->email,
'payment_id' => 0,
'description' => 'Member pay for Pool Trading Investment',
'date' =>   date('Y-m-d h:i:s', time()),
'status' => 1 
);

$update_status1 = $this->db->table('history')->insert($historydata1);


if($pack_amounts>0)
{

$historydata2 = array(
'uusersid' => $uusersid,
'amount' => $pack_amounts,
'btc_amount' => $pack_amounts,
'depositid'  => $deposit_id,
'from_email' => $user_mail->email,
'type' => 'pool_invest_fee',
'payment_id' => 0,
'description' => 'Pool Trading Investment Fee',
'date' =>   date('Y-m-d h:i:s', time()),
'status' => 1 
);

$update_status1 = $this->db->table('history')->insert($historydata2);

}

/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/
// level Commission send bro

$user_name_get = $this->db->query("SELECT * FROM uusers where uusersid ='".$uusersid."'")->getRow();
$user_name = $user_name_get->fullname;

$this->level_commission($uusersid,$pack_amount,0,$deposit_id,$user_name,$uusersid);

/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/





$buy_bal = curbalance($uusersid);
$balance = str_replace(",","", $buy_bal);


if($update_status1)
{
$json['result'] = 'ok';
$json['message'] ="Pool Trading Investment SuccessFully....";
$json['balance'] = number_format($balance,2);
}
else
{
$json['result'] = 'notok';
$json['message'] ="Pool Trading Investment Not SuccessFully....";
}

echo json_encode($json);

}


}
/*-----------------------------------------  Pool Trading investment end -------------------------------*/

/*-----------------------------------------  Pool Trading investment list -------------------------------*/

public function pool_trade_list(){
$this->db = db_connect();
$this->common_model = model('CommonModel');
$session = session();
$uusersid = $session->get('uusersid');
$this->data['withdrawal'] = $this->db->query("SELECT * from deposit where uusersid = '".$uusersid."'  order by depositid desc")->getResult();
echo view('user/pool_trade_list',$this->data);

}

/*-----------------------------------------  Pool Trading investment list -------------------------------*/


/*---------------------------------  Pool Trading investment claim_pack -------------------------------*/

public function claim_pack(){

$this->db = db_connect();
$this->common_model = model('CommonModel');
$session = session();
$uusersid = $session->get('uusersid');

$package_id = $this->request->getPost('deposit_id');

$check_pack = $this->db->query("SELECT * from deposit where uusersid = '".$uusersid."' and depositid = '".$package_id."'")->getRow();

if($check_pack)
{

if($check_pack->status=="matured")
{

$deposit_data = array(
'request_status' => 1, 
);



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

$json['result'] = 'ok';

// Send Mail to admin

$send_mail = $this->send_claim_mail($uusersid);

}
else
{
$json['result'] = 'notok';
$json['message'] ="Invalid Claim Package.....";
}

}
else
{
$json['result'] = 'notok';
$json['message'] ="Invalid Claim Package.....";
}

echo json_encode($json);

}

/*---------------------------  Pool Trading investment claim_pack -------------------------------*/


public function send_claim_mail($uusersid)
{

	
	$this->db = db_connect();
	$referral1=$this->db->query("SELECT * FROM uusers WHERE uusersid='".$uusersid."'");
	$row=$referral1->getRow();

	$referal_id=$row->fullname;

	$messages = "Invesment Capital Claim Request From" . $referal_id;

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

	$this->db = db_connect();
	
	$table='admin';
	$condition = "id = '1'";
	$admin_email= $this->common_model->GetResults($table,$condition);


	$sub = 'Invesment Capital Claim Request';
	$mailid = '1';
	$mail_subject_data = $this->common_model->getMailTemplate($mailid);
	$message  = $messages;
	$message  = str_replace('#sitename', site_info_lang('site_name',1), $message);
	$mail=$this->sendmail($mail_subject_data->from_mail,$message,$sub,$mail_subject_data->from_mail);

}


/*--------------------------- commission distribute  function start ------------------------------*/    



public function site_controls($site_key){

 $site_value_get = $this->db->query("SELECT * FROM `site_controls` WHERE settings_name ='pool_invest' and site_key = '".$site_key."'")->getRow();

 return $site_value_get->site_value;

}


public function level_commission($userid,$amount,$i,$deposit_id,$user_name,$send_id)
{

$user_info = $this->db->query("SELECT * FROM `uusers_matrix` where uusersid ='".$userid."'")->getRow();

$level1 = $this->site_controls('pool_invest_level');
$level = explode(',',$level1);


$i=$i;
$getlevel = $level[$i];


if($getlevel)
{

$user_upline = $user_info->referral_id;
$user_upline_info =  $this->db->query("SELECT * FROM `uusers_matrix` where uusersid ='".$user_upline."'")->getRow();
$upline_userid = $user_upline_info->uusersid;


if($upline_userid=="")
{
$ids = '1';
}
else
{ 
$ids = $upline_userid;
}


/*-----------------------------------------------------------------------------*/
/*---------------- Check user level commission --------------------------------*/
/*-----------------------------------------------------------------------------*/

$check_level=$i;
$check_level++;

$check_user_leve = $this->check_level_commission($ids,$check_level);

if($check_user_leve=="ok")
{

if($user_upline)
{

$referal_commision = ($amount / 100) * $getlevel;

if($referal_commision!="")
{

$j=$i;
$j++;

$history_data = array(
"uusersid" => $ids,
"amount" => $referal_commision,
"description" => "Level-".$j." Commision Earned From - ".$user_name,
"type" => "bonus_commissions",
"date" => date('Y-m-d H:i:s'),
"depositid"=>$deposit_id,
"pool_amt" =>$amount,
"pool_level" =>$j,
"pool_percentage" =>$getlevel,
"from_pool_earn"  =>$send_id,
"transactionid"=> "LEVL".strtoupper(uniqid()),
);


$history_status = $this->db->table('history')->insert($history_data);

}

}


}

/*-----------------------------------------------------------------------------*/
/*---------------- Check user level commission end  --------------------------------*/
/*-----------------------------------------------------------------------------*/




$condition =  $this->db->query("SELECT * FROM `uusers_matrix` where uusersid ='".$ids."'")->getRow();
$next_upline =$condition->referral_id;

if($next_upline!="")
{
$i++;
$this->level_commission($ids,$amount,$i,$deposit_id,$user_name,$send_id);
}
}

}



	public function check_level_commission($userid,$level)
	{

	if($userid >0)
	{
	$helper_deposit = pool_deposit($userid);

	if($helper_deposit > 0)
	{

	$check_level = $this->db->query("SELECT * FROM `package_settings` where min_amt <= ".$helper_deposit." ORDER BY `package_settings`.`id` DESC " )->getRow();

	$check_level = $check_level->level;

	if($check_level >= $level)
	{
	return 'ok';
	}

	}
	else
	{
	return 'notok';
	}


	}
	else
	{
	return 'notok';
	}


	}


/*--------------------------- commission distribute  function start ------------------------------*/   

/*----------------------------- Pool Trading Profit wallet investment --------------------*/

public function pool_invest_profit_wallet()
{


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


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

$uusersid = $this->session->get('uusersid');
$buy_bal = profit_wallet($uusersid);
$balance = str_replace(",","", $buy_bal);


$pack_id=$this->request->getPost('pool_invest_pack');
$pack_amount=$this->request->getPost('pool_invest_amount');

// check balance 


$invest_pool_pack_count = $this->db->table('history')->where('type','pool_invest')->where('uusersid', $uusersid)->get()->getNumRows();

$check_tradepool_fee_format = $this->db->table('site_controls')->where('settings_name','pool_invest')->where('site_key', 'robot_fee_format')->get()->getRow();


$check_tradepool_fee = $this->db->table('site_controls')->where('settings_name','pool_invest')->where('site_key', 'robot_fee')->get()->getRow();


if($check_tradepool_fee_format->site_value=='on')
{   

if($invest_pool_pack_count <= 0)
{
$pack_amounts = $check_tradepool_fee->site_value;
}
else
{
$pack_amounts = 0;
}

}
else
{
$pack_amounts = $check_tradepool_fee->site_value;
}

$all_amount = $pack_amounts + $pack_amount;

if($all_amount <= $balance)
{
$flag = 0;
}
else
{

$flag = 1;

$json['result'] = 'notok';
$json['message'] ="Insufficient Balance";

echo json_encode($json);
exit();    
}

// cehck balance end


$invest_pool_pack = $this->db->table('package_settings')->where('id',$pack_id)->get()->getRow();


// check package invest  amount 

if($invest_pool_pack)
{

$flag = 1;

if($pack_amount <= $invest_pool_pack->max_amt  &&  $pack_amount >= $invest_pool_pack->min_amt)
{
$flag = 0;
}
else
{
$flag = 1;

$json['result'] = 'notok';
$json['message'] ="Please Check Minimum and Maximum Amount..";

echo json_encode($json);
exit();   

}

}
else
{

$flag = 1;

$json['result'] = 'notok';
$json['message'] ="Please Select Package...";

echo json_encode($json);
exit();   

}

$str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$tnxid =  substr(str_shuffle($str_result), 0, 10);
$transactionid = "PTI-".$tnxid; 


$deposit_data = array(
'uusersid' => $uusersid,
'planid' => $pack_id,
'btc_amount' => $pack_amount,
'amount'     => $pack_amount,
'transhash' =>  $transactionid,
'payment_id' => 0,
'coin_id' =>0,
'confirmation'=>0,
'currency' =>1,
'compound' =>$pack_amount,
'description' => 'Member pay for Pool Trading Investment',
'invest_date' =>   date('Y-m-d h:i:s', time()),
'mature_date' =>   date('Y-m-d h:i:s', strtotime($date. ' + '.$invest_pool_pack->duration.' days')),
'run_date'    =>   date('Y-m-d h:i:s', strtotime($date. ' + 1 days')),
'status' => 'active', 
'ac_mode' => 1,
);

$builder = $this->db->table('deposit');
$builder->insert($deposit_data);
$deposit_id =  $this->db->insertID();

$historydata1 = array(
'uusersid' => $uusersid,
'amount' => $pack_amount,
'btc_amount' => $pack_amount,
'depositid'  => $deposit_id,
'type' => 'pool_invest',
'payment_id' =>1,
'from_email' => $user_mail->email,
'description' => 'Member pay for Pool Trading Investment',
'date' =>   date('Y-m-d h:i:s', time()),
'status' => 1 
);

$update_status1 = $this->db->table('history')->insert($historydata1);


if($pack_amounts>0)
{

$historydata2 = array(
'uusersid' => $uusersid,
'amount' => $pack_amounts,
'btc_amount' => $pack_amounts,
'depositid'  => $deposit_id,
'from_email' => $user_mail->email,
'type' => 'pool_invest_fee',
'payment_id' => 1,
'description' => 'Pool Trading Investment Fee',
'date' =>   date('Y-m-d h:i:s', time()),
'status' => 1 
);

$update_status1 = $this->db->table('history')->insert($historydata2);

}

/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/
// level Commission send bro

$user_name_get = $this->db->query("SELECT * FROM uusers where uusersid ='".$uusersid."'")->getRow();
$user_name = $user_name_get->fullname;

$this->level_commission($uusersid,$pack_amount,0,$deposit_id,$user_name,$uusersid);

/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/


$buy_bal = profit_wallet($uusersid);
$balance = str_replace(",","", $buy_bal);


if($update_status1)
{
$json['result'] = 'ok';
$json['message'] ="Pool Trading Investment SuccessFully....";
$json['balance'] = number_format($balance,2);
}
else
{
$json['result'] = 'notok';
$json['message'] ="Pool Trading Investment Not SuccessFully....";
}

echo json_encode($json);

}


}
/*------------------------  Pool Trading profit wallet investment end -------------------------------*/



/*----------------------------- Pool Trading rewards wallet investment --------------------*/

public function pool_invest_reward_wallet()
{


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


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

$uusersid = $this->session->get('uusersid');
$buy_bal = reward_wallet($uusersid);
$balance = str_replace(",","", $buy_bal);


$pack_id=$this->request->getPost('pool_invest_pack');
$pack_amount=$this->request->getPost('pool_invest_amount');

// check balance 


$invest_pool_pack_count = $this->db->table('history')->where('type','pool_invest')->where('uusersid', $uusersid)->get()->getNumRows();

$check_tradepool_fee_format = $this->db->table('site_controls')->where('settings_name','pool_invest')->where('site_key', 'robot_fee_format')->get()->getRow();

$check_tradepool_fee = $this->db->table('site_controls')->where('settings_name','pool_invest')->where('site_key', 'robot_fee')->get()->getRow();


if($check_tradepool_fee_format->site_value=='on')
{   

if($invest_pool_pack_count <= 0)
{
$pack_amounts = $check_tradepool_fee->site_value;
}
else
{
$pack_amounts = 0;
}

}
else
{
$pack_amounts = $check_tradepool_fee->site_value;
}

$all_amount = $pack_amount + $pack_amounts;

if($all_amount <= $balance)
{
$flag = 0;
}
else
{

$flag = 1;

$json['result'] = 'notok';
$json['message'] ="Insufficient Balance";

echo json_encode($json);
exit();    
}

// cehck balance end

$invest_pool_pack = $this->db->table('package_settings')->where('id',$pack_id)->get()->getRow();

// check package invest  amount 

if($invest_pool_pack)
{

$flag = 1;

if($pack_amount <= $invest_pool_pack->max_amt  &&  $pack_amount >= $invest_pool_pack->min_amt)
{
$flag = 0;
}
else
{
$flag = 1;

$json['result'] = 'notok';
$json['message'] ="Please Check Minimum and Maximum Amount..";

echo json_encode($json);
exit();   

}

}
else
{

$flag = 1;

$json['result'] = 'notok';
$json['message'] ="Please Select Package...";

echo json_encode($json);
exit();   

}

$str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$tnxid =  substr(str_shuffle($str_result), 0, 10);
$transactionid = "PTI-".$tnxid; 


$deposit_data = array(
'uusersid' => $uusersid,
'planid' => $pack_id,
'btc_amount' => $pack_amount,
'amount'     => $pack_amount,
'transhash' =>  $transactionid,
'payment_id' => 0,
'coin_id' =>0,
'confirmation'=>0,
'currency' =>1,
'compound' =>$pack_amount,
'description' => 'Member pay for Pool Trading Investment',
'invest_date' =>   date('Y-m-d h:i:s', time()),
'mature_date' =>   date('Y-m-d h:i:s', strtotime($date. ' + '.$invest_pool_pack->duration.' days')),
'run_date'    =>   date('Y-m-d h:i:s', strtotime($date. ' + 1 days')),
'status' => 'active', 
'ac_mode' => 1,
);

$builder = $this->db->table('deposit');
$builder->insert($deposit_data);
$deposit_id =  $this->db->insertID();

$historydata1 = array(
'uusersid' => $uusersid,
'amount' => $pack_amount,
'btc_amount' => $pack_amount,
'depositid'  => $deposit_id,
'type' => 'pool_invest',
'payment_id' =>2,
'from_email' => $user_mail->email,
'description' => 'Member pay for Pool Trading Investment',
'date' =>   date('Y-m-d h:i:s', time()),
'status' => 1 
);

$update_status1 = $this->db->table('history')->insert($historydata1);


if($pack_amounts>0)
{

$historydata2 = array(
'uusersid' => $uusersid,
'amount' => $pack_amounts,
'btc_amount' => $pack_amounts,
'depositid'  => $deposit_id,
'from_email' => $user_mail->email,
'type' => 'pool_invest_fee',
'payment_id' => 2,
'description' => 'Pool Trading Investment Fee',
'date' =>   date('Y-m-d h:i:s', time()),
'status' => 1 
);

$update_status1 = $this->db->table('history')->insert($historydata2);

}

/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/
// level Commission send bro

$user_name_get = $this->db->query("SELECT * FROM uusers where uusersid ='".$uusersid."'")->getRow();
$user_name = $user_name_get->fullname;

$this->level_commission($uusersid,$pack_amount,0,$deposit_id,$user_name,$uusersid);

/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/


$buy_bal = reward_wallet($uusersid);
$balance = str_replace(",","", $buy_bal);


if($update_status1)
{
$json['result'] = 'ok';
$json['message'] ="Pool Trading Investment SuccessFully....";
$json['balance'] = number_format($balance,2);
}
else
{
$json['result'] = 'notok';
$json['message'] ="Pool Trading Investment Not SuccessFully....";
}

echo json_encode($json);

}


}
/*------------------------  Pool Trading reward wallet investment end -------------------------------*/



/*----------------------------- Pool Trading rewards cash investment --------------------*/

public function pool_invest_cash_wallet()
{


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


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

$uusersid = $this->session->get('uusersid');
$buy_bal = cash_wallet($uusersid);
$balance = str_replace(",","", $buy_bal);


$pack_id=$this->request->getPost('pool_invest_pack');
$pack_amount=$this->request->getPost('pool_invest_amount');

// check balance 

$invest_pool_pack_count = $this->db->table('history')->where('type','pool_invest')->where('uusersid', $uusersid)->get()->getNumRows();

$check_tradepool_fee_format = $this->db->table('site_controls')->where('settings_name','pool_invest')->where('site_key', 'robot_fee_format')->get()->getRow();

$check_tradepool_fee = $this->db->table('site_controls')->where('settings_name','pool_invest')->where('site_key', 'robot_fee')->get()->getRow();

if($check_tradepool_fee_format->site_value=='on')
{   

if($invest_pool_pack_count <= 0)
{
$pack_amounts = $check_tradepool_fee->site_value;
}
else
{
$pack_amounts = 0;
}

}
else
{
$pack_amounts = $check_tradepool_fee->site_value;
}

$all_amount = $pack_amount +$pack_amounts;

if($all_amount <= $balance)
{
$flag = 0;
}
else
{

$flag = 1;

$json['result'] = 'notok';
$json['message'] ="Insufficient Balance";

echo json_encode($json);
exit();    
}

// cehck balance end

$invest_pool_pack = $this->db->table('package_settings')->where('id',$pack_id)->get()->getRow();

// check package invest  amount 

if($invest_pool_pack)
{

$flag = 1;

if($pack_amount <= $invest_pool_pack->max_amt  &&  $pack_amount >= $invest_pool_pack->min_amt)
{
$flag = 0;
}
else
{
$flag = 1;

$json['result'] = 'notok';
$json['message'] ="Please Check Minimum and Maximum Amount..";

echo json_encode($json);
exit();   

}

}
else
{

$flag = 1;

$json['result'] = 'notok';
$json['message'] ="Please Select Package...";

echo json_encode($json);
exit();   

}

$str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$tnxid =  substr(str_shuffle($str_result), 0, 10);
$transactionid = "PTI-".$tnxid; 


$deposit_data = array(
'uusersid' => $uusersid,
'planid' => $pack_id,
'btc_amount' => $pack_amount,
'amount'     => $pack_amount,
'transhash' =>  $transactionid,
'payment_id' => 0,
'coin_id' =>0,
'confirmation'=>0,
'currency' =>1,
'compound' =>$pack_amount,
'description' => 'Member pay for Pool Trading Investment',
'invest_date' =>   date('Y-m-d h:i:s', time()),
'mature_date' =>   date('Y-m-d h:i:s', strtotime($date. ' + '.$invest_pool_pack->duration.' days')),
'run_date'    =>   date('Y-m-d h:i:s', strtotime($date. ' + 1 days')),
'status' => 'active', 
'ac_mode' => 1,
);

$builder = $this->db->table('deposit');
$builder->insert($deposit_data);
$deposit_id =  $this->db->insertID();

$historydata1 = array(
'uusersid' => $uusersid,
'amount' => $pack_amount,
'btc_amount' => $pack_amount,
'depositid'  => $deposit_id,
'type' => 'pool_invest',
'payment_id' =>3,
'from_email' => $user_mail->email,
'description' => 'Member pay for Pool Trading Investment',
'date' =>   date('Y-m-d h:i:s', time()),
'status' => 1 
);

$update_status1 = $this->db->table('history')->insert($historydata1);


if($pack_amounts>0)
{

$historydata2 = array(
'uusersid' => $uusersid,
'amount' => $pack_amounts,
'btc_amount' => $pack_amounts,
'depositid'  => $deposit_id,
'from_email' => $user_mail->email,
'type' => 'pool_invest_fee',
'payment_id' => 3,
'description' => 'Pool Trading Investment Fee',
'date' =>   date('Y-m-d h:i:s', time()),
'status' => 1 
);

$update_status1 = $this->db->table('history')->insert($historydata2);

}

/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/
// level Commission send bro

$user_name_get = $this->db->query("SELECT * FROM uusers where uusersid ='".$uusersid."'")->getRow();
$user_name = $user_name_get->fullname;

$this->level_commission($uusersid,$pack_amount,0,$deposit_id,$user_name,$uusersid);

/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/


$buy_bal = cash_wallet($uusersid);
$balance = str_replace(",","", $buy_bal);


if($update_status1)
{
$json['result'] = 'ok';
$json['message'] ="Pool Trading Investment SuccessFully....";
$json['balance'] = number_format($balance,2);
}
else
{
$json['result'] = 'notok';
$json['message'] ="Pool Trading Investment Not SuccessFully....";
}

echo json_encode($json);

}


}
/*------------------------  Pool Trading cash wallet investment end -------------------------------*/

}
