<?php 
namespace App\Controllers\Admin;
use App\Views;
use App\Models\CommonModel;
use App\Libraries\MyEncrypt;
use App\Libraries\PHPMailer;

class Login extends BaseController {

	/**
	 * 
	 * Start 
	 * Create Date: 18 Jun, 2016
	 * This controller to manage admin login.
	 * Created saravana kumar.
	 * @see http://zhyip.com/
	 * Last Updated: 08 July, 2016
	 * End
	 * 
	*/

	public function __construct() {
		$this->common_model = model('CommonModel');
		helper('site_helper');
		// form validation library
		// custom encryption
		// library('MyEncrypt');
		helper('cookie');
	}


public function resetupdate()
	{
		if($this->request->getPost()){

			$myencrypt = new MyEncrypt;
			$myencrypt->encode($userfound->id);

			$uusersid = $myencrypt->decode($this->request->getPost('reset_id'));
			$condition = "id = '".$uusersid."'";
			$userfound = $this->common_model->GetRow('admin',$condition);
			
			if($userfound) {
				$password = crypt(urlencode($this->input->getPost('password')));
				$userdata = array(
					'password' => $password,
					'authcode' => ''
				);
				$this->db->where('id',$userfound->id);
				$update_status = $this->db->table('admin')->update($userdata);

				if($update_status) {
					$session->setFlashData('reset_success_message', lang('language_lang.new_password_success_message'));
					redirect('admin/login');
				} else {
					$session->setFlashData('reset_error_message', lang('language_lang.reset_error_message'));
					redirect('admin/login/reset');
				}
			}

			$this->load->view('admin/activateuser');

		}
	}

	public function reset() {
		$this->session = session();
		$this->db = db_connect();
		if($this->request->getPost()){
			$resetmail = $this->request->getPost('email');
			$validation =  \Config\Services::validation();
            $validation->setRules([
				'email' => ['label' => 'email', 'rules' => 'trim|required|valid_email']
				]);
			
			

			// check form validate
			if ($validation->withRequest($this->request)->run() == TRUE) {
				$condition = "email = '".$resetmail."'";
				$user = $this->common_model->GetRow('admin', $condition);
				
				$slug = md5($user->id . $user->email . time());
				$reset_data =  array(
					'authcode' => $slug
				);
				
				$update_status = $this->db->table('admin')->where('id',$user->id)->update($reset_data);
				
				if($update_status) {
					$link = base_url().'admin/login/activate/'.$slug;
	
				
					$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($mail_data['admin_email'], site_info_lang('site_name',session()->get('langid')));  
			        $mail->AddReplyTo($mail_data['admin_email'],site_info_lang('site_name',session()->get('langid')));
			        $mailid = '18';
			        $mail_subject_data = $this->common_model->getMailTemplate($mailid);
					$message  = str_replace('[FIRSTNAME]', $user->username, $mail_subject_data->message);
					// $message  = str_replace('[PASSWORD]', $user->fullname, $message);
					$message  = str_replace('[URL]', $link, $message);
					$message  = str_replace('#adminemail', $mail_data['admin_email'], $message);
					$message  = str_replace('#sitename', site_info_lang('site_name',session()->get('langid')), $message);
					
			        $mail->Subject    = "Reset password";
			        $mail->msgHTML($message);
			        $mail->AltBody    = "Your Password has been reseted Successfully";
			        
			        $mail->AddAddress($user->email, $user->username);

			        // $mail->AddAttachment("images/phpmailer.gif"); 
			        // $mail->AddAttachment("images/phpmailer_mini.gif"); 

			        if(!$mail->Send()) {
			            $data["message"] = "Error: " . $mail->ErrorInfo;
			        } else {
			            $data["message"] = "Message sent correctly!";
			        }

					$this->session->setFlashData('reset_success_message', "Reset mail sent successfully");
					redirect()->to('admin/login');
				} else {
					$this->session->setFlashData('reset_error_message', $mail->ErrorInfo);
					redirect()->to('admin/login/reset');
				}
			}
			else
			{
				$this->session->setFlashData('reset_error_message', "Reset mail sent successfully");
				redirect()->to('admin/login/reset');

			}
			
		} 
		echo view('admin/resetpassword');
	}

	public function index() {
		// admin login only
		$this->common_model = model("CommonModel");
		$this->db = db_connect();
        $session = \Config\Services::session();
		if(!$session->get('admin_login')) {
			/*if(isset($_COOKIE['remember_token'])) 
			{

				$myencrypt = new MyEncrypt;
				$token_value = $myencrypt->decode($this->input->cookie('remember_token'));
				$this->isCookie($token_value,TRUE);	

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

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



			$this->db = db_connect();
		$login_check=$this->db->query("select * from site_controls where settings_name='login' and site_key='log_captcha_status'")->getRow();
			$login_load = $login_check->site_value;

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



				$username = $this->request->getPost('username');
                $validation =  \Config\Services::validation();
                    	$validation->setRules([
				'username' => ['label' => 'Username', 'rules' => 'trim|required|alpha_numeric|username_check[$username]'],
				'password' => ['label' => 'Password', 'rules' => 'trim|required']]);

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



					$result = $this->common_model->getPassword($this->request->getPost('username'));
					$hashed_password = $result->password;

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

                        $condition="username = '".$username."'";
                        $admin = $this->common_model->GetRow('admin',$condition);
                       
						if($admin->ipVerification=='on' && $admin->ip!=$_SERVER['SERVER_ADDR']){
                          
                            
							//if($admin->ip!=$_SERVER['SERVER_ADDR'])
							//{
                                 
								$emailconfirm = random_string('numeric', 16);
    
								$email_verify = array(
									'confirmcode'  => $emailconfirm
								);
								$this->db = db_connect();
						
								$update_status = $this->db->table('admin')->where('id','1')->update($email_verify);

							    $link = base_url('admin/emailconfirm');

								// $this->load->library('My_PHPMailer');
								$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($mail_data['admin_email'], site_info_lang('site_name',session()->get('langid')));  
						        $mail->AddReplyTo($mail_data['admin_email'],site_info_lang('site_name',session()->get('langid')));
						        $mailid = '25';
						        $mail_subject_data = $this->common_model->getMailTemplate($mailid);
								$message  = str_replace('[FIRSTNAME]', $admin->username, $mail_subject_data->message);
								$message  = str_replace('[CODE]', $emailconfirm, $message);
								$message  = str_replace('[URL]', $link, $message);
								$message  = str_replace('#adminemail', $mail_data['admin_email'], $message);
								$message  = str_replace('#sitename', site_info_lang('site_name',session()->get('langid')), $message);
			                    
						        $mail->Subject    = "Confirmation code";
						        $mail->msgHTML($message);
						        $mail->AltBody    = "Your account has been activated Successfully";
						        
						        $mail->AddAddress($admin->email, $admin->username);

						        if(!$mail->Send()) {
						            $data["message"] = "Error: " . $mail->ErrorInfo;
						        } else {
						            $data["message"] = "Message sent correctly!";
						        }

						        echo view('admin/emailconfirmation');
							//}

						}
						/*else if($admin->mailverification=='on'){

							$condition="id = '1'";
                            $admin = $this->common_model->GetRow('admin',$condition);

                            $emailconfirm = random_string('numeric', 16);
							$email_verify = array(
								'confirmcode'  => $emailconfirm
							);
							$this->db->where('id','1');
							$update_status = $this->db->update('admin',$email_verify);

						    $link = base_url().'admin/emailconfirm';

							$this->load->library('My_PHPMailer');
							$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($mail_data['admin_email'], site_info_lang('site_name',session()->get('langid')));  
					        $mail->AddReplyTo($mail_data['admin_email'],site_info_lang('site_name',session()->get('langid')));
					        $mailid = '26';
					        $mail_subject_data = $this->common_model->getMailTemplate($mailid);
							$message  = str_replace('[FIRSTNAME]', $admin->username, $mail_subject_data->message);
							$message  = str_replace('[CODE]', $emailconfirm, $message);
							$message  = str_replace('[URL]', $link, $message);
							$message  = str_replace('#sitename', site_info_lang('site_name',session()->get('langid')), $message);
		                     
					        $mail->Subject    = "Email Verification code";
					        $mail->msgHTML($message);
					        $mail->AltBody    = "Your account has been activated Successfully";
					        
					        $mail->AddAddress($admin->email, $admin->username);

					        if(!$mail->Send()) {
					            $data["message"] = "Error: " . $mail->ErrorInfo;
					        } else {
					            $data["message"] = "Message sent correctly!";
					        }

					        redirect()->to('admin/emailconfirm');

						}*/
						// else if($usersettings['admin_enable_twofactor_auth'] == 'on')
						// {
						// 	// $array = array(
						// 	// 	"ad_id" => $result->id
						// 	// );
      //  //                      $this->session->set($array);
						// 	// redirect()->to(site_url('admin/verify'));	
						// }
						else
						{ 
                
						    $array = array(
								"logged_in" => TRUE,
								"userid" => $result->id,
								"admin_login" => TRUE,
								"user_type" => $result->type,
								"permission" => $result->permission
							);

							$lastaccess = array(
								"uusers_id" => $result->id, 
				                "uusers_ip" => $_SERVER['REMOTE_ADDR'],
				                "lastaccess"   => date('Y-m-d H:i:s'),
				                "user_type" => ($result->id == '1') ? 'admin' : 'subadmin'
							);
							$insert_status = $this->db->table('uusers_online')->insert($lastaccess);
	                        

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

							
								helper('cookie');

								// $this->session->set_userdata('remember_me', true);
								// set_cookie("remember_me",$result->id.''.$result->username)
								$myencrypt = new MyEncrypt;
								$remember_token_value = $this->request->getPost('password');
								$remember_token_value1 = $result->username;
								$value = $myencrypt->encode($remember_token_value."|".$remember_token_value1);

								// $cookie = array(
								//     'name'   => 'remember_me',
								//     'value'  => $remember_token_value."|".$remember_token_value1,
								//     'expire' => '3600',  // one hour
								//     'domain' => base_url(),
								//     'path'   => base_url().'admin'
								// );
								

								set_cookie('remember_token', $value, 3600); //expires in one hour
								// set_cookie('remember_me', $remember_token_value, 3600); //expires in one hour

							}
							else
							{
								set_cookie('remember_token', '', 3600);

							}



							session()->set($array);

                            
							// $this->session->set_flashdata('success_message', 'Login Successfully');
                           
							return redirect()->to('admin');	
						
					
						}

					} else {
						
					$session->setFlashData('error_message', 'Invalid Username or Password');
						return redirect()->to('admin');
					}

				} 
				
			}

			echo view('admin/login');

		} else {
			return redirect()->to('admin_dashboard');
		}
	}

	public function validcode()
	{

		$condition = "confirmcode = '".$this->request->getPost('confirmcode')."'";
    	$confirm_found = $this->common_model->GetRow('admin',$condition);

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

	public function emailconfirm(){
	
		echo view('admin/emailconfirmation');
	}
	public function verify(){
	
		echo view('admin/verify');
	}

	public function emailconfirmupdate() {

        $condition = "confirmcode = '".$this->request->getPost('confirmcode')."'";

        $confirm_found = $this->common_model->GetRow('admin',$condition);
        if($confirm_found)
        {

		    $confirm_data = array(
				"confirmcode"	=>	"",
				"ip" => $_SERVER['REMOTE_ADDR']
			);
			$this->db->where('id','1');
			$query_status = $this->db->update('admin',$confirm_data);
                
            $lastaccess = array(
				"uusers_id" => $confirm_found->id, 
                "uusers_ip" => $_SERVER['REMOTE_ADDR'],
                "lastaccess"   => date('Y-m-d H:i:s'),
                "user_type" => ($result->id == '1') ? 'admin' : 'subadmin'
			);
			$insert_status = $this->db->insert('uusers_online', $lastaccess);

			$array = array(
				"logged_in" => TRUE,
				"userid" => $confirm_found->id,
				"admin_login" => TRUE
			);
			$this->session->set_userdata($array);
			redirect()->to('admin');
	    }
		
	}

	public function twofactor()
	{
		if($this->request->getPost()) 
		{
			$authenticator = new PHPGangsta_GoogleAuthenticator();
	        $otp = $this->request->getPost('confirmcode');
			$condition ="id = '".session()->get('ad_id')."'";
			$admin_id=session()->get('ad_id');
	        $hashedpass = $this->common_model->GetRow('admin',$condition);
			$secret = $hashedpass->secret_key;
			if($secret=='' || $secret=='0')
			{
				$secret=$this->request->getPost('secret');
			}
			$tolerance = 2;
			$checkResult = $authenticator->verifyCode($secret,$otp,$tolerance);

			if($checkResult)
			{
				$confirm_data = array(
				"confirmcode"	=>	"",
				"ip" => $_SERVER['REMOTE_ADDR'],
				"secret_key" => $secret
				);
				$this->db->where('id',$admin_id);
				$query_status = $this->db->update('admin',$confirm_data);
	                
	            $lastaccess = array(
					"uusers_id" => $admin_id, 
	                "uusers_ip" => $_SERVER['REMOTE_ADDR'],
	                "lastaccess"   => date('Y-m-d H:i:s'),
	                "user_type" => ($result->id == '1') ? 'admin' : 'subadmin'
				);
				$insert_status = $this->db->insert('uusers_online', $lastaccess);

				$array = array(
					"logged_in" => TRUE,
					"userid" => $admin_id,
					"admin_login" => TRUE
				);
				$this->session->set_userdata($array);
				redirect()->to('admin');
				
			}
			else
			{
				$this->session->set_flashdata('error_message', 'Invalid OTP Code');
			}

		}
		
		redirect()->to('admin/verify');
		
	}

	public function logout() {
		session()->remove('logged_in');
		session()->remove('userid');
		session()->remove('admin_login');
		// $this->session->sess_destroy();
		return redirect()->to('admin/login');
	}

	public function username_check($str)
	{
		$this->db = db_connect();
		$this->db->select('username');
		$this->db->table('admin');
		$this->db->where('username',$str);

		$query = $this->db->get();
		if ($query->getNumRows()>0)
			return true;
		else
		{
			$validator->set_message('username_check', '<label class="validation-error-label">This invalid details of %s</label>');
			return false;
		}
	}

	public function activate() {
		
		$hash = $this->uri->segment(4);
		$condition = "authcode = '".$hash."'";
		$userfound = $this->common_model->GetRow('admin',$condition);

		if($userfound) {

			$myencrypt = new MyEncrypt;
			$this->data['reset_id'] = $myencrypt->encode($userfound->id);
			$this->data['fullname'] = $userfound->name;
			$this->data['action'] = base_url().'admin/login/resetupdate';
			echo view('admin/activateuser',$this->data);
		} else {
			redirect()->to('admin/login');
		}
	}


	public function checkmail($str)
	{

		$this->db->select('*');
		$this->db->from('admin');
		$this->db->where('email',$str);	
		$query = $this->db->get();
		
		if ($query->num_rows()>0)
		{
			return true;
		}
		else
		{
			return false;
		}
		
	}
}