<?php
require_once __DIR__ . '/../DBconnection.php';

class UsuarioController extends DBconnection
{
    public function login($user, $pass)
    {
        $query = "SELECT u.*, r.rol AS rol 
                  FROM usuario u
                  INNER JOIN rol r ON u.id_rol = r.id
                  WHERE u.nombre = :user AND u.status = 1";
        $stmt = $this->connect()->prepare($query);
        $stmt->bindParam(':user', $user, PDO::PARAM_STR);
        $stmt->execute(); // Asegúrate de ejecutar la consulta
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($result && password_verify($pass, $result['password'])) {
            session_start();
            $_SESSION['loggedin'] = true;
            $_SESSION['id'] = $result['id'];
            $_SESSION['nombre'] = $result['nombre'];
            $_SESSION['rol'] = $result['rol'];

            echo json_encode(['status' => 'success', 'message' => 'Usuario logueado exitosamente']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Usuario o contraseña incorrectos']);
        }
    }

    public function logout()
    {
        session_start();
        session_destroy();
        echo json_encode(['status' => 'success', 'message' => 'Sesión cerrada exitosamente']);
    }

    public function getUsers()
    {
        $query = "SELECT u.*, r.rol AS rol
                  FROM usuario u
                  INNER JOIN rol r ON u.id_rol = r.id
                  WHERE u.status = 1";
        $stmt = $this->connect()->prepare($query);
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($result);
    }

    public function getUser($id)
    {
        $query = "SELECT u.*, r.rol AS rol
                  FROM usuario u
                  INNER JOIN rol r ON u.id_rol = r.id
                  WHERE u.id = :id";
        $stmt = $this->connect()->prepare($query);
        $stmt->execute(array(':id' => $id));
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        echo json_encode($result);
    }

    public function deleteUser($id)
    {
        $query = "UPDATE usuario SET status = 0 WHERE id = :id";
        $stmt = $this->connect()->prepare($query);
        $stmt->execute(array(':id' => $id));
        if ($stmt->rowCount() > 0) {
            echo json_encode(['status' => 'success', 'message' => 'Usuario eliminado exitosamente']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'No se pudo eliminar el usuario']);
        }
    }

    public function createUser($name, $pass, $rol)
    {
        $hashedPass = password_hash($pass, PASSWORD_DEFAULT);

        $query = "INSERT INTO usuario (nombre, password, id_rol, status) 
                  VALUES (:name, :pass, :rol, 1)";
        $stmt = $this->connect()->prepare($query);
        $stmt->execute(array(':name' => $name, ':pass' => $hashedPass, ':rol' => $rol));
        if ($stmt->rowCount() > 0) {
            echo json_encode(['status' => 'success', 'message' => 'Usuario creado exitosamente']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'No se pudo crear el usuario']);
        }
    }

    public function updateUser($id, $name, $pass, $rol)
    {
        $hashedPass = password_hash($pass, PASSWORD_DEFAULT);

        $query = "UPDATE usuario SET nombre = :name, password = :pass, id_rol = :rol WHERE id = :id";
        $stmt = $this->connect()->prepare($query);
        $stmt->execute(array(':name' => $name, ':pass' => $hashedPass, ':rol' => $rol, ':id' => $id));
        if ($stmt->rowCount() > 0) {
            echo json_encode(['status' => 'success', 'message' => 'Usuario actualizado exitosamente']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'No se pudo actualizar el usuario']);
        }
    }

    public function getRoles()
    {
        $query = "SELECT * FROM rol";
        $stmt = $this->connect()->prepare($query);
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($result);
    }
}
