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

class Login extends CI_Controller {

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

		// Load form helper library
		$this->load->helper('form');

		// Load form validation library
		$this->load->library('form_validation');

		// Load database
		// Se carga en autoload
		//$this->load->model('Usuario_model', 'Usuario', true);
	}

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function index() {
		if (!empty($_SESSION['usuario'])) {
			redirect('ventas/tienda');
		}
		if ($this->Usuario->try()){
			redirect('/ventas/tienda', 'refresh');
		}

		if (!empty($this->input->post('username'))) {
			$this->form_validation->set_rules('username', 'Username', 'trim|required');
			$this->form_validation->set_rules('password', 'Password', 'trim|required');

			if ($this->form_validation->run() == TRUE) {
				$data = getPost($this->input, ['username', 'password']);
				$result = $this->Usuario->login($data);
				if ($result == TRUE) {

					$username = $this->input->post('username');
					$result = $this->Usuario->get($username);
					if ($result != false) {
						$session_data = array(
							'id' => $result[0]->id,
							'username' => $result[0]->username,
							'ps_id' => $result[0]->ps_id,
							'alias' => $result[0]->alias,
							'admin' => $result[0]->id_grupo == 1,
							'perfil' => $result[0]->id_grupo
						);
						$_SESSION['usuario'] =  $session_data;

						// Solo guardamos el username por ahora
						$cookie_payload = array(
							'username' => $result[0]->username
						);
						$cookie = array(
							'name' => 'VentasDMG',
							'value' => base64_encode(json_encode($cookie_payload)),
							'expire' => '36000000',
						);
						$this->input->set_cookie($cookie);
						redirect('/ventas/tienda', 'refresh');
					}
				}
			}
		}
		$this->load->view('login');
	}

	public function logout() {
		unset($_SESSION['usuario']);
		delete_cookie('VentasDMG');
		session_destroy();
		redirect('/login', 'refresh');
	}
}
