<?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->model('m_masters');
		$this->load->library('GoogleAuthenticator');
		date_default_timezone_set("Asia/Jakarta");
	}
	public function index()
	{
// 		$data['title'] = "Welcome to Telemarketing!";
// 		$this->load->view('v_login',$data);
		
		$data['title'] = "Welcome to WhiteDread!";
		if (empty($this->session->userdata('username')))
        { 
          $this->load->view('v_login',$data);
        }
        else
        {
            redirect('c_modules');
        }
		
	}

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

		$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
		{		
			    $querystring = "select * from users where user = '".$viewing['txtemail'] . "' and password = md5('".$viewing['txtpassword'] . "')";
				$viewing['listusersarray'] = $this->m_masters->querying($querystring);
				$viewing['listusers'] = $viewing['listusersarray']->result();
				$viewing['listuserscount'] = $viewing['listusersarray']->num_rows();

				if($viewing['listuserscount'] > 0)
				{
				    
					$this->session->set_userdata('tempusername',$viewing['listusers'][0]->user);
					$this->session->set_userdata('tempbrandgroup',$viewing['listusers'][0]->brandgroup);
					$this->session->set_userdata('tempprivilege',$viewing['listusers'][0]->privilege);
				// 	echo $this->session->userdata('temrpusername');
					$this->load->view('v_googleauth');


				}
				else
				{
					$this->session->set_flashdata('message',"Invalid Username Or Password");
					redirect('c_login');
				}
			
		} 		
	}

	public function validategoogle()
	{
		$code = $this->input->post('googlecode');
		$querystring = "select gsecret from gsecret";
		$secret = $this->m_masters->querying($querystring)->result()[0]->gsecret;
		// echo $querystring;
		$g = new \Sonata\GoogleAuthenticator\GoogleAuthenticator();
		
		if ($g->checkCode($secret, $code)) {

				$this->session->set_userdata('username',$this->session->userdata('tempusername'));
				$this->session->set_userdata('brandgroup',$this->session->userdata('tempbrandgroup'));
				$this->session->set_userdata('privilege',$this->session->userdata('tempprivilege'));
				redirect('c_modules');	
			
		}
		else
		{
			$this->session->set_flashdata('message',"Google Authenticator Code Incorrect!");
			redirect('c_login');
		}
	}	
}

	

