<?php

namespace App\Controllers;

use App\DAO\Filter\QueryFilterTranslator;
use App\DAO\Order\QueryOrder;
use App\DAO\Order\QueryOrderTranslator;
use App\DAO\Pagination\Pagination;
use App\Services\AgendaService;
use App\Services\CepService;
use App\Services\FormularioService;
use App\Services\ServiceResponse\ServiceResponseInterface;
use App\Utils\Collections\QueryFilterCollection;
use App\Utils\Collections\QueryOrderCollection;
use App\Validations\FormularioValidation;
use App\Validations\PacienteValidation;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;

class FormularioController extends BaseController {

	public function registerFormulario(): Response {

		$data_post = $this->getDataPost();
		$validation_errors = FormularioValidation::validateFormularioRegistration( $data_post );
		if (count( $validation_errors )) {
			return $this->response->setStatusCode( ResponseInterface::HTTP_BAD_REQUEST )
				->setJSON( [ 
				'message' => 'Informe os dados corretamente.',
				'errors' => $validation_errors
			] );
		}
		$formulario_service_response = (new FormularioService())->registerFormulario( $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 formulário foi cadastrado com sucesso.'
			],
			ServiceResponseInterface::FORBIDDEN => [ 
				'code' => ResponseInterface::HTTP_FORBIDDEN,
				'message' => 'O usuário não tem permissão para realizar essa operação.'
			],
			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( $formulario_service_response, $response_messages );

	}

	public function getFormulariosByMedicoID(int $id_medico): Response {

		$pagination = $this->getPaginationFromRequest();
		$query_filter_collection = new QueryFilterCollection( $_GET, QueryFilterTranslator::formulario() );
		$query_order_collection = new QueryOrderCollection( $_GET, QueryOrderTranslator::formulario() );
		$formulario_service_response = (new FormularioService())->getFormularioList( $id_medico, $pagination, $query_filter_collection, $query_order_collection );
		$response_messages = [ 
			ServiceResponseInterface::SUCESS => [ 
				'code' => ResponseInterface::HTTP_OK,
				'message' => 'Os dados dos formulários foram encontrados com sucesso.'
			],
			ServiceResponseInterface::RECORD_NOT_FOUND => [ 
				'code' => ResponseInterface::HTTP_PARTIAL_CONTENT,
				'message' => 'Nenhum registro foi encontrado.'
			],
			ServiceResponseInterface::FORBIDDEN => [ 
				'code' => ResponseInterface::HTTP_FORBIDDEN,
				'message' => 'Esse usuário não tem permissão para realizar essa operação.'
			],
			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 getAllFormularios(): Response {

		$pagination = $this->getPaginationFromRequest();
		
// 		if (is_null( $pagination )) {
// 			$pagination = Pagination::builder()->setCurrentPage( 1 )
// 			->setPerPage( 10 )
// 			->build();
// 		}
		
		$query_filter_collection = new QueryFilterCollection( $_GET, QueryFilterTranslator::formulario() );
		$query_order_collection = new QueryOrderCollection( $_GET, QueryOrderTranslator::formulario() );
//         $query_order_collection->push(QueryOrder::builder()
//             ->setTable('formulario')
//             ->setNameParam('titulo')
//             ->setDesc($_GET['sort'] === '-')
//             ->build()
//         );
		$formulario_service_response = (new FormularioService())->getAllFormularioList( $pagination, $query_filter_collection, $query_order_collection );
		$response_messages = [ 
			ServiceResponseInterface::SUCESS => [ 
				'code' => ResponseInterface::HTTP_OK,
				'message' => 'Os dados dos formulários foram encontrados com sucesso.'
			],
			ServiceResponseInterface::RECORD_NOT_FOUND => [ 
				'code' => ResponseInterface::HTTP_PARTIAL_CONTENT,
				'message' => 'Nenhum registro foi encontrado.'
			],
			ServiceResponseInterface::FORBIDDEN => [ 
				'code' => ResponseInterface::HTTP_FORBIDDEN,
				'message' => 'Esse usuário não tem permissão para realizar essa operação.'
			],
			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 getFormularioByID(int $id_formulario): Response {

		$formulario_service_response = (new FormularioService())->getFormularioByID( $id_formulario );
		$response_messages = [ 
			ServiceResponseInterface::SUCESS => [ 
				'code' => ResponseInterface::HTTP_OK,
				'message' => 'Os dados do formulário 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 updateFormularioData(int $id_formulario): Response {

		$data_post = $this->getDataPost();
		$validation_errors = FormularioValidation::validateFormularioUpdate( $data_post );
		if (count( $validation_errors )) {
			return $this->response->setStatusCode( ResponseInterface::HTTP_BAD_REQUEST )
				->setJSON( [ 
				'message' => 'Informe os dados corretamente.',
				'errors' => $validation_errors
			] );
		}

		$paciente_service_response = (new FormularioService())->updateFormularioData( $id_formulario, $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' => 'Os dados do formulario 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.'
			],
			ServiceResponseInterface::FORBIDDEN => [ 
				'code' => ResponseInterface::HTTP_FORBIDDEN,
				'message' => 'O usuário não tem permissão para realizar essa operação.'
			],
			ServiceResponseInterface::UNKNOWN_ERROR => [ 
				'code' => ResponseInterface::HTTP_UNAUTHORIZED,
				'message' => 'Este formulário já possui respostas, não é possível editá-lo. Salve-o como um novo formulário.'
			],
			ServiceResponseInterface::ERROR_DELETING => [ 
				'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
				'message' => 'Houve erros ao deletar os dados do formulário.'
			],
			ServiceResponseInterface::ERROR_UPDATE => [ 
				'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
				'message' => 'Houve erros ao atualizar os dados do formulário.'
			]
		];
		return $this->getResponse( $paciente_service_response, $response_messages );

	}

	public function updateFormularioSimple(int $id_formulario): Response {

		$data_post = $this->getDataPost();
		$validation_errors = FormularioValidation::validateFormularioUpdateSimple( $data_post );
		if (count( $validation_errors )) {
			return $this->response->setStatusCode( ResponseInterface::HTTP_BAD_REQUEST )
				->setJSON( [ 
				'message' => 'Informe os dados corretamente.',
				'errors' => $validation_errors
			] );
		}
		$formulario_service_response = (new FormularioService())->updateFormularioSimpleData( $id_formulario, $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::RECORD_NOT_FOUND => [ 
				'code' => ResponseInterface::HTTP_PARTIAL_CONTENT,
				'message' => 'O formulario não foi encontrado.'
			],
			ServiceResponseInterface::SUCESS => [ 
				'code' => ResponseInterface::HTTP_OK,
				'message' => 'Os dados do formulario foram atualizados com sucesso.'
			],
			ServiceResponseInterface::VALIDATION_PARAMS_ERROR => [ 
				'code' => ResponseInterface::HTTP_BAD_REQUEST,
				'message' => 'Informe os dados corretamente.'
			]
		];
		return $this->getResponse( $formulario_service_response, $response_messages );

	}

	public function desativaFormulario(int $id_formulario): Response {

		$paciente_service_response = (new FormularioService())->desativaFormulario( $id_formulario );
		$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' => 'Este formulario foi desativado.'
			],
			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.'
			],
			ServiceResponseInterface::FORBIDDEN => [ 
				'code' => ResponseInterface::HTTP_FORBIDDEN,
				'message' => 'O usuário não tem permissão para realizar essa operação.'
			],
			ServiceResponseInterface::UNKNOWN_ERROR => [ 
				'code' => ResponseInterface::HTTP_UNAUTHORIZED,
				'message' => 'Este formulário já possui respostas, não é possível editá-lo. Salve-o como um novo formulário.'
			],
			ServiceResponseInterface::ERROR_DELETING => [ 
				'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
				'message' => 'Houve erros ao deletar os dados do formulário.'
			],
			ServiceResponseInterface::ERROR_UPDATE => [ 
				'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
				'message' => 'Houve erros ao atualizar os dados do formulário.'
			]
		];
		return $this->getResponse( $paciente_service_response, $response_messages );

	}

	public function getListFormulariosByProcedimentoId(int $idProcedimento): Response {

		$formularioService = new FormularioService();
		$formularioService_response = $formularioService->getListFormulariosByProcedimentoId( $idProcedimento );
		$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' => 'Consulta Executada 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.'
			],
			ServiceResponseInterface::FORBIDDEN => [ 
				'code' => ResponseInterface::HTTP_FORBIDDEN,
				'message' => 'O usuário não tem permissão para realizar essa operação.'
			],
			ServiceResponseInterface::UNKNOWN_ERROR => [ 
				'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
				'message' => 'Erro interno do servidor.'
			]
		];
		return $this->getResponse( $formularioService_response, $response_messages );

	}


    public function getListFormulariosByAtendimento(): Response {

        $formularioService = new FormularioService();
        $formularioService_response = $formularioService->getListFormulariosByAtendimento();
        $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' => 'Formulário listado 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.'
            ],
            ServiceResponseInterface::FORBIDDEN => [
                'code' => ResponseInterface::HTTP_FORBIDDEN,
                'message' => 'O usuário não tem permissão para realizar essa operação.'
            ],
            ServiceResponseInterface::UNKNOWN_ERROR => [
                'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
                'message' => 'Erro interno do servidor.'
            ]
        ];
        return $this->getResponse( $formularioService_response, $response_messages );

    }

}