<?php if (!defined('BASEPATH')) exit('No direct script access allowed');



class User_login extends MY_Controller {



    Public function __construct(){

        parent::__construct();

        $this->load->model("user_login_model","login");
        $this->load->helper('front_helper');

    }

    public function loginPage()
    {
    	$this->loadHtml('login','User Login Page');
    }

    public function registrationPage()
    {
    	$this->loadHtml('registration','User Registration Page');
    }


    function is_logged_in()
	{
		//print_r($this->session->all_userdata());die;

		$is_user_logged_in = $this->session->userdata('is_user_logged_in');
		if(!isset($is_user_logged_in) || $is_user_logged_in != true)
		{

		}else{
			redirect(base_url());
		}

	}

	public function doLogin()
	{
		$error=1;
		$message=$location='';
		if(!isset($_POST['login']))
		{
			$_POST['login'] = 'login';
		}
		if((isset($_POST['email']) && isset($_POST['password'])) || isset($_POST['login']))
		{
			$data = $this->login->loginValidate($_POST);
			if($data)
			{
				if(((strtolower($data[0]['email'])!=strtolower($_POST['email'])) || ($data[0]['mobile_no']!=strtolower($_POST['email']))) && ($data[0]['password']!=md5($_POST['password'])))
				{
					$this->session->set_flashdata("emessage",$this->lang->line("error_user_login"));
					if(isset($_POST['redirect']) && $_POST['redirect']==1){
						$location = base_url("user-login?redirect=1");
					}else{
						$location = base_url("user-login");
					}
				}else{
					if(isset($_POST['redirect']) && $_POST['redirect']==1){
						$location = $this->loginRedirect($data[0],1);
					}else{
						$location = $this->loginRedirect($data[0]);
					}
				}
			}else{
				$this->session->set_flashdata("emessage",$this->lang->line("error_user_login"));
				if(isset($_POST['redirect']) && $_POST['redirect']==1){
					$location = base_url("user-login?redirect=1");
				}else{
					$location = base_url("user-login");
				}
			}
		}else{
			$this->session->set_flashdata("emessage",$this->lang->line("error_user_login"));
			if(isset($_POST['redirect']) && $_POST['redirect']==1){
				$location = base_url("user-login?redirect=1");
			}else{
				$location = base_url("user-login");
			}
		}
		redirect($location);
	}

	public function loginRedirect($data=array(),$r='')
	{
		$sdata = array(
			'email' => $data['email'],
			'profileid'	=>	$data['profileid'],
			'is_user_logged_in' => true,
			'user_login_type' => "register_user"
		);

		$this->session->set_userdata($sdata);
		if($r==1){
			$redirect = base_url('checkout');
		}else{
			if($this->session->userdata("current")){
				$redirect = base_url($this->session->userdata("current"));
				$this->session->unset_userdata("current");
			}else{
				$redirect = base_url('user-profile');
			}
		}
		return $redirect;
	}

	public function sociallogin123()
    {    	
	  	$data['name'] = strtolower($this->input->post('fname')).' '.strtolower($this->input->post('lname'));
	  	$data['email'] = $this->input->post('email');
	  	//print_r($data['email']); die;
	  	$result = $this->common->getsData('user',array('email'=>$data['email']));
	  	//echo "<pre>"; print_r($result); die;
	  	if(empty($result)){
	  		$data['profileid'] = strtotime(date("Y-m-d H:i:s"));
			$data['reg_date'] = date("Y-m-d H:i:s");
			$data['user_type'] = 'register_user';
			$data['verify'] = 1;
	  		$this->common->insertData('user',$data);
	  		$uid = $this->db->insert_id();
			$own_referal = strtoupper(substr($data['name'], 0,3)).$uid.substr(strtoupper(date('M')),0,2).rand(11,99).strtoupper($this->getRandomString(4));
			$this->common->updateData('user',array('own_referal'=>$own_referal),array('id'=>$uid));
			$edata['link'] = base_url('user-verify-email?info='.base64_encode($data['email']));
			$email_message = $this->load->view('email_temp/account',$edata,true);
			$this->email->from(from_email,author);
			$this->email->to($data['email']);
			$this->email->subject('Customer account confirmation');
			$this->email->message($email_message);
			// $this->email->send();
	  	}else{
	  		$data['profileid'] = $result['profileid'];
	  	}

		$location = $this->loginRedirect($data);		

		redirect($location);
    }

    function getRandomString($digits) { 
	    $total_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
	    $randomString = ''; 
	        for ($i = 0; $i < $digits; $i++) { 
	            $index = rand(0, strlen($total_characters) - 1); 
	            $randomString .= $total_characters[$index]; 
	        }
	    return $randomString; 
	}

	public function sendTestMail()
	{
		$e['orderid'] = '12345fd';
		$e['subject'] = "Your Order: 12345 has been delivered df.";
		$e['title'] = "Your Order is ffdfd!";
		$e['content'] = "fdffd  fThank you for your being our valued customer. Find other products you may like? View them here.";
		$e['btntext'] = "View order";
		$e['btnlink'] = base_url('all-order');
		$email_message = $this->load->view('email_temp/order-status',$e,true);
		$subject = 'test';
		echo $email_message;
		$this->common->sendMailBySendGrid('vinod.starwebindia@gmail.com','',from_email,author,$subject,$email_message);
	}


	public function registerUser()
	{
		// if(isset($_POST['g-recaptcha-response']) && $_POST['g-recaptcha-response']!=''){
			if(isset($_POST)){
				$emailErr = '';
				// if($_POST['name']==''){
				// 	$emailErr .= "Please Enter Name <br>";
				// }
				if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
				  $emailErr .= "Please Enter Valid Email Address <br>"; 
				}
				// if($_POST['mobile_no']=='' || !is_numeric($_POST['mobile_no']) || strlen($_POST['mobile_no'])!=8) {
				//   $emailErr .= "Please Enter Valid Mobile No. <br>"; 
				// }
				// if($_POST['dob']==''){
				// 	$emailErr .= "Please Enter Date of Birth <br>";
				// }
				// if($_POST['country']==''){
				// 	$emailErr .= "Please Select Country <br>";
				// }
				// if($_POST['address']==''){
				// 	$emailErr .= "Please Enter Address <br>";
				// }
				if(!isset($_POST['terms'])){
					$emailErr .= "Please Accept Terms & Conditions <br>";
				}
				if($_POST['password']==''){
					$emailErr .= "Please Enter Password <br>";
				}
				if($_POST['password']!=$_POST['confirm_password']){
					$emailErr .= "Password & Confirm Password is not match <br>";
				}

				if($emailErr!=''){
					$this->session->set_flashdata("emessage",$emailErr);
					redirect($_SERVER['HTTP_REFERER']);
				}else{
					$message=$location='';
					$_POST['plain_password'] = $_POST['password'];
					$_POST['password'] = md5($_POST['password']);
					$_POST['profileid'] = strtotime(date("Y-m-d H:i:s"));
					$_POST['reg_date'] = date("Y-m-d H:i:s");
					$_POST['user_type'] = 'register_user';
					$_POST['verify'] = 1;
					/*if(isset($_POST['used_referal']) && $_POST['used_referal']!='')
					{
						$yes = $this->common->getsData("user",array("own_referal"=>$_POST['used_referal'],'user_type'=>'register_user'));
						if($yes){

						}else{
							$this->session->set_flashdata("emessage",'Referal code not match');
							redirect($_SERVER['HTTP_REFERER']);
						}
					}*/
					if($this->common->getData("user",array("email"=>$_POST['email'],'user_type'=>'register_user')))
					{
						$this->session->set_flashdata("emessage",$this->lang->line("email_exist"));
						redirect($_SERVER['HTTP_REFERER']);
					}else if($this->common->getData("user",array("email"=>$_POST['email'],'user_type'=>'guest_user'))){
						$ud = $this->common->getsData("user",array("email"=>$_POST['email'],'user_type'=>'guest_user'));
						$_POST['profileid'] = $ud['profileid'];
						$userdata = $this->common->getField('user',$_POST);
						$res = $this->common->updateData('user',$userdata,array('email'=>$_POST['email']));
						if($res){
							if(isset($_POST['redirect']) && $_POST['redirect']==1){
								$location = $this->loginRedirect($_POST,1);
				            }else{
								$location = $this->loginRedirect($_POST);
				            }
						}else{
							redirect($_SERVER['HTTP_REFERER']);
						}
					}else{
						$res = $this->login->registerUser($_POST);
						if($res){
							/*$uid = $this->db->insert_id();
							$own_referal = strtoupper(substr($_POST['name'], 0,3)).$uid.substr(strtoupper(date('M')),0,2).rand(11,99).strtoupper($this->getRandomString(4));
							$this->common->updateData('user',array('own_referal'=>$own_referal),array('id'=>$uid));*/
							/*if(isset($_POST['used_referal']) && $_POST['used_referal']!=''){
								$query = ('UPDATE  user SET `total_point` =  total_point+200, `remain_point` =  remain_point+200 WHERE `own_referal` ="'.$_POST['used_referal'].'"');
		                        $this->db->query($query);
							}
							$edata['email'] = $_POST['email'];
							$edata['pass'] = $_POST['plain_password'];
							$edata['link'] = base_url('user-verify-email?info='.base64_encode($_POST['email']));
							$email_message = $this->load->view('email_temp/account',$edata,true);
							$subject = 'Welcome to '.author.'!';
							$this->common->sendMailBySendGrid($_POST['email'],'',from_email,author,$subject,$email_message); */

							/*if(isset($_POST['newsletter']) && $_POST['newsletter']==1){
								$yes = $this->common->getsData('newsletter',array('email'=>$_POST['email']));
					            if($yes){
					                
					            }else{
					                $ip = $this->input->ip_address();
					                $res = $this->common->insertData('newsletter',array('email'=>$_POST['email'],'name'=>$_POST['name'],'ip_address'=>$ip,'date'=>date('Y-m-d H:i:s')));
					            }
					        }*/
				            if(isset($_POST['redirect']) && $_POST['redirect']==1){
								$location = $this->loginRedirect($_POST,1);
				            }else{
								$location = $this->loginRedirect($_POST);
				            }
						}else{
							redirect($_SERVER['HTTP_REFERER']);
						}
					}
					redirect($location);
				}
			}else{
				$this->session->set_flashdata("emessage","All fields are required.");
				redirect($_SERVER['HTTP_REFERER']);
			}
		// }else{
		// 	$this->session->set_flashdata("emessage","Captcha is required.");
		// 	redirect($_SERVER['HTTP_REFERER']);
		// }		

	}

	public function forgetPasswordPage()
	{
		$this->loadHtml("forget_password","Forget Password");
	}

	public function forgetPassword()
	{
		$email = $_POST['email'];
		if(isset($email))
		{
			if($data = $this->common->getsData('user',array('email'=>$email,"user_type"=>"register_user")))
			{
				$list= array();
				$characters = '0123456789';
				$length = 4;
			    $charactersLength = strlen($characters);
			    $randomString = '';
			    for ($i = 0; $i < $length; $i++) {
			        $randomString .= $characters[rand(0, $charactersLength - 1)];
			    }
			    $this->common->updateData('user',array('password'=>md5($randomString),'plain_password'=>$randomString),array('profileid'=>$data['profileid']));
			    
			    // $edata['pass'] = $randomString;
			    // $email_message = $this->load->view('email_temp/forgot-pass',$edata,true);
			    $email_message = 'Your password has been reset<br>Your new auto-generated password:'.$randomString.'<br><a href="'.base_url('user-login').'" target="_blank">Login Here</a>';
			    //echo $email_message."<br>";
			    //echo $email."<br>";
			    $subject = "Password Reset";
			    $this->common->sendMailBySendGrid($email,'',from_email,author,$subject,$email_message);
				// $this->email->from(from_email,author);
				// $this->email->to($email);
				// $this->email->subject('Forgot Password');
				// $this->email->message($email_message);
				// $this->email->send();

				$this->session->set_flashdata('message',"Password Sent Your Email. Please Check Your Email.");
				redirect(base_url("user-login"));
			}else{
				$this->session->set_flashdata('emessage','Something Went Wrong. Please Try Again.');
				redirect(base_url("forgot-password"));
			}
		}
	}

	public function verifyAccountPage()
	{
		if(isset($_GET['info']) && $_GET['info']!=''){
			$email = base64_decode($_GET['info']);
			$res = $this->common->updateData('user',array('verify'=>1),array('email'=>$email));
			if($res){
				$this->session->set_flashdata('message',"Success! Your Account has been verified");
				redirect(base_url("user-profile"));
			}else{
				echo "Link Expired";
			}
		}else{
			echo "Link Expired";
		}
	}

}