<?php
class Login extends CI_Controller {

    function __construct(){
        parent::__construct();
        $this->load->model('user_model');
    }

    function index(){
        $view = '';
        $view['error'] = '';
        if ($this->user_model->is_logged_in() == TRUE)
            redirect('admin/home');

        $this->load->library('form_validation');
        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required');

        if ($this->input->post('login')) {
            if ($this->form_validation->run() == TRUE) {
                $username = $this->input->post('username');
                $password = md5($this->input->post('password'));
                if ($this->user_model->login($username, $password) == TRUE) {
                    //buat session user
                    $getUserData = $this->user_model->get_data($username, $password);
                    $userdata = array (
                        'username' => $username,
                        'password' => $password,
                        'accesslevel' => $getUserData->row()->access_level
                    );
                    $this->session->set_userdata($userdata);
                    //echo "<pre>"; print_r($this->session->all_userdata()); echo "</pre>";

                    redirect('admin/home');                    
                }
                else
                    $view['error'] = 'Username dan Password Salah';
            }
            else {
                $view['error'] = 'Username dan Password Harus Terisi';
            }
        }
        $this->load->view('login1', $view);
    }

    function logout() {
        $array_items = array (
            'username' => $this->session->userdata('username'),
            'password' => $this->session->userdata('password'),
            'accesslevel' => $this->session->userdata('accesslevel')
        );

        $this->session->unset_userdata($array_items);
        $this->session->sess_destroy();
        redirect(base_url(), 'refresh');
    }
}
?>