<?php

namespace src\Service;

use src\Conexao\Conexao;

class usuarioService
{

    private $conn;

    public function __construct()
    {
        $conexao = new Conexao();
        $this->conn = $conexao->getConexao();
    }

    public function listar($paginaAtual = 1, $itensPorPagina = 20, $termoPesquisa = null)
    {
        $offset = ($paginaAtual - 1) * $itensPorPagina;

        $queryTotal = "SELECT COUNT(*) as total FROM usuario";
        $query = "SELECT * FROM usuario";

        if (!empty($termoPesquisa)) {
            $termoPesquisa = '%' . $termoPesquisa . '%';
            $queryTotal .= " WHERE nome LIKE ?";
            $query .= " WHERE nome LIKE ?";
        }

        $queryTotal .= " ORDER BY id DESC";
        $stmtTotal = $this->conn->prepare($queryTotal);
        if (!$stmtTotal) {
            throw new \Exception("Erro ao preparar a consulta de total: " . $this->conn->error);
        }

        if (!empty($termoPesquisa)) {
            $stmtTotal->bind_param("s", $termoPesquisa);
        }

        $stmtTotal->execute();
        $resultTotal = $stmtTotal->get_result();
        $totalRegistro = $resultTotal->fetch_object()->total;
        $stmtTotal->close();

        $query .= " ORDER BY id DESC LIMIT ?, ?";
        $stmt = $this->conn->prepare($query);
        if (!$stmt) {
            throw new \Exception("Erro ao preparar a consulta: " . $this->conn->error);
        }

        if (!empty($termoPesquisa)) {
            $stmt->bind_param("sii", $termoPesquisa, $offset, $itensPorPagina);
        } else {
            $stmt->bind_param("ii", $offset, $itensPorPagina);
        }

        $stmt->execute();
        $result = $stmt->get_result();

        $usuarios = [];
        while ($row = $result->fetch_object()) {
            $usuarios[] = $row;
        }

        $stmt->close();

        return [
            'paginaAtual' => intval($paginaAtual),
            'itensPorPagina' => intval($itensPorPagina),
            'totalRegistro' => $totalRegistro,
            'dados' => $usuarios
        ];
    }

    public function salvar(\src\Model\usuarioModel $usuario)
    {
        $query = "INSERT INTO usuario (nome, email, senha) VALUES (?, ?, ?)";

        $stmt = $this->conn->prepare($query);
        if (!$stmt) {
            throw new \Exception("Erro ao preparar a consulta: " . $this->conn->error);
        }

        $nome = $usuario->getNome();
        $email = $usuario->getEmail();
        $senha = $usuario->getSenha();

        $stmt->bind_param(
            'sss',
            $nome,
            $email,
            $senha
        );
        $stmt->execute();

        return $stmt->insert_id;
    }

    public function atualizar(\src\Model\usuarioModel $usuario)
    {
        $query = "UPDATE usuario SET nome = ?, email = ?, senha = ? WHERE id = ?";

        $stmt = $this->conn->prepare($query);
        if (!$stmt) {
            throw new \Exception("Erro ao preparar a consulta: " . $this->conn->error);
        }

        $id = $usuario->getId();
        $nome = $usuario->getNome();
        $email = $usuario->getEmail();
        $senha = $usuario->getSenha();

        $stmt->bind_param(
            'sssi',
            $nome,
            $email,
            $senha,
            $id
        );
        $stmt->execute();
    }

    public function localizar($id)
    {
        $query = "SELECT * FROM usuario WHERE id = ?";

        $stmt = $this->conn->prepare($query);
        if (!$stmt) {
            throw new \Exception("Erro ao preparar a consulta: " . $this->conn->error);
        }

        $stmt->bind_param("i", $id);
        $stmt->execute();

        $result = $stmt->get_result();
        $usuario = $result->fetch_object();

        return $usuario;
    }

    public function deletar($id)
    {
        $queryPermissao = "DELETE FROM permissoes WHERE id_usuario = ?";

        $stmt = $this->conn->prepare($queryPermissao);
        if (!$stmt) {
            throw new \Exception("Erro ao preparar a consulta: " . $this->conn->error);
        }

        $stmt->bind_param("i", $id);
        $stmt->execute();

        $query = "DELETE FROM usuario WHERE id = ?";

        $stmt = $this->conn->prepare($query);
        if (!$stmt) {
            throw new \Exception("Erro ao preparar a consulta: " . $this->conn->error);
        }

        $stmt->bind_param("i", $id);
        $stmt->execute();

        
    }
}
