<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class login extends MX_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('form');
        $this->load->helper('cookie');
        $this->load->library('form_validation');
    }

    public function index()
    {
        // Se já está logado, redireciona para o dashboard
        $admin = $this->session->userdata('admin');
        if (is_array($admin) && !empty($admin['id'])) {
            redirect('admin/dashboard');
            return;
        }

        $data['page_title'] = lang('sign_in');
        $data['error']      = '';

        if ($this->input->post('submitted')) {
            $username = $this->input->post('username');
            $password = $this->input->post('password');

            if (empty($username) || empty($password)) {
                $data['error'] = lang('authenication_failed');
            } else {
                $result = $this->auth->login_admin($username, $password);
                if ($result) {
                    redirect('admin/dashboard');
                    return;
                } else {
                    $data['error'] = lang('authenication_failed');
                }
            }
        }

        $this->load->view('login/login', $data);
    }

    public function login()
    {
        $this->index();
    }

    public function logout()
    {
        $this->auth->logout();
        redirect('admin/login');
    }
}