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

class Login extends MY_Controller {
	function __construct(){
        parent::__construct();
		$this->load->model('login_model');
		$this->load->model('setting_model');
        $this->load->library('form_validation');		
	}
	
	function index(){
		// Check Session Login
		if(isset($_SESSION['logged_in'])){
			redirect(site_url());
		}
		// Check Remember Me
		if(isset($_COOKIE['remember_me'])){			
			$this->login_model->set_session($_COOKIE['remember_me']);
			redirect(site_url());
		}
		$data['judul_app'] = $this->setting_model->get_by_id(1);
		$this->load->view('login', $data);
	}
	
	public function login_process($check_login = false){
		// Check Session Login
		if(isset($_SESSION['logged_in'])){
			redirect(site_url());
		}
		// Check Remember Me
		if(isset($_COOKIE['remember_me'])){			
			$this->login_model->set_session($_COOKIE['remember_me']);
			redirect(site_url());
		}
		$username = escape($this->input->post("username"));		
		$remember_me = escape($this->input->post("remember_me"));	
		if($username){
			$check_login = $this->login_model->check_login($username);	
		}
		if($check_login){
			$id = $check_login[0]->id;
			$this->login_model->set_session($id,$username);
			if($remember_me){
				$this->login_model->set_cookie_remember($username);
			}
			$this->session->set_flashdata('msg', 'Selamat Datang');
			redirect(site_url());
		}else{
			$this->session->set_flashdata('login_false', 'Username salah.');
			redirect(site_url('login'));
		}
	}
	
	function logout(){
		session_destroy();
		redirect(site_url(''));
	}
}
