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

class c_login extends CI_Controller {
	function __construct(){
		parent::__construct();		
		$this->load->model('m_masters',"listusers");
		$this->load->library('GoogleAuthenticator');
		date_default_timezone_set("Asia/Jakarta");
	}
	public function index()
	{
		$data['title'] = "Welcome to Telemarketing!";
		$this->load->view('v_login',$data);
	}

	public function validatelogin()
	{
		$viewing['title'] = 'Login Page';
		$viewing['txtemail']=$this->input->post('checkemail');
		$viewing['txtpassword']=$this->input->post('checkpassword');
		$code = $this->input->post('pass-code');

		$this->form_validation->set_rules('checkemail','Email','required');
		$this->form_validation->set_rules('checkpassword','Password','required|max_length[20]');	
		
		// $this->load->view('v_testing',$viewing);
		if($this->form_validation->run()==FALSE)
		{
			$this->load->view('v_login',$viewing);
		}
		else
		{		
			$secret = 'MTQ2UIGO75XRUKJJ';
			$g = new \Sonata\GoogleAuthenticator\GoogleAuthenticator();
			// echo 'Current Code is: ';
			// echo $g->getCode($secret);
			// echo "\n";
			// echo "Check if $code is valid: ";
			if ($g->checkCode($secret, $code)) {
			    // echo "YES \n";

			    $viewing['querystring'] = "select * from operators where operator = '".$viewing['txtemail'] . "' and password = password('".$viewing['txtpassword'] . "')";
				$viewing['listusersarray'] = $this->listusers->getusers($viewing['querystring']);
				$viewing['listusers'] = $viewing['listusersarray']->result();
				$viewing['listuserscount'] = $viewing['listusersarray']->num_rows();

				if($viewing['listuserscount'] > 0)
				{
					

					$querystring = "select loggedin from operators where operator = '".$viewing['txtemail'] ."'";
					
					$userlogin = $this->listusers->querying($querystring)->result();
					if($userlogin[0]->loggedin == '0')
					{	
						$this->session->set_userdata('tempusername',$viewing['listusers'][0]->Operator);
						$this->session->set_userdata('tempprivileges',$viewing['listusers'][0]->Privilege);
						$this->session->set_userdata('tempprivilege',$viewing['listusers'][0]->OperatorGroup);
						redirect('c_limbo/changepasswordawal');
					}
					else
					{
						$this->session->set_userdata('username',$viewing['listusers'][0]->Operator);
						$this->session->set_userdata('privileges',$viewing['listusers'][0]->Privilege);
						$this->session->set_userdata('privilege',$viewing['listusers'][0]->OperatorGroup);
						redirect('c_modules');	
					}
				}
				else
				{
					$this->session->set_flashdata('message',"Invalid Username Or Password");
					redirect('c_login');
				}
			} 
			else {
			    // echo "NO \n";
				$this->session->set_flashdata('message',"Google Authenticator Code Incorrect!");
					redirect('c_login');
			}
		}	
	}

}