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

class Login extends CI_Controller {
	
	function __construct() {
		parent::__construct();
		$this->load->model('login_model');
		$this->load->library('authlib');
		
	}
	
	public function index()	{
		//$this->session->sess_destroy();	
		$data['error'] = "";
		$username = '';
		//cek session
		$username = $this->session->userdata("username");		
		if ($username != "") {
			//cek timeout
			$cek = $this->authlib->cek_timeout($username);
			if ($cek == 1) {
				//redirect home
				redirect('home', 'refresh');
			} else {
				//get error timeout
				$data['error'] = '
					<div class="alert alert-danger fade in">
						<button class="close" data-dismiss="alert">x</button>
						User '.$username.' Time Out Please Re-Login
					</div>';		
			}
		}
		
		$this->load->view('login_views',$data);
	}
	
	//validate user login
	public function validate_login() {
		
		$username = $this->input->post('username');
		$password = $this->input->post('password');		
		$validate = $this->login_model->userAuthen($username,md5($password));	
		
		if ($validate != 1) {
			
			$data['error'] = '
				<div class="alert alert-danger fade in">
					<button class="close" data-dismiss="alert">x</button>
					Not Valid
				</div>				
			';
			$this->load->view('login_views',$data);
		} else {
			
			//create session
			$session = $this->login_model->create_sess($username); 
			
			if ($session == 1) {
				//get first module
				redirect('home#main_page', 'refresh');
			} else {
				echo 'Failed to create session'; die();
			}
		}
		
		
		
	}
	
	function logout() {
		
		$username = $this->session->userdata("username");
		if(!empty($username)) {
			//update table session
			$update_sess = $this->login_model->update_session($username);
			if ($update_sess == true) {
				//redirect login
				redirect('login', 'refresh');
			}
		}
	}
	
	//validate cek user exist
	public function cek_user() {
				
		$username = $this->input->get('username');
		$cek = $this->login_model->cek_user_valid($username);
		
		if ($cek > 0) {
			$json = true;
		} else {
			$json = false;
		}		
		echo json_encode($json);
		
	}
}
