<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Services\ServiceResponse\ServiceResponseInterface;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;
use App\Services\AnamneseService;
use App\Services\ServiceResponse\ServiceResponse;
use App\Services\MedicoService;
use App\Services\AssistenteService;
use App\Services\JWT\UsuarioLogado;
use App\Validations\ConsultaValidation;
use App\Services\FormularioService;

class AnamneseController extends BaseController {

	public function newAnamneseAdicional(): Response {

		$request = $this->getDataPost();
		$service = new AnamneseService();
		$medicoService = new MedicoService();
		$assistenteService = new AssistenteService();
		$service_response = new ServiceResponse();
		$valid = $service->newAnamneseAdicionalValid( $request );
		if (!$valid) {
			$service_response->setStatus( ServiceResponseInterface::INSUFFICIENT_DATA );
		} else {
			$id_medico = $medicoService->getMedicoIDFromUsuarioID( UsuarioLogado::getUsuarioId() );
			$id_assistente = $assistenteService->getAssistenteIDFromUsuarioID( UsuarioLogado::getUsuarioId() );
			if (($id_medico == 0) && ($id_assistente == 0)) {
				$service_response->setStatus( ServiceResponseInterface::FORBIDDEN );
			} else {
				$request ['idMedico'] = $id_medico;
				$request ['idAssistente'] = $id_assistente;
				$service_response = $service->newAnamneseAdicional( $request );
			}
		}

		$response_messages = [ 
			ServiceResponseInterface::SUCESS => [ 
				'code' => ResponseInterface::HTTP_OK,
				'message' => 'Os dados do dashboard foram encontrados com sucesso.'
			],
			ServiceResponseInterface::FORBIDDEN => [ 
				'code' => ResponseInterface::HTTP_FORBIDDEN,
				'message' => 'Usuário sem permissão para esta operação.'
			],
			ServiceResponseInterface::HAVE_CONFLICTS => [ 
				'code' => ResponseInterface::HTTP_CONFLICT,
				'message' => 'Dados conflitantes.'
			],
			ServiceResponseInterface::FOREIGN_KEY_DONT_EXISTS => [ 
				'code' => ResponseInterface::HTTP_BAD_REQUEST,
				'message' => 'Dados inválidos.'
			],
			ServiceResponseInterface::INSUFFICIENT_DATA => [ 
				'code' => ResponseInterface::HTTP_BAD_REQUEST,
				'message' => 'Dados inválidos.'
			],
			ServiceResponseInterface::SERVICE_INTERNAL_ERROR => [ 
				'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
				'message' => 'Erro interno do servidor.'
			],
			ServiceResponseInterface::UNKNOWN_ERROR => [ 
				'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
				'message' => 'Erro interno do servidor.'
			],
			ServiceResponseInterface::DATABASE_CONNECTION_ERROR => [ 
				'code' => ResponseInterface::HTTP_FAILED_DEPENDENCY,
				'message' => 'Erro interno decomunicação com Banco de dados.'
			]
		];

		return $this->getResponse( $service_response, $response_messages );

	}

	public function saveAnamneseAdicional(): Response {

		/*
		 * { "id_formulario":171,"id_agendamento":6593,"titulo":"titulo","descricao":"descricao",
		 * "respostas":[{"id_pergunta":1250,"resposta":"TEste 01"},{"id_pergunta":1251,"resposta":"10"},
		 * {"id_pergunta":1252,"resposta":"TEste 01"},{"id_pergunta":1253,"resposta":"TEste 01"},
		 * {"id_pergunta":1254,"resposta":"TEste 01"},{"id_pergunta":1255,"resposta":"TEste 01"},
		 * {"id_pergunta":1256,"resposta":"TEste 01"}],
		 * "id_requisicao_procedimento":3123}
		 */
		$data_post = $this->getDataPost();

		$validation_errors = ConsultaValidation::validateRegisterPost( $data_post );

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

		$respostas = $data_post ['respostas'];
		$formularioService = new FormularioService();
		$formulario = $formularioService->getFormularioByID( $data_post ['id_formulario'] );
		$perguntas = $formulario->getData() ['perguntas'];
		$resp = $formularioService->getReformatRespostasFormulario( $perguntas, $respostas );
		$data_post ['respostas'] = $resp;
		$service = new AnamneseService();
		$service_response = $service->saveAnamneseAdicional( $data_post );

		$response_messages = [ 
			ServiceResponseInterface::SUCESS => [ 
				'code' => ResponseInterface::HTTP_OK,
				'message' => 'Os dados foram gravados com sucesso.'
			],
			ServiceResponseInterface::FORBIDDEN => [ 
				'code' => ResponseInterface::HTTP_FORBIDDEN,
				'message' => 'Usuário sem permissão para esta operação.'
			],
			ServiceResponseInterface::HAVE_CONFLICTS => [ 
				'code' => ResponseInterface::HTTP_CONFLICT,
				'message' => 'Dados conflitantes.'
			],
			ServiceResponseInterface::VALIDATION_PARAMS_ERROR => [ 
				'code' => ResponseInterface::HTTP_BAD_REQUEST,
				'message' => 'Requisição com parametros inconsistentes'
			],
			ServiceResponseInterface::FOREIGN_KEY_DONT_EXISTS => [ 
				'code' => ResponseInterface::HTTP_BAD_REQUEST,
				'message' => 'Dados inválidos.'
			],
			ServiceResponseInterface::INSUFFICIENT_DATA => [ 
				'code' => ResponseInterface::HTTP_BAD_REQUEST,
				'message' => 'Dados inválidos.'
			],
			ServiceResponseInterface::SERVICE_INTERNAL_ERROR => [ 
				'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
				'message' => 'Erro interno do servidor.'
			],
			ServiceResponseInterface::UNKNOWN_ERROR => [ 
				'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
				'message' => 'Erro interno do servidor.'
			],
			ServiceResponseInterface::DATABASE_CONNECTION_ERROR => [ 
				'code' => ResponseInterface::HTTP_FAILED_DEPENDENCY,
				'message' => 'Erro interno decomunicação com Banco de dados.'
			]
		];

		return $this->getResponse( $service_response, $response_messages );

	}

	public function newAnamneseRetroativa(): Response {

		$request = $this->getDataPost();
		$service = new AnamneseService();
		$medicoService = new MedicoService();
		$service_response = new ServiceResponse();
		$valid = $service->newAnamneseRetroativaValid( $request );
		if (!$valid) {
			$service_response->setStatus( ServiceResponseInterface::INSUFFICIENT_DATA );
		} else {
			$id_medico = $medicoService->getMedicoIDFromUsuarioID( UsuarioLogado::getUsuarioId() );
			if ($id_medico == 0) {
				$service_response->setStatus( ServiceResponseInterface::FORBIDDEN );
			} else {
				$request ['idMedico'] = $id_medico;
				$service_response = $service->newAnamneseRetroativa( $request );
			}
		}

		$response_messages = [ 
			ServiceResponseInterface::SUCESS => [ 
				'code' => ResponseInterface::HTTP_OK,
				'message' => 'Os dados foram gravados com sucesso.'
			],
			ServiceResponseInterface::FORBIDDEN => [ 
				'code' => ResponseInterface::HTTP_FORBIDDEN,
				'message' => 'Usuário sem permissão para esta operação.'
			],
			ServiceResponseInterface::HAVE_CONFLICTS => [ 
				'code' => ResponseInterface::HTTP_CONFLICT,
				'message' => 'Dados conflitantes.'
			],
			ServiceResponseInterface::FOREIGN_KEY_DONT_EXISTS => [ 
				'code' => ResponseInterface::HTTP_BAD_REQUEST,
				'message' => 'Dados inválidos.'
			],
			ServiceResponseInterface::INSUFFICIENT_DATA => [ 
				'code' => ResponseInterface::HTTP_BAD_REQUEST,
				'message' => 'Dados inválidos.'
			],
			ServiceResponseInterface::SERVICE_INTERNAL_ERROR => [ 
				'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
				'message' => 'Erro interno do servidor.'
			],
			ServiceResponseInterface::UNKNOWN_ERROR => [ 
				'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
				'message' => 'Erro interno do servidor.'
			],
			ServiceResponseInterface::DATABASE_CONNECTION_ERROR => [ 
				'code' => ResponseInterface::HTTP_FAILED_DEPENDENCY,
				'message' => 'Erro interno decomunicação com Banco de dados.'
			]
		];

		return $this->getResponse( $service_response, $response_messages );

	}

}

