<?php
require_once ("config/db.php");
require_once ("config/conexion.php");
class Login
{
  	private $db_connection = null;
	public $errors = array();
    public $messages = array();
	
	public function __construct()
    {
        if (isset($_GET["logout"])) 
		{
            $this->doLogout();
        }
        elseif (isset($_POST["login"])) 
        {
            $this->dologinWithPostData();
        }
    }

	private function dologinWithPostData()
    {
        if (empty($_POST['user_name'])) 
        {
            $this->errors[] = "Campo usuario vacío.";
            return;
        } 
        if (empty($_POST['user_password'])) 
        {
            $this->errors[] = "Campo contraseña vacío.";
            return;
        }

        $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        if ($this->db_connection->connect_errno) 
        {
            $this->errors[] = "Problema de conexión con la base de datos.";
            return;
        }
        $this->db_connection->set_charset("utf8");

        $user_name = $this->db_connection->real_escape_string($_POST['user_name']);
        $sql = "SELECT * FROM users WHERE user_name = '$user_name' OR user_email = '$user_name'";
        $result_of_login_check = $this->db_connection->query($sql);

        if (!$result_of_login_check || $result_of_login_check->num_rows === 0) 
        {
            $this->errors[] = "Usuario no existe.";
            return;
        }

        $result_row = $result_of_login_check->fetch_object();

        if ($result_row->intentos == 1) 
        {
            $this->errors[] = "Usuario bloqueado. Contacte al administrador.";
            return;
        }

        if ($_POST['user_password'] !== $result_row->user_password_hash) 
        {
            $this->errors[] = "Contraseña incorrecta.";
            return;
        }

        // Login exitoso: establecer variables de sesión
        $_SESSION['user_id'] = $result_row->user_id;
        $_SESSION['user_name'] = $result_row->user_name;
        $_SESSION['user_email'] = $result_row->user_email;
        $_SESSION['rol'] = $result_row->ROL;
        $_SESSION['estado'] = $result_row->estado;
        $_SESSION['user_login_status'] = 1;
        $_SESSION['intentos'] = $result_row->intentos;
        $_SESSION['role'] = $result_row->ROL;
        $_SESSION['estadoe'] = $result_row->estado;

        $usuario_completo = $result_row->firstname . " " . $result_row->lastname;
        $_SESSION['log'] = $result_row->user_name;
        $_SESSION['usuario'] = $usuario_completo;

        // Registrar sesión en historico_sesiones
        $ip = $_SERVER['REMOTE_ADDR'];
        $fecha = date("Y/m/d");
        $hora_ini = date("H") . " : " . date("i") . " : " . date("s");
        $this->db_connection->query("INSERT INTO historico_sesiones (user_name, usuario, fecha, hora_ini, hora_fin, ip) VALUES ('{$result_row->user_name}', '$usuario_completo', '$fecha', '$hora_ini', '', '$ip')");

        $this->messages[] = "Inicio de sesión exitoso.";
    }
    
	public function doLogout()
    {
		global $con;
		if (isset($_SESSION['user_name'])) {
			$user = mysqli_real_escape_string($con, $_SESSION['user_name']);
			$res = mysqli_query($con, "SELECT MAX(id_sesion) AS max_id FROM historico_sesiones WHERE user_name='$user'");
			$row = mysqli_fetch_assoc($res);
			if ($row && $row['max_id']) {
				$hora_fin = date("H") . " : " . date("i") . " : " . date("s");
				mysqli_query($con, "UPDATE historico_sesiones SET hora_fin='$hora_fin' WHERE id_sesion='{$row['max_id']}'");
			}
		}
        session_destroy();
        $this->messages[] = "Has sido desconectado.";
		header("location: index.php");
	}
	
	public function isUserLoggedIn()
    {
        if (isset($_SESSION['user_login_status']) AND $_SESSION['user_login_status'] == 1) 
        {
            return true;
        }
        return false;
    }
}
?>
