<?php


namespace App\Controllers;

use App\DAO\Filter\QueryFilter;
use App\DAO\Filter\QueryFilterTranslator;
use App\DAO\Order\QueryOrderTranslator;
use App\Services\DocumentoAnexoService;
use App\Services\ServiceResponse\ServiceResponseInterface;
use App\Utils\Collections\QueryFilterCollection;
use App\Utils\Collections\QueryOrderCollection;
use App\Validations\DocumentoAnexoValidation;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Paths;
use Exception;

class DocumentoAnexoController extends BaseController
{

    function registerDocumentoAnexo()
    {
        $data_post = $this->getDataPost();
        if (!$this->validate(DocumentoAnexoValidation::register())) {
            return $this->response->setJSON([
                'message' => 'Informe os dados corretamente.',
                'errors' => $this->validation->getErrors()
            ]);
        }
        if(!isset($_FILES['arquivo']) || $_FILES['arquivo']['name'] == '') {
            return $this->response->setJSON([
                'message' => 'Nenhum arquivo enviado.',
                'errors' => $this->validation->getErrors()
            ]);
        }

        try {
            $assistente_service_response = (new DocumentoAnexoService())->registerDocumentoAnexo($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 arquivo 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($assistente_service_response, $response_messages);
        } catch (Exception $e) {
            return(json_encode($e->getMessage()));
        }
    }

    function getDocumentoAnexoList(){
        $pagination = $this->getPaginationFromRequest();
        $query_filter_collection = new QueryFilterCollection($_GET, QueryFilterTranslator::anexos());
        $query_order_collection = new QueryOrderCollection($_GET, QueryOrderTranslator::anexos());
        $procedimento_service_response = (new DocumentoAnexoService())->getDocumentoAnexoList($pagination, $query_filter_collection, $query_order_collection);
        $response_messages = [
            ServiceResponseInterface::SUCESS => [
                'code' => ResponseInterface::HTTP_OK,
                'message' => 'Os dados da galeria 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($procedimento_service_response, $response_messages);
    }

    public function searchDocumentoAnexoByID (int $id_arquivo) : Response {
        $query_filter = QueryFilter::builder()
            ->setTable('documentos_anexados')
            ->setNameParam('id')
            ->setValue($id_arquivo)
            ->setIsExact(true)
            ->build();
        $erro_service_response = (new DocumentoAnexoService())->getDocumentoAnexo($query_filter);
        $response_messages = [
            ServiceResponseInterface::SUCESS => [
                'code' => ResponseInterface::HTTP_OK,
                'message' => 'O arquivo foi encontrado 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($erro_service_response, $response_messages);
    }

    public function deleteDocumentoAnexo (int $id_galeria) {
        $erro_service_response = (new DocumentoAnexoService())->deleteDocumentoAnexo($id_galeria);
        $response_messages = [
            ServiceResponseInterface::SUCESS => [
                'code' => ResponseInterface::HTTP_OK,
                'message' => 'A exclusão foi efetuda com sucesso.'
            ],
            ServiceResponseInterface::RECORD_NOT_FOUND => [
                'code' => ResponseInterface::HTTP_PARTIAL_CONTENT,
                'message' => 'Nenhum registro foi encontrado.'
            ],
            ServiceResponseInterface::RECORD_IS_LINKED => [
                'code' => ResponseInterface::HTTP_BAD_REQUEST,
                'message' => 'Essa foto está vinculada a outros cadastros do sistema. Portanto, não pode ser excluído.'
            ],
            ServiceResponseInterface::DATABASE_CONNECTION_ERROR => [
                'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
                'message' => 'Erro interno do servidor.'
            ],
        ];
        return $this->getResponse($erro_service_response, $response_messages);
    }

}
