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

class Auth extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model('Usuario_model');
		$this->load->model('App_config_model');
	}

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

	public function login()
	{
		if ($this->session->userdata('logged_in') === TRUE) {
			redirect('dashboard');
		}

		if ($this->input->method(TRUE) === 'POST') {
			$this->form_validation->set_rules('username', 'Usuario', 'trim|required');
			$this->form_validation->set_rules('password', 'Contrasena', 'trim|required');

			if ($this->form_validation->run() === TRUE) {
				$username = $this->input->post('username', TRUE);
				$password = $this->input->post('password', TRUE);

				$user = $this->Usuario_model->verificar_usuario($username, $password);
				if ($user) {
					$this->session->set_userdata(array(
						'user_id' => (int) $user->id,
						'username' => $user->username,
						'logged_in' => TRUE
					));

					redirect('dashboard');
				}

				$this->session->set_flashdata('error', 'Usuario o contrasena incorrectos.');
			}
		}

		$data['app_config'] = $this->App_config_model->obtener();
		$this->load->view('auth/login', $data);
	}

	public function logout()
	{
		$this->session->sess_destroy();
		redirect('login');
	}
}
