<?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\WalletCoreAPI;
use App\Libraries\Google_authendicator;

error_reporting(0);


require_once(dirname(__DIR__).'/payout.php');
// class Withdraw extends CI_Controller {

class Withdraw extends BaseController {

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

        $this->uri = service('uri');
        $this->uri = current_url(true);

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

        // user login only
        if($this->session->get('user_login') || $this->session->get('admin_login')) {

            // form validation library
            $this->finance_model = model('finance_model');
            
        } else {
            $this->session->set('user_last_page', current_url(true));
            return  redirect()->to('user/login');
        }

    }

    public function index() {

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



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

        if($userinfo->user_withdraw!='1')
        {
            $this->session->setFlashData('error_message', "Withdraw Fund Request Access Restricted!... Please contact Support team");

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


        $this->uri = new \CodeIgniter\HTTP\URI();
        $this->uri = service('uri');
        $this->uri = current_url(true);

        $id =  $this->request->uri->getSegment('2');

        $condition = "uusersid = '".$this->session->get('uusersid')."' AND contents!=''";
        $this->data['payment_list'] = $this->common_model->GetResults('uusers_payment',$condition);

        $withdraw_data = $this->common_model->GetSettingall('withdraw');
        $this->data['action'] = base_url().'/user/validatewithdraw';
        foreach ($withdraw_data as $row) {
            $this->data[$row->site_key] = $row->site_value;
        }

            $check_factor = $this->check_two_factor(1);
            if($check_factor==1)
            {
                echo view('user/withdraw',$this->data);
            }
    

    }



        public function transfer() {

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


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

        if($userinfo->user_transfer!='1')
        {
            $this->session->setFlashData('error_message', "Fund transfer Request Access Restricted!... Please contact Support team");

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

        $this->uri = new \CodeIgniter\HTTP\URI();
        $this->uri = service('uri');
        $this->uri = current_url(true);

        $id =  $this->request->uri->getSegment('2');

        $condition = "uusersid = '".$this->session->get('uusersid')."' AND contents!=''";
        $this->data['payment_list'] = $this->common_model->GetResults('uusers_payment',$condition);

        $withdraw_data = $this->common_model->GetSettingall('withdraw');
        $this->data['action'] = base_url().'/user/validatetransfer';
        foreach ($withdraw_data as $row) {
            $this->data[$row->site_key] = $row->site_value;
        }

   
        $check_factor = $this->check_two_factor(2);

        if($check_factor==1)
        {

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

        }
        // }

    }


    public function verifyregcode1()
    {

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

        
        $sub = "Transfer Request 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->username, $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    = "Transfer Request Email verification";
            
            $this->sendmail($user->email, $user->username, $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 verifyregcode()
    {
  
        $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;

        
        $sub = "Withdraw Request 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->username, $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    = "Withdraw Request Email verification";
            
            $this->sendmail($user->email, $user->username, $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 validatetransfer()
    {
        $this->session = \Config\Services::session();
        helper('text');
        $this->uri = service('uri');
        $this->uri = current_url(true);
        $payment_id=9;
        $payment_data = $this->common_model->GetPayment($payment_id);
        $public_key = $payment_data[3]->payment_value;
        $private_key = $payment_data[2]->payment_value;
         $coid = 'NyYmemh5aXA=';
       //$coid=$this->uri->getSegment('5');
        $this->form_validation = \Config\Services::validation();

        $myencrypt = new MyEncrypt;
        $coinid = $myencrypt->decode($coid);


        $this->db = db_connect();
        $this->session = session();


        if($this->request->getpost()) 
        {
         
            $this->form_validation->setRules([

                "amount" => [
                    "label" => "Amount", 
                    "rules" => "trim|required"
                ],

            ]);
            $this->form_validation->setRules([
                    "recv_id" => [
                        "label" => "Receiver name", 
                        "rules" => "trim|required"
                    ],
                ]);

                $this->form_validation->setRules([
                    "sec_pin" => [
                        "label" => "Security pin", 
                        "rules" => "trim|required"
                    ],
                ]);



          


            if ($this->form_validation->withRequest($this->request)->run() == TRUE) 
            {
    
              
                
               
                $trans_amount = $this->request->getPost('org_amt');
                $uusersid = $this->session->get('uusersid');
                echo $uusersid;
              
                $coinid = 1;

                $trans_fee = $this->request->getpost('trans_fee');
                $receiver_id = $this->request->getpost('recv_id');
                // $security_pin = $this->request->getpost('sec_pin');

              
                $withdraw_data = $this->common_model->GetSettingall('withdraw');
                
                foreach ($withdraw_data as $row) {
                    $withdata[$row->site_key] = $row->site_value;
                }

               

                

                $withdraw_condition = "uusersid = '".$uusersid."' AND type IN ('transfer')";

                switch ($withdata['trans_period_type']) {

                    case 'day':
                    $withdraw_condition .=  "AND DATE(date) = CURDATE()";
                    $withdraw_limit_over = "transfer_daily_limit";
                    break;

                    case 'week':
                    $withdraw_condition .=  "AND YEARWEEK(date) = YEARWEEK(CURDATE())";
                    $withdraw_limit_over = "transfer_weekly_limit";
                    break;

                    case 'month':
                    $withdraw_condition .=  "AND MONTH(date) = MONTH(CURDATE())";
                    $withdraw_limit_over = "transfer_monthly_limit";
                    break;

                    case 'year':
                    $withdraw_condition .=  "AND YEAR(date) = YEAR(CURDATE())";
                    $withdraw_limit_over = "transfer_yearly_limit";
                    break;
                }
                // echo"<pre>";
                // print_r($withdraw_condition);
                // echo"</pre>";
               $check_withdraw = $this->finance_model->GetTransactionsCount($withdraw_condition);

   

                
                $flags=0;
                if($withdata)
                {
                    if($check_withdraw < $withdata['trans_limit'])
                    $flags=1;
                    else{
                    $this->session->setFlashData('error_message', lang('language_lang.'.$withdraw_limit_over));
                    return  redirect()->to('transfer');
                    }
                }
                else
                {
                    $flags=1;
                }
                
                $receiver_info = $this->db->table('uusers')->where('username',$receiver_id)->get()->getRow();
                $sender_info = $this->db->table('uusers')->where('uusersid',$uusersid)->get()->getRow();

                  

                if($flags=='1')  
                {
                   
                    $txn_id = strtoupper(random_string('alnum', 16));
                    $ac_mode = 1;
                     $description = "Fund Transfered to ".$receiver_info->username;
                    $trans_data = array(
                    "uusersid" => $this->session->get('uusersid'),
                    "amount"    =>  $trans_amount,
                    "type"     => 'transfer',
                    "description" => $description,
                    'address' => $receiver_info->email,
                    "receiver_id" => $receiver_info->uusersid,
                    "date"     =>  date("Y-m-d H:i:s"),
                    "transactionid" => $txn_id,
                    "currency"=>$coinid,
                    "ac_mode"=>$ac_mode,
                    "user_group"    => $sender_info->new_entry,
                    "from_email" => $receiver_info->email,
                   
                );
               
                $description = "Fund Received from ".$sender_info->username;
                $trans_data1 = array(
                        "uusersid" => $receiver_info->uusersid,
                        "amount"    =>  $trans_amount,
                        "type"     => 'fund_received',
                        "description" => $description,
                        "address"   =>  $sender_info->email,
                        "date"     =>  date("Y-m-d H:i:s"),
                        "transactionid" => $txn_id,
                        "user_group"    => $receiver_info->new_entry,
                        "from_email" => $sender_info->email
                     
                    );
                    if($trans_fee > 0) 
                    { 
                            $trans_fee_data = array(
                                "uusersid" => $this->session->get('uusersid'),
                                "amount"    =>  $trans_fee,
                                "type"   =>  "transfer_fee",
                                "description" => "Transfer fee",
                                "date"     =>  date("Y-m-d H:i:s"),
                                "transactionid" => strtoupper(random_string('alnum', 16)),
                                "user_group"    => $sender_info->new_entry,
                                "from_email" => $sender_info->email
                            );
                    }
                                $this->db = db_connect();
                                $query_status1 = $this->db->table('history')->insert($trans_data);

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

                                $query_status2 = $this->db->table('history')->insert($trans_data1);
                                $query_status = $this->db->table('history')->insert($trans_fee_data);

                                
                                // // sent mail to user
                                 $subject = 'Fund Transfered Information';
                                $mailid = '34';
                                $mail_subject_data = $this->common_model->getMailTemplate($mailid);
                                $message  = str_replace('[FIRSTNAME]', $sender_info->fullname, $mail_subject_data->message);
                                $message  = str_replace('[TXTAMT]', $withdraw_amount, $message);
                                $message  = str_replace('[WITHDRAWDATE]', date("Y-m-d H:i:s"), $message);
                                $message  = str_replace('[TXTAMT]', $amount, $message);
                                $message  = str_replace('[transid]', $txn_id, $message);
                                $message  = str_replace('[USERNAME]', $receiver_info->fullname, $message);
                                $message  = str_replace('[EMAIL]', $receiver_info->email, $message);
                                $message  = str_replace('#adminemill', $mail_subject_data->from_mail, $message);
                                $message  = str_replace('#sitename', site_info_lang('site_name',$this->session->get('langid')), $message);
                                if($mail_subject_data->status=='1')
                                {
                                 $mail_status = $this->sendmail($sender_info->email, $sender_info->fullname, $subject, $message,$mail_subject_data->from_mail);
                                }



                                // $subject = 'Fund Received Information';
                                 $mailid = '35';
                                 $mail_subject_data = $this->common_model->getMailTemplate($mailid);
                                 $message  = str_replace('[FIRSTNAME]', $receiver_info->fullname, $mail_subject_data->message);
                                 $message  = str_replace('[TXTAMT]', $withdraw_amount, $message);
                                 $message  = str_replace('[WITHDRAWDATE]', date("Y-m-d H:i:s"), $message);
                                 $message  = str_replace('[transid]', $txn_id, $message);
                                 $message  = str_replace('[USERNAME]', $sender_info->fullname, $message);
                                 $message  = str_replace('[EMAIL]', $sender_info->email, $message);
                                 $message  = str_replace('#adminemill', $mail_subject_data->from_mail, $message);
                                 $message  = str_replace('#sitename', site_info_lang('site_name',$this->session->get('langid')), $message);

                                if($mail_subject_data->status=='1')
                                {
                                $mail_status = $this->sendmail($receiver_info->email, $receiver_info->fullname, $subject, $message,$mail_subject_data->from_mail);
                                }

                                // if($query_status) {
                                //     $this->session->setFlashdata('success_message', lang('user_withdraw_success_message'));
                                //     return  redirect()->to('transfer/');
                                // } else {
                                //     $this->session->setFlashdata('error_message', "Withdrawal failed");
                                //     return  redirect()->to('transfer/');
                                // }


                                
                if($query_status1 && $query_status2) {
                  $notification = array(
                    'uusersid' => $uusersid, 
                    'message'  => 'Transfer to '. $receiver_id.' -'.$trans_amount.' succeeded',
                    'created_date' => date('Y-m-d H:i:s')
                    );
                    $this->db->table('notification_table')->insert($notification);
                $this->session->setFlashdata('success_message', "Transfer Completed");
                return  redirect()->to('transfer');  
                }else{
                $this->session->setFlashdata('error_message', "Transfer failed");
                return  redirect()->to('transfer');
                }   
            }

            }       
        }       
    }

    public function validategastransfer()
    {
        $this->session = \Config\Services::session();
        $this->form_validation = \Config\Services::validation();
        $this->db = db_connect();
        helper('text');

     
        if($this->request->getpost()) 
        {
         
         
            $this->form_validation->setRules([

                "amount" => [
                    "label" => "Amount", 
                    "rules" => "trim|required"
                ],

            ]);

            
            if ($this->form_validation->withRequest($this->request)->run() == TRUE) 
            {
                $gas_amount = $this->request->getPost('amount');
                $txn_id = strtoupper(random_string('alnum', 16));

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

                $trans_data = array(
                        "uusersid" => $this->session->get('uusersid'),
                        "amount"    =>  $gas_amount ,
                        "type"     => 'transfer_gaswallet',
                        "description" => "Fund transfered to gas wallet",
                        "address"   =>  $sender_info->email,
                        "date"     =>  date("Y-m-d H:i:s"),
                        "transactionid" => $txn_id,
                        "user_group"    => $sender_info->new_entry,
                        "from_email" => $sender_info->email
                     
                    );
                $query_status = $this->db->table('history')->insert($trans_data);
                $last_update=$this->db->InsertID();

                if($query_status) 
                {

                    $notification = array(
                      'uusersid' =>  $this->session->get('uusersid'), 
                      'message'  => 'Transfer gas amount -'.$gas_amount.' succeeded',
                      'created_date' => date('Y-m-d H:i:s')
                      );
                      $this->db->table('notification_table')->insert($notification);



                    $referral_info = $this->db->table("uusers")->where('uusersid',$sender_info->referral_id)->get()->getRow();
                    if($referral_info)
                    {
                        $this->levelcomission($gas_amount,$referral_info->uusersid,$last_update,0);
                    }

                    /*$rank_info = $this->db->table("rewardsettings")->where('id',$referral_info->rankid)->get()->getRow();

                    if($rank_info)
                    {
                        $gas_reward=$rank_info->gas_reward;
                        $reward_balance=$gas_amount * $gas_reward/100;
                        $trans_data1 = array(
                            "uusersid" => $referral_info->uusersid,
                            "amount"    =>  $reward_balance ,
                            "type"     => 'commissions',
                            "description" => "Gas wallet Reward Earned",
                            "address"   =>  $sender_info->email,
                            "date"     =>  date("Y-m-d H:i:s"),
                            "transactionid" => $txn_id,
                            "from_email" => $sender_info->email
                        
                        );
                        $query_status1 = $this->db->table('history')->insert($trans_data1);

                        $notification = array(
                            'uusersid' =>  $referral_info->uusersid, 
                            'message'  => 'Gas wallet Reward bonus Earned -'.$reward_balance.' From '.$sender_info->username,
                            'created_date' => date('Y-m-d H:i:s')
                            );
                            $this->db->table('notification_table')->insert($notification);


                    }*/

                      
                  $this->session->setFlashdata('success_message', "Transfer Completed");
                  return  redirect()->to('transfer');  
                  }else{
                  $this->session->setFlashdata('error_message', "Transfer failed");
                  return  redirect()->to('transfer');
                  } 

            
            }

        }
    }

    public function levelcomission($amount,$referral,$reference_id,$level)
    {
        $this->session = \Config\Services::session();
        $this->form_validation = \Config\Services::validation();
        $this->db = db_connect();
        $userinfo = $this->db->table("uusers")->where('uusersid',$this->session->get('uusersid'))->get()->getRow();
        $referral_info = $this->db->table("uusers")->where('uusersid',$referral)->get()->getRow();
        $rank=$referral_info->rankid;
        if($rank=='' || $rank=='0')
        {
            $rank='0';    
        }

        $get_row=$this->db->query("select * from history where type='commissions' and referance_id='".$reference_id."' and rankid='".$rank."'")->getNumRows();

      
        if($get_row=='0' || $get_row=='')
        {
             if($rank=='0')
             {
                $remain_calculate='20';
                $description = "Gas wallet Reward Earnings Received from -".$userinfo->username;
                $update_rank='0';
             }
             else 
             {
                $get_rank=$this->db->query("select * from rewardsettings where id='".$rank."'")->getRow();
                $get_rows=$this->db->query("select sum(rank_perc) as rank_perc from history where type='commissions' and referance_id='".$reference_id."'")->getRow();
               
                if(!empty($get_rows->rank_perc))
                {
                    
                    $rank_percentage=$get_rows->rank_perc;
                    $remain_calculate=$get_rank->gas_reward - $rank_percentage;
                
                }
                else
                {
                    
                    $remain_calculate= $get_rank->gas_reward;
                    
                }
                $update_rank=$get_rank->id;
                
                $description ="Gas wallet Earnings for ".$get_rank->rank_name." Received From-".$userinfo->username;

             }
             if($remain_calculate > 0)
             {

                $txn_id = strtoupper(random_string('alnum', 16));
                
                $reward_balance=$amount * $remain_calculate/100;
                $trans_data1 = array(
                    "uusersid" => $referral_info->uusersid,
                    "amount"    =>  $reward_balance,
                    "type"     => 'commissions',
                    "description" => $description,
                    "address"   =>  $userinfo->email,
                    "date"     =>  date("Y-m-d H:i:s"),
                    "referance_id" => $reference_id,
                    "rank_perc" => $remain_calculate,
                    "rankid" => $update_rank,
                    "transactionid" => $txn_id,
                    "user_group"    => $referral_info->new_entry,
                    "from_email" => $userinfo->email
                
                );

                $query_status1 = $this->db->table('history')->insert($trans_data1);

                

                $notification = array(
                    'uusersid' =>  $referral_info->uusersid, 
                    'message'  => $description,
                    'created_date' => date('Y-m-d H:i:s')
                    );
                    $this->db->table('notification_table')->insert($notification);
             }

        }
        if($referral_info->referral_id >0)
        {
           
            $level++;
            $this->levelcomission($amount,$referral_info->referral_id,$reference_id,$level);
        }

    }

    public function withdraw_details(){
        $session = session();
        $uusersid = $session->get('uusersid');
        $this->data['withdrawal'] = $this->db->query("Select * from history where type='withdrawal' and uusersid = '".$uusersid."' order by historyid desc")->getResult();
         echo view('user/withdraw_details',$this->data);
    }

    public function transfer_details(){
        $session = session();
        $uusersid = $session->get('uusersid');
        $this->data['withdrawal'] = $this->db->query("Select * from history where type in ('transfer','fund_received') and uusersid = '".$uusersid."' order by historyid desc")->getResult();
         echo view('user/transfer_details',$this->data);
    }

    public function deposit_details(){
         $session = session();
        $uusersid = $session->get('uusersid');
        $this->data['deposit'] = $this->db->query("Select * from history where type='deposit' and uusersid = '".$uusersid."' order by historyid desc")->getResult();
         echo view('user/deposit_details',$this->data);
    }



    public function validatewithdraw()
    {
        $this->session = \Config\Services::session();
        helper('text');
        $this->uri = service('uri');
        $this->uri = current_url(true);
        $payment_id=9;
        $payment_data = $this->common_model->GetPayment($payment_id);
        $public_key = $payment_data[3]->payment_value;
        $private_key = $payment_data[2]->payment_value;
       //$this->request->uri->getSegment('2');

        $coid = 'NyYmemh5aXA=';
       //$coid=$this->uri->getSegment('5');
        $this->form_validation = \Config\Services::validation();

        $myencrypt = new MyEncrypt;
        $coinid = $myencrypt->decode($coid);



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

            $this->form_validation->setRules([

                "amount" => [
                    "label" => "Amount", 
                    "rules" => "trim|required"
                ],

            ]);
            $this->form_validation->setRules([
                    "address" => [
                        "label" => "Address", 
                        "rules" => "trim|required"
                    ],
            ]);




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

               
                $withdraw_amount = $this->request->getPost('org_amt');
                $address = $this->request->getPost('address');
                $uusersid = $this->session->get('uusersid');
                $withdraw_fee = $this->request->getPost('trans_fee');
                $coinid = 1;

                $withdraw_data = $this->common_model->GetSettingall('withdraw');
                
                foreach ($withdraw_data as $row) {
                    $withdata[$row->site_key] = $row->site_value;
                }

               

                

                $withdraw_condition = "uusersid = '".$uusersid."' AND type IN ('withdrawal')";

                switch ($withdata['with_period_type']) {
                    case 'day':
                    $withdraw_condition .=  "AND DATE(date) = CURDATE()";
                    $withdraw_limit_over = "withdraw_daily_limit";
                    break;

                    case 'week':
                    $withdraw_condition .=  "AND YEARWEEK(date) = YEARWEEK(CURDATE())";
                    $withdraw_limit_over = "withdraw_weekly_limit";
                    break;

                    case 'month':
                    $withdraw_condition .=  "AND MONTH(date) = MONTH(CURDATE())";
                    $withdraw_limit_over = "withdraw_monthly_limit";
                    break;

                    case 'year':
                    $withdraw_condition .=  "AND YEAR(date) = YEAR(CURDATE())";
                    $withdraw_limit_over = "withdraw_yearly_limit";
                    break;
                }
                
                $check_withdraw = $this->finance_model->GetTransactionsCount($withdraw_condition);

                
                $flags=0;
                if($withdata || 1)
                {
                    if($check_withdraw < $withdata['with_limit'])
                    $flags=1;
                    else{
                    $this->session->setFlashData('error_message', lang('language_lang.'.$withdraw_limit_over));
                    return  redirect()->to('withdrawfund');
                    }
                }
                else
                {
                    $flags=1;
                }

                if($flags=='1')  
                {
                    $txn_id = strtoupper(random_string('alnum', 16));
                    $user = $this->common_model->GetUser($this->session->get('uusersid'));
                    $ac_mode = 1;
                    
                    if($withdraw_amount > 0) 
                    {
                        
                        $ac_mode='2';
                        $withdraw_data = array(
                            "uusersid" => $this->session->get('uusersid'),
                            "amount"    =>  $withdraw_amount,
                            "type"     => 'withdraw_request',
                            "description" => "Withdraw Request",
                            "address"   =>  $address,
                            "date"     =>  date("Y-m-d H:i:s"),
                            "payment_id"    =>  '9',
                            "transactionid" => $txn_id,
                            "currency"=>$coinid,
                            "user_group"    => $user->new_entry,
                            "ac_mode"=>$ac_mode
                        );
                        $query_status1 = $this->db->table('history')->insert($withdraw_data);
                        $insertedID = $this->db->insertID();
                            
                        $withdraw_fee_data = array(
                            "uusersid" => $this->session->get('uusersid'),
                            "amount"    =>  $withdraw_fee,
                            "type"   =>  "withdraw_fee",
                            "description" => "Withdraw fee",
                            "date"     =>  date("Y-m-d H:i:s"),
                            "payment_id"    =>  '9',
                            "transactionid" => strtoupper(random_string('alnum', 16)),
                            "currency"=>$coinid,
                            "ac_mode"=>$ac_mode,
                            "user_group"    => $user->new_entry,
                            "substatus"=>$insertedID
                        );

                        $query_status2 = $this->db->table('history')->insert($withdraw_fee_data);


                            // $subject = 'Withdraw Requested Information';
                            // $mailid = '27';
                            // $mail_subject_data = $this->common_model->getMailTemplate($mailid);
                            // $message  = str_replace('[NAME]', $user->fullname, $mail_subject_data->message);
                            // $message  = str_replace('[TXTAMT]', $withdraw_amount, $message);
                            // $message  = str_replace('[WITHDRAWDATE]', date("Y-m-d H:i:s"), $message);
                            // $message  = str_replace('[PAYEMENT]', $address, $message);
                            // $message  = str_replace('[transid]', $txn_id, $message);
                            // $message  = str_replace('#adminemill', $mail_subject_data->from_mail, $message);
                            // $message  = str_replace('#sitename', site_info_lang('site_name',$this->session->get('langid')), $message);
                            
                            // if($mail_subject_data->status=='1')
                            // {
                            //     $mail_status = $this->sendmail($mail_subject_data->from_mail, $mail_subject_data->from_mail, $subject, $message,$mail_subject_data->from_mail);
                            // }



                            /*$subject = 'Withdraw Requested Information';
                            $mailid = '27';
                            $mail_subject_data = $this->common_model->getMailTemplate($mailid);
                            $message  = str_replace('[NAME]', $user->fullname, $mail_subject_data->message);
                            $message  = str_replace('[TXTAMT]', $withdraw_amount, $message);
                            $message  = str_replace('[WITHDRAWDATE]', date("Y-m-d H:i:s"), $message);
                            $message  = str_replace('[PAYEMENT]', $address, $message);
                            $message  = str_replace('[transid]', $txn_id, $message);
                            $message  = str_replace('#adminemill', $mail_subject_data->from_mail, $message);
                            $message  = str_replace('#sitename', site_info_lang('site_name',$this->session->get('langid')), $message);
                            
                            if($mail_subject_data->status=='1')
                            {
                                $mail_status = $this->sendmail($user->email, $user->fullname, $subject, $message,$mail_subject_data->from_mail);
                            }*/


                            // $subject = 'Withdraw Requested Information';
                            // $mailid = '6';
                            // $mail_subject_data = $this->common_model->getMailTemplate($mailid);
                            // $message  = str_replace('[NAME]', $user->fullname, $mail_subject_data->message);
                            // $message  = str_replace('[TXTAMT]', $withdraw_amount, $message);
                            // $message  = str_replace('[WITHDRAWDATE]', date("Y-m-d H:i:s"), $message);
                            // $message  = str_replace('[PAYEMENT]', $address, $message);
                            // $message  = str_replace('[transid]', $txn_id, $message);
                            // $message  = str_replace('#adminemill', $mail_subject_data->from_mail, $message);
                            // $message  = str_replace('#sitename', site_info_lang('site_name',$this->session->get('langid')), $message);
                            
                            // if($mail_subject_data->status=='1')
                            // {
                            //     $mail_status = $this->sendmail($user->email, $user->fullname, $subject, $message,$mail_subject_data->from_mail);
                            // }

                            $this->session->setFlashdata('success_message', "Withdraw Requested. wait for admin confirmation");
                            return  redirect()->to('withdrawfund');  
                        }
                    
                }
            }
            else
            {
                $this->session->setFlashdata('error_message', "Withdrawal failed !!! Please contact admin for further information");
                return  redirect()->to('withdrawfund');
            }
        }    
        else
        {
            return  redirect()->to('withdrawfund');
        }
    }       




    
    // server side withdraw amount validtion
    function check_withdraw_amount($str, $gateway_id)
    {

        $coid=$this->uri->segment(4);
        $myencrypt = new MyEncrypt;
        $coinid = $myencrypt->decode($coid);
        $id=$coinid;
        $first_dat=$this->db->query("select * from coin_info where coid='".$id."'");  
        $fir_d=$first_dat->result();
        $coin_det=$fir_d[0];
        $fees=$coin_det->transfer_fees;
        $coin_decimal=$coin_det->coin_decimal;
        $with_min=$coin_det->min_withdraw;
        $buy_bal=curbalance($this->session->userdata('uusersid'),$id);
        $balance=str_replace(",","", $buy_bal);
        $amount_value = $this->input->post('amount');
        $withdrawfee=$fees*$amount_value/100;
        $withdraw_amount = $amount_value + $withdraw_fee;

        $balance_amount = $balance;
        if($balance_amount < $withdraw_amount) {
            $this->form_validation->set_message('check_withdraw_amount', lang("withdraw_payment_insufficent_balance"));
            return false;
        } 

        if($withdraw_amount < $with_min)
        {
            $this->form_validation->set_message('check_withdraw_amount', lang("withdraw_amount_error_message"));
            return false;
        }
        else
        {
            return true;
        }
    }
    

    function withdrawfee($id='') {
        
        $this->uri = service('uri');
        $this->uri = current_url(true);
    //$id=$this->uri->getSegment('5');
        $id =  $this->request->uri->getSegment('2');

        $first_dat=$this->db->query("select * from coin_info where coid='".$id."'");  
        $fir_d=$first_dat->getResult();

        $coin_det=$fir_d[0];
        $fees=$coin_det->transfer_fees;
        $coin_decimal=$coin_det->coin_decimal;

        $withdraw_datas = $this->common_model->GetSettingall('withdraw');
        $coin_dets = $withdraw_datas[0]->site_value;


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


        if($amount_value) {

            $withdraw_data = $this->common_model->GetSettingall('withdraw');
            foreach ($withdraw_data as $row) {
                $withdata[$row->site_key] = $row->site_value;
            }
            
            $fee_percent = $coin_dets * $amount_value;
            $final_value = $fee_percent / 100 ;


            echo number_format($final_value,5);
        }
        
    }

    function checkfee($gateway_id='') {

        $this->uri = service('uri');
        $this->uri = current_url(true);
        $id =  $this->request->uri->getSegment('2');

        $id=$id;

        $first_dat=$this->db->query("select * from coin_info where coid='".$id."'");  
        $fir_d=$first_dat->getResult();
        $coin_det=$fir_d[0];
        $fees=$coin_det->transfer_fees;


        $coin_decimal=$coin_det->coin_decimal;
        $with_min=$coin_det->min_withdraw;
        $buy_bal=curbalance($this->session->get('uusersid'),$id);

        

        $balance=str_replace(",","", $buy_bal);
        $amount_value = service('request')->getPost('amount');
        $withdrawfee=$fees*$amount_value/100;

     
        
        $withdraw_amount = $amount_value + $withdraw_fee;

        

        if($amount_value) {

            if ($withdraw_amount < $with_min) 
            {
                $json['valid'] = false;
                $json['message'] = 'Withdraw amount between'." ".$with_min.' '.strtoupper($coin_det->coin_symbol);
            } 
            else 
            {
                $json['valid'] = true;
            }
        }


        $balance_amount = $balance;


       
   
        
        if($balance_amount) {


            if($balance_amount < $withdraw_amount) {
              
                $json['valid'] = false;
                $json['message'] = "Insufficient Balance";
            }

        }

        
       
        echo json_encode($json);
    }


    public function validtranspassword(){
        $post_pwd = $this->input->post('currentpin');
        $condition = "uusersid = '".$this->session->userdata('uusersid')."'";
        $uemail = $this->common_model->GetRow('uusers_security', $condition);
        $hashed_password = $uemail->trans_pin;
        if ($hashed_password == crypt(urlencode($this->input->post('currentpin')), $hashed_password)) {
            
            $json['valid'] = true;

        }   
        
        else {
            $json['valid'] = false;
            $json['message']=lang("trans_pin_error");
        }
        
        echo json_encode($json);

    }


    function checkbalance($id) {

        // $this->uri = service('uri');
        // $this->uri = current_url(true);
  //  // $id=$this->uri->getSegment('5');
        // $id =  $this->request->uri->getSegment('2');


        // $currency_info = defaultcurrency();
        $sender_id  = $this->session->get('uusersid');
        

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


        if($balance > 0) {
            // if(service('request')->getPost('payment')){
            //  $json['valid'] = true;
            // } else {
                echo number_format($balance,2, '.', '');
            //}
        } else {
            // if(service('request')->getPost('payment')){
            //  $json['valid'] = false; 
            //  $json['message'] = "The selected gateway have Insufficient balance";
            // } else {
                echo number_format(0,2, '.', '');
            //}
        }
        // if(isset($json)){
        //  echo json_encode($json);
        // }
        
    }
    
    private function check_balance($sender_id){

        if($sender_id){
        $balance = curbalance($sender_id);
        // $usd_balance=$this->balance_check($sender_id,'1');

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

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




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

        // if($sender_id) {

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

     //        // calculate user expenses
        //  $condition1 = "uusersid = '".$sender_id."' AND type IN (".$expenses_type.")";
     //        // $condition1 = 'uusersid ='."'".$sender_id."'".'AND payment_id ='."'".$gateway_id."'"."and (".$expenses_type.")";
        //  $expenses = $this->common_model->GetEarnings('history',$condition1);
        //  $Earnings = ($earnings->earnamt) ? $earnings->earnamt : '0';
        //  $Expenses = ($expenses->earnamt) ? $expenses->earnamt : '0' ;
     //       /* $AvailableBalance = $Earnings - $Expenses;
            
     //        if($AvailableBalance<0)
     //        $AvailableBalance=0;*/

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

    }

     public function email_verify()
    {
        $this->session = session();
        $this->db = db_connect();
        $userid = $this->session->get('uusersid');
        $code=$this->request->getPost('email');
        $user_available = $this->db->query("Select * from uusers where email = '".$code."'")->getRow();
        if($user_available){
              $confirm = $this->db->table('history')->where('uusersid',$user_available->uusersid)->where('type','activation')->where('status',1)->get()->getRow();
            if($confirm) 
            echo 1;
            else
            echo 3;
        }else{
             echo 2;
        }
    }


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

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

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

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

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

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

        }




        return $amount;

    }



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


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

    public function validate_email()
    {
        $this->session = session();
        $this->db = db_connect();
        $userid = $this->session->get('uusersid');
        $code=$this->request->getPost('email_address');
        $user_available = $this->db->query("Select * from uusers where email = '".$code."'")->getRow();
        if($user_available){
              $confirm = $this->db->table('history')->where('uusersid',$user_available->uusersid)->where('type','activation')->where('status',1)->get()->getRow();
            if($confirm) 
            $json['valid'] = true;
            else
            $json['valid'] = false;
        }else{
             $json['valid'] = false;
        }
        echo json_encode($json);
    }

    public function checkpin(){

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

            $condition = "uusersid = '".$this->session->get('uusersid')."'";
            $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)) {

                $id=$this->session->get('log_id');
                $this->session->set('temp_access',true);
                return redirect()->to('withdrawfund');
                
            }
            else{
                $this->session->setFlashdata('error_message', lang("language_lang.trans_pin_error"));
                return redirect()->to('withdraw/checkpin');
            }
        } else {
            $this->data['action'] = base_url().'/withdraw/checkpin';
            echo view('user/transaction_pin',$this->data);
        }

    }
    


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


    public function testing()
    {
        $PassPhrase = 'Arm@123456';
        $login_id = '6401844';
        $payer_account = 'U11591976';
        
        $payee_account = 'U12234173';
        $payment_amount = 0.01;
        
        $f=fopen("https://perfectmoney.is/acct/confirm.asp?AccountID=".$login_id."&PassPhrase=".$PassPhrase."&Payer_Account=".$payer_account."&Payee_Account=".$payee_account."&Amount=".$payment_amount, "rb");

        if($f===false){
            $error_message = 'error openning url';
        }

        // getting data
        $out=array(); $out="";
        while(!feof($f)) $out.=fgets($f);

        fclose($f);

        // searching for hidden fields
        if(!preg_match_all("/<input name='(.*)' type='hidden' value='(.*)'>/", $out, $result, PREG_SET_ORDER)){
            $error_message = 'Ivalid output';
        }

        $ar="";
        foreach($result as $item){
            $key=$item[1];
            $ar[$key]=$item[2];
        }
        if($ar) {
            $data = array(
                'payment' => 'perfectmoney',
                'post_content' => json_encode($ar),
                'datetime' => date('Y-m-d H:i:s')
            );
            $this->db->insert('ipn_process', $data);
            return $ar;
        } else {
            $data = array(
                'payment' => 'perfectmoney',
                'post_content' => $error_message.' '.$out,
                'datetime' => date('Y-m-d H:i:s')
            );
            $this->db->insert('ipn_process', $data);
            return FALSE;
        }
    }




public function check_two_factor($fun_value)
{

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

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

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['codess']  = $get_code;
$this->data['email'] = $result->email;

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

if($fun_value==1)
{
$this->data['action'] = base_url('/withdraw_authverify');
}
else
{
$this->data['action'] = base_url('/transfer_authverify');
}

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



}
}
}

}
else
{
    return true;
}

}

public function withdraw_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);
    $Resultcheck='1';
    if($Resultcheck)
    {

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


    $this->uri = new \CodeIgniter\HTTP\URI();
    $this->uri = service('uri');
    $this->uri = current_url(true);


    $id =  $this->request->uri->getSegment('2');

    $condition = "uusersid = '".$this->session->get('uusersid')."' AND contents!=''";
    $this->data['payment_list'] = $this->common_model->GetResults('uusers_payment',$condition);

    $withdraw_data = $this->common_model->GetSettingall('withdraw');
    $this->data['action'] = base_url().'/user/validatewithdraw';
    foreach ($withdraw_data as $row) {
    $this->data[$row->site_key] = $row->site_value;
    }

    $enable_pin = $this->data['with_use_pin'];

    if($enable_pin=='on') {

    $this->session->set('log_id',$id);

    if($this->session->get('temp_access')==true) {
    $this->session->set('temp_access',false);
    echo view('user/withdraw',$this->data);
    } else {
    $this->data['action'] = base_url().'/withdraw/checkpin';
    echo view('user/transaction_pin',$this->data);
    }

    } else {

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

    }

    }
    else
    {
     $this->session->setFlashData('error_message',"Sorry Invalid Verfication Code");
    return redirect()->to('withdrawfund');
    }
    }


}


public function transfer_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)
    {


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


            $this->uri = new \CodeIgniter\HTTP\URI();
            $this->uri = service('uri');
            $this->uri = current_url(true);

            $id =  $this->request->uri->getSegment('2');

            $condition = "uusersid = '".$this->session->get('uusersid')."' AND contents!=''";
            $this->data['payment_list'] = $this->common_model->GetResults('uusers_payment',$condition);

            $withdraw_data = $this->common_model->GetSettingall('withdraw');
            $this->data['action'] = base_url().'/user/validatetransfer';
            foreach ($withdraw_data as $row) {
            $this->data[$row->site_key] = $row->site_value;
            }

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

    }
    else
    {
    $this->session->setFlashData('error_message',"Sorry Invalid Verfication Code");
    return redirect()->to('transfer');
    }
    }


}

public function name_verify()
{
    $this->session = session();
    $this->db = db_connect();
    $userid = $this->session->get('uusersid');
    $name=trim($this->request->getPost('rec_name'));

    $user_available = $this->db->query("Select * from uusers where username = '".$name."'")->getRow();

    $uname = trim($user_available->username);

    if($user_available){
         /* $confirm = $this->db->table('history')->where('uusersid',$user_available->uusersid)->where('type','activation')->where('status',1)->get()->getRow();
        if($confirm) 
        echo 1;
        else
        echo 3;*/
    echo 1;
    }else{
         echo 2;
    }
}


public function validsecuritypin()
{
   
    $this->session = session();
    $this->db = db_connect();
    $userid = $this->session->get('uusersid');
    

    $pin = $this->request->getPost('sec_pin');
   

    $result = $this->db->query("Select * from uusers where uusersid = '".$userid."'")->getRow();
   

    $hashed_password = $result->trans_password;

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


}