<?php

namespace src\Service;

use src\Conexao\Conexao;

class permissaoService
{

    private $conn;

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

    public function listar($id) {
        $query = "SELECT pa.url as url, pa.id AS id_pagina, pa.nome AS pagina, COALESCE(p.permissao, FALSE) AS permissao from paginas pa LEFT JOIN permissoes p on pa.id = p.id_pagina AND p.id_usuario = ?;";

        $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();

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

        return $permissao;
    }

    public function salvar($id_usuario, $permissoes) {
        $query = "
            INSERT INTO permissoes (id_usuario, id_pagina, permissao)
            VALUES (?, ?, ?)
            ON DUPLICATE KEY UPDATE permissao = VALUES(permissao);
        ";

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

        foreach ($permissoes as $permissao) {
            $id_pagina = $permissao['id_pagina'];
            $valor_permissao = $permissao['permissao']; 

            $stmt->bind_param("iii", $id_usuario, $id_pagina, $valor_permissao);
            $stmt->execute();
        }

        $stmt->close();
    }
}