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

class Auth extends MY_Controller {

	function __construct() {
        parent::__construct();

    }

    function index(){
		//echo $this->encrypt->decode("je8SrHJtBN2imtp7X5lZT5l7z6vsMv2uqpBmNOU/NbrvCQ8mjmjZKbdg2ixUEN5sTd6RvWjzWet7fOPdSrdI3g==");
		//echo $this->encrypt->encode("demo");
		//die();
		$this->template['active'] = 'home';
		if ($this->session->userdata('userinfo')) {
			redirect(base_url().'webadmin/dashboard');
	    } else {
			$this->load->view('login', $this->template);
		}
	}

	function in() {
		$user = $this->input->post('user');
		$pass = $this->input->post('pass');
		// $redirect = isset($_GET["redirect"]) ? $_GET["redirect"] : '';
		if ($this->configApp["superUsers"][$user] && $pass == $this->encrypt->decode($this->configApp["superUsers"][$user])) {
			$array = array(
					"_id" => $user,
					"idUser" => $user,
					"akses" => "1", 
					"changePasswordDate" => date('Y-m-d H:i:s')
				);
			$this->session->set_userdata('userinfo', $array);
			redirect(base_url().'webadmin/dashboard');
		}else if($user == "" && $pass == ""){
			$this->session->set_flashdata('response', array('status' => 'error', 'message' => 'Username atau password kosong, silahkan ulangi kembali'));	
			redirect(base_url().'webadmin');
		}else {
			$pass = md5($pass);
			//$cekold = $this->model_global->get_data(array('data' => 'row','table' => 'user', 'where' => array('status !=' => -1, 'BINARY username =' => $user, 'BINARY password=' => $pass)));
			$cek = $this->db->query("selECT * FROM (`user`) WHERE `status` != -1 AND BINARY username = '".$user."' AND BINARY password= '".$pass."'")->result_array();
			if(!empty($cek)){
				if($cek[0]['status']=="0"){
					$this->response = $this->session->flashdata('response');
					$this->session->set_flashdata('response', array('status' => 'error', 'message' => 'Akun non-aktif, silahkan hubungi administrator'));	
					redirect(base_url().'webadmin');
					
				}else{
					$array = array(
							"_id" => $cek[0]['id_user'],
							"idUser" => $cek[0]['name'], 
							"akses" => $cek[0]['akses'],
							"changePasswordDate" => date('Y-m-d H:i:s')
						);
					$this->session->set_userdata('userinfo', $array);
					redirect(base_url().'webadmin/dashboard');
				}
			}else{
				$this->response = $this->session->flashdata('response');
				$this->session->set_flashdata('response', array('status' => 'error', 'message' => 'Username atau password yang dimasukkan salah, silahkan ulangi kembali'));	
				redirect(base_url().'webadmin');
			}
		}
	}
	
	function out() {
		$this->session->set_userdata('userinfo', array());
		redirect(base_url()."webadmin");
	}
}

