<?php

namespace App\Controllers;

use App\DAO\PerfilDAO;
use App\DAO\Filter\QueryFilter;
use App\DAO\Filter\QueryFilterTranslator;
use App\DAO\Order\QueryOrderTranslator;
use App\Services\PerfilService;
use App\Services\ServiceResponse\ServiceResponseInterface;
use App\Utils\Collections\QueryFilterCollection;
use App\Utils\Collections\QueryOrderCollection;
use App\Validations\PerfilValidation;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;

class PerfilController extends BaseController {

    public function getPerfilList(): Response {
        $pagination = $this->getPaginationFromRequest();
        if ($_GET ['sort'] === null) {
            $_GET ['sort'] = "descricao";
        }
        $query_filter_collection = new QueryFilterCollection( $_GET, QueryFilterTranslator::perfil() );
        $query_order_collection = new QueryOrderCollection( $_GET, QueryOrderTranslator::perfil() );
        $unidade_service_response = (new PerfilService())->getPerfilList( $pagination, $query_filter_collection, $query_order_collection );
        $response_messages = [
            ServiceResponseInterface::SUCESS => [
                'code' => ResponseInterface::HTTP_OK,
                'message' => 'Os dados de perfil foram encontrados com sucesso.' ],
            ServiceResponseInterface::RECORD_NOT_FOUND => [
                'code' => ResponseInterface::HTTP_PARTIAL_CONTENT,
                'message' => 'Nenhum registro foi encontrado.' ],
            ServiceResponseInterface::SERVICE_INTERNAL_ERROR => [
                'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
                'message' => 'Erro interno do servidor.' ],
            ServiceResponseInterface::DATABASE_CONNECTION_ERROR => [
                'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
                'message' => 'Erro interno do servidor.' ] ];
        return $this->getResponse( $unidade_service_response, $response_messages );

    }

    public function getPerfilByID(int $id_perfil): Response {
        $formulario_service_response = (new PerfilService())->getPerfilByID($id_perfil);
        $response_messages = [
            ServiceResponseInterface::SUCESS => [
                'code' => ResponseInterface::HTTP_OK,
                'message' => 'Os dados do perfil foram encontrados com sucesso.'
            ],
            ServiceResponseInterface::RECORD_NOT_FOUND => [
                'code' => ResponseInterface::HTTP_PARTIAL_CONTENT,
                'message' => 'Nenhum registro foi encontrado.'
            ],
            ServiceResponseInterface::SERVICE_INTERNAL_ERROR => [
                'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
                'message' => 'Erro interno do servidor.'
            ],
            ServiceResponseInterface::DATABASE_CONNECTION_ERROR => [
                'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
                'message' => 'Erro interno do servidor.'
            ],
        ];
        return $this->getResponse($formulario_service_response, $response_messages);
    }


	public function register(): Response {

		if (! $this->validate( PerfilValidation::register() )) {
			return $this->response->setJSON( [ 
					'message' => 'Informe os dados corretamente.',
					'errors' => $this->validation->getErrors() ] );
		}
		$data_post = $_POST;
		$unidade_service_response = (new PerfilService())->registerPerfil($data_post);
		$response_messages = [ 
				ServiceResponseInterface::DATABASE_CONNECTION_ERROR => [ 
						'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
						'message' => 'Erro de conexão com o banco de dados.' ],
				ServiceResponseInterface::SUCESS => [ 
						'code' => ResponseInterface::HTTP_OK,
						'message' => 'O perfil foi cadastrado com sucesso.' ],
				ServiceResponseInterface::VALIDATION_PARAMS_ERROR => [ 
						'code' => ResponseInterface::HTTP_BAD_REQUEST,
						'message' => 'Informe os dados corretamente.' ],
				ServiceResponseInterface::SERVICE_INTERNAL_ERROR => [ 
						'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
						'message' => 'Erro interno do servidor.' ] ];
		return $this->getResponse( $unidade_service_response, $response_messages );

	}

	public function updatePerfilData(int $id_perfil): Response {

		if (! $this->validate( PerfilValidation::update( $id_perfil ) )) {
			return $this->response->setJSON( [ 
					'message' => 'Informe os dados corretamente.',
					'errors' => $this->validation->getErrors() ] );
		}
		$unidade_dao = new PerfilDAO();
		$validation = $unidade_dao->getPerfilFromId( $id_perfil );
		if ($validation == null) {
			return $this->response->setJSON( [ 
					'message' => 'O perfil não está registrado.',
					'errors' => $this->validation->getErrors() ] );
		}
		$unidade_service_response = (new PerfilService())->updatePerfilData( $id_perfil, $_POST );
		$response_messages = [ 
				ServiceResponseInterface::DATABASE_CONNECTION_ERROR => [ 
						'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
						'message' => 'Erro de conexão com o banco de dados.' ],
				ServiceResponseInterface::SUCESS => [ 
						'code' => ResponseInterface::HTTP_OK,
						'message' => 'Os dados do perfil foram atualizados com sucesso.' ],
				ServiceResponseInterface::VALIDATION_PARAMS_ERROR => [ 
						'code' => ResponseInterface::HTTP_BAD_REQUEST,
						'message' => 'Informe os dados corretamente.' ],
				ServiceResponseInterface::SERVICE_INTERNAL_ERROR => [ 
						'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
						'message' => 'Erro interno do servidor.' ] ];
		return $this->getResponse( $unidade_service_response, $response_messages );
	}

}