<?php

namespace src\Controller;

use src\Service\permissaoService;
use src\Utils\responseHelpers;
use src\Utils\validator;
use src\Utils\token;
use Exception;

class permissaoController
{

    private $permissaoService;

    public function __construct(permissaoService $permissaoService)
    {
        $this->permissaoService = $permissaoService;
        token::verifyToken();
    }

    public function listar()
    {
        try {

            $id = $_GET['id'];
            $permissoes = $this->permissaoService->listar($id);
            responseHelpers::sendSuccessResponse($permissoes);
        } catch (Exception $e) {
            responseHelpers::sendErrorResponse($e->getMessage(), 500);
        }
    }

    public function salvar() {
        try {
            $data = json_decode(file_get_contents('php://input'), true);
            validator::validateRequiredFields($data, ['id_usuario', 'permissoes']);
            $data = array_map(function($value) {
                return is_string($value) ? htmlspecialchars($value) : $value;
            }, $data);

            $this->permissaoService->salvar($data['id_usuario'], $data['permissoes']);
            responseHelpers::sendSuccessResponse('Permissão salva com sucesso');
        } catch (Exception $e) {
            responseHelpers::sendErrorResponse($e->getMessage(), 500);
        }
    }
}
