<?php

namespace src\Service;

class logService
{
    public function salvar(\src\Model\logModel $log)
    {
        $conexao = new \src\Conexao\Conexao();
        $conn = $conexao->getConexao();

        $query = "INSERT INTO log (rota, metodo, erro) VALUES (?, ?, ?)";

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

        $rota = $log->getRota();
        $metodo = $log->getMetodo();
        $erro = $log->getErro();

        $stmt->bind_param("sss", $rota, $metodo, $erro);

        $stmt->execute();
    }

    public function listarPaginado($paginaAtual = 1, $itensPorPagina = 20) {
        $conexao = new \src\Conexao\Conexao();
        $conn = $conexao->getConexao();

        $query = "SELECT COUNT(*) as total FROM log";
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            throw new \Exception("Erro ao preparar a consulta: " . $conn->error);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        $totalRegistro = $result->fetch_object()->total;

        $offset = ($paginaAtual - 1) * $itensPorPagina;

        $query = "SELECT * FROM log ORDER BY id DESC LIMIT ?, ?";
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            throw new \Exception("Erro ao preparar a consulta: " . $conn->error);
        }
        $stmt->bind_param("ii", $offset, $itensPorPagina);
        $stmt->execute();
        $result = $stmt->get_result();

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

        $stmt->close();
        $conn->close();

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

    public function localizar($id)
    {
        $conexao = new \src\Conexao\Conexao();
        $conn = $conexao->getConexao();

        $query = "SELECT * FROM log WHERE id = ?";

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

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

        $stmt->execute();

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

        return $log;
    }
}
