<?php


namespace App\Controllers\User;
use App\Views;
use App\Models\CommonModel;
use App\Helpers\site_helper;
use App\Libraries\PHPMailer;  
use App\Libraries\My_PHPMailer;
use PHPMailer\PHPMailer\Exception;
use App\Libraries\MyEncrypt;
use App\Libraries\mathcaptcha;


class Register extends BaseController {

	/**
	 * 
	 * Start 
	 * Create Date: 1 Augest, 2016
	 * This controller to manage register page.
	 * Created karthiga.
	 * @see http://zhyip.com/user/register/
	 * Last Updated: 23 Augest, 2016
	 * End
	 * 
	*/

	public function __construct() 
	{

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

		$this->common_model = model('CommonModel');
		helper('site_helper');
		$status = site_info('site_status');
		if($status!='on')
		{
			redirect('offline');
		
		}  

	}
	

	public function index() 
	{

		
		/* if check IP is blocked */
		$blocked_list = Checkip();
		if($blocked_list) 
		{
			redirect('');
		}
	     $this->session = \Config\Services::session();
	     $this->db = db_connect();

		if($this->session->get('reff_name'))
		{
			$this->data['reff_name'] = $this->session->get('reff_name');
			$this->data['sponsor_details'] = $this->db->query("SELECT * FROM uusers where username='".$this->session->get('reff_name')."'")->getRow();
		}
		else
		{
			$this->data['sponsor_details']="";
		}
        


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

	}

	public function reg()
	{
		
			
		//$referral1=$this->db->query("SELECT * FROM uusers WHERE username='".$referral."'");
		//$res=$referral1->row();
		//$referral_id=$res->uusersid;
		//$qry=$this->db->query("SELECT * FROM register ORDER BY id DESC LIMIT 1");
		//$res=$qry->row();
		//$email=$res->email;
		//print($email);
		//exit();
		/*
		if($this->request->getPost()) 
		{
			$email=$this->request->getPost('email');
			$referral_id=$this->request->getPost('referral_id');
			$password=crypt(urlencode($this->request->getPost('password')),'');
			//$cpassword=$this->request->getPost('cpassword');
			$data= array(
				"password" => $password,
				"email" => $email,
				"referral_id"=>$referral_id
				);
			$query_status = $this->db->insert('uusers',$data);
			//echo "successfull";

		}*/
		
		echo view('user/reg');
	}
	public function reg1()
	{
	
       $session = \Config\Services::session();
       helper('site_helper');


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

        $this->session = session();		
     	$password=crypt(urlencode($this->request->getPost('password')),'');

     	$fullname = $this->request->getPost('first_name')." ".$this->request->getPost('last_name');
			//$cpassword=$this->request->getPost('cpassword');
			$data= array(
				"password" => $password,
				"fullname" => $fullname,
				"email" => $this->session->get('email'),
				"status" =>'1',
				"createdate" =>date('Y-m-d'),
				"referral_id" => $this->session->get('referral'),
				"invitation_code"=>$this->session->get('invitation_code')
				);
			
			$this->db = db_connect();
			$query_status = $this->db->table('uusers')->insert($data);
            $lastuserid = $this->db->insertId();

			$security_data = array(
			"uusersid"	=>	$lastuserid,
			"changeip"	=>	'disabled',
			"change_browser"	=>	 'enabled',
			);
			$query_status = $this->db->table('uusers_security')->insert($security_data);

			$referral=$this->session->get('referral');
			if($query_status)
			{

	     $query=$this->db->query("SELECT * FROM uusers WHERE referral_id='".$referral."'");
		$user_count=$query->getNumRows();

			}

			$useremail=$this->session->get('email');

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

		    $uusers_id=$row->uusersid;

		    $referral_id=$this->session->get('referral');
		    /*$spillover_id=$this->db->query("SELECT * FROM uusers WHERE uusersid='".$spill_id."'");
		    $row=$spillover_id->getRow();
		    $spill_over_id=$row->referral_id;*/
			$matrix_data= array(
			"uusersid"=>$uusers_id,
			"referral_id"=>$referral_id,
			"spillover_id"=>$referral_id,
			"user_count"=>'0',
			"cr_date" => date('Y-m-d H:i:s')
			
			 );	

		$query_status = $this->db->table('uusers_matrix')->insert($matrix_data);

			if($query_status)
			{
				$user_count=$user_count;

			$data=array(
				"user_count"=>$user_count
			);

	   $update_status = $this->db->table('uusers_matrix')->where('uusersid',$referral_id)->update($data);
			
			
			if($query_status)
			{	
				$subject = 'Account Activated Successfully';
				$mailid = '2';
				$link =  base_url().'/login';
				$mail_subject_data = $this->common_model->getMailTemplate($mailid);
				$message  = str_replace('[EMAIL]', $this->session->get('email'), $mail_subject_data->message);
				$message  = str_replace('[FULLNAME]', $fullname, $message);
				$message  = str_replace('[URL]', $link, $message);
				$message  = str_replace('[PASSWORD]', $this->request->getPost('password'), $message);
				$message  = str_replace('#sitename', site_info_lang('site_name',$this->session->get('langid')), $message);
				$mail_status = $this->sendmail($useremail,$message,$subject,$mail_subject_data->from_mail);
          }
			
	        //$session->unset('otp');
			//$this->session->destroy();

			  $this->session = session();	

        
				$session->setFlashData('success_message', 'Sign up Completed');
				return redirect()->to('user/login');	
					
				} 
			
				else 
				{
					$session->setFlashData('error_message', 'Failed to Signup');

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

	}

	public function invitation_code()
	{

		$cde='0123456789abcdeghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

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

	    return $invite;

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

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

			$this->db = db_connect();

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

		    $referal_id=$row->uusersid;
			//$id=$res->uusersid;
			$invite=$this->invitation_code();

			$repeat_invite=$this->db->query("SELECT * FROM uusers WHERE invitation_code='".$invite."'");

			$numrows=$repeat_invite->getNumRows();

			if($numrows>0)
			{
				$invite=$this->invitation_code();
			}
		  

             $this->session->set("invitation_code" , $invite);

		     //$session->set($newdata);
			redirect('user/register/reg',$this->data);
			
	}

	public function verifyregcode()
	{
       
		
		$email = $this->request->getPost('email');
        $referral=$this->request->getPost('referral'); 
        $this->db = db_connect();

      
       $referral1=$this->db->query("SELECT * FROM uusers WHERE invitation_code='".$referral."'");
	   $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 = "Email verification";

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

        $this->session->set('referral',$referal_id);
        $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;
		}

       if($email)
       {
			$sub = 'Verify E-Mail Address';
			$mailid = '1';
			$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(
        		"referral" => $referral,
         		"email" => $email,
         		"otp" => $otp
         	);

           $this->db = db_connect();

         $query_status = $this->db->table('register')->insert($data);
         $json['message'] = "OTP send to your Email.";
         }

     }

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

        echo json_encode($json['message']);
          
        
	}
	
	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 validreferral() {

		$getPost_refname = $this->request->getPost('referralname');
		if($getPost_refname){
            $condition = "invitation_code ='" . $getPost_refname . "'";
			$refname = $this->common_model->GetRow('uusers', $condition);
			if($refname){
                $json['valid'] = true;
			}
			else {
				$json['valid'] = false;
			}
		}
		else{
			$json['valid'] = false;
		}
		echo json_encode($json);
	}

	public function changecountry(){
		
		$iso2 = $this->request->getPost('id');

		$condition = "iso_2 = '".$iso2."'";
		$countries = $this->common_model->GetRow('country',$condition);

		if($countries!='')
		{
			echo $countries->CountryCode;
		}
		else
		{
			echo 0;
		}

	}

	public function validuser()
	{
		$getPost_usrname = $this->request->getPost('username');
		if($getPost_usrname){
            $condition = "username ='" . $getPost_usrname . "'";
			$uname = $this->common_model->GetRow('uusers', $condition);
			if($uname){
                $json['valid'] = false;
			}
			else {
				$json['valid'] = true;
			}
		}
		else{
			$json['valid'] = true;
		}
		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'] = false;
			}
			else {
				$json['valid'] = true;
			}
		}
		else{
			$json['valid'] = true;
		}
		echo json_encode($json);
	}


	public function captcha_check($str)
	{
		$this->load->library('recaptcha');
		$response = $this->recaptcha->verifyResponse($str);
		if (isset($response['success']) and $response['success'] === true) {
			return true;  
		}
		else
		{	
		$this->form_validation->set_message('captcha_check', ucwords($this->lang->line('cap_err')));
			return false;
		}

	}
	

	// public function referral() {

	// 	$referral = $this->uri->segment(2);

	// 	if($referral)
	// 	{
	// 		$condition = "username ='" . $referral . "'";
	// 		$sponser_user = $this->common_model->GetRow('uusers', $condition);
	// 		if($sponser_user){
	// 			$this->session->set_userdata('reff_name',$sponser_user->username);
	// 			redirect('user');
	// 		}
	// 		else {
				
	// 			redirect();
	// 		}
	// 	} else {
	// 		$this->session->unset_userdata('reff_name');
	// 	}
		
	// }

		public function referral() {

        $uri = service('uri');
		  $this->uri = service('uri');
         $this->uri = current_url(true);
       
        $this->session = \Config\Services::session();
        $referral =  $this->request->uri->getSegment('2');

		if($referral)
		{
			$condition = "username ='" . $referral . "'";
			$sponser_user = $this->common_model->GetRow('uusers', $condition);
			if($sponser_user){
				$this->session->set('reff_name',$sponser_user->username);

				return redirect()->to('register');
			}
			else {
				
				return redirect()->to('/');
			}
		} else {
			$this->session->unsetGet('reff_name');
		}
		
	}

	public function refersh(){

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

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


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

	    $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 true;
        } else {
            return true;
        }
	}

	function check_math_captcha() {
		$str = $this->request->getPost('math_captcha');
	    
	    if( $str == $this->session->userdata('mathcaptcha_answer'))
	    {
	       $json['valid'] = true;
	    }
	    else
	    {
			$json['valid'] = false;
		}
		echo json_encode($json);
	}

	public function getfullname(){

		$getPost_sponsor = $this->request->getPost('sponsor');
		if($getPost_sponsor){
            $condition = "username ='" . $getPost_sponsor . "'";
			$uemail = $this->common_model->GetRow('uusers', $condition);
			if($uemail){
                $json['fullname'] = $uemail->fullname;
			}
			else {
				$json['valid'] = false;
			}
		}
		else{
			$json['valid'] = true;
		}
		echo json_encode($json);
	}

	function test() {
		$this->load->view('user/demo');
		
	}
	
	
}