<?php

namespace App\Controllers;

use App\DAO\Filter\QueryFilterTranslator;
use App\DAO\Order\QueryOrderTranslator;
use App\Services\ConsultaService;
use App\Services\JWT\UsuarioLogado;
use App\Services\JWTService;
use App\Services\PetService;
use App\Services\ServiceResponse\ServiceResponseInterface;
use App\Utils\Collections\QueryFilterCollection;
use App\Utils\Collections\QueryOrderCollection;
use App\Validations\ConsultaValidation;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;
use App\Services\FormularioService;

class ConsultaController extends BaseController {

	public function registerConsulta() {

		$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'];
		for($i = 0; $i < count( $perguntas ); $i++) {
			if (count( $respostas ) > 0) {
				$tem = 0;
				for($y = 0; $y < count( $respostas ); $y++) {
					if ($perguntas [$i] ['id'] == $respostas [$y] ['id_pergunta']) {
						$tem = 1;
					}
				}

				if ($tem == 0) {
					$arr = [ 
						'id_pergunta' => $perguntas [$i] ['id'],
						'resposta' => ''
					];
					array_push( $respostas, $arr );
				}
			} else {
				$arr_2 = [ 
					'id_pergunta' => $perguntas [$i] ['id'],
					'resposta' => ''
				];
				array_push( $respostas, $arr_2 );
			}
		}
		$data_post ['respostas'] = $respostas;
		$formulario_service_response = (new ConsultaService())->registerConsulta( $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' => 'A consulta foi registrada 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 registerConsultaTelevet() {

        $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'];
        for($i = 0; $i < count( $perguntas ); $i++) {
            if (count( $respostas ) > 0) {
                $tem = 0;
                for($y = 0; $y < count( $respostas ); $y++) {
                    if ($perguntas [$i] ['id'] == $respostas [$y] ['id_pergunta']) {
                        $tem = 1;
                    }
                }

                if ($tem == 0) {
                    $arr = [
                        'id_pergunta' => $perguntas [$i] ['id'],
                        'resposta' => ''
                    ];
                    array_push( $respostas, $arr );
                }
            } else {
                $arr_2 = [
                    'id_pergunta' => $perguntas [$i] ['id'],
                    'resposta' => ''
                ];
                array_push( $respostas, $arr_2 );
            }
        }
        $data_post ['respostas'] = $respostas;
        $formulario_service_response = (new ConsultaService())->registerConsulta( $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' => 'A consulta foi registrada 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 registerConsultaRequisicao() {

		$data_post = $this->getDataPost();
		$validation_errors = ConsultaValidation::validateRegisterRequisicaoPost( $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 ConsultaService())->registerConsultaRequisicao( $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' => 'A consulta foi registrada 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 registerConsultaMultipleRequisicao() {

        $data_post = $this->getDataPost();
        $validation_errors = ConsultaValidation::validateRegisterMultipleRequisicaoPost( $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 ConsultaService())->registerConsultaMultipleRequisicao( $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' => 'A consulta foi registrada 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 updateConsulta(int $id_consulta): Response {

		$data_post = $this->getDataPost();

		if (isset( $data_post ["id_agendamento"] )) {
			$data_post ["id_agendamento"] = ( int ) $data_post ["id_agendamento"];
		}

		if (isset( $data_post ["id_formulario"] )) {
			$data_post ["id_formulario"] = ( int ) $data_post ["id_formulario"];
		}

		$validation_errors = ConsultaValidation::validateRegisterUpdate( $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 ConsultaService())->updateConsultaData( $id_consulta, $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 consulta 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( $formulario_service_response, $response_messages );

	}

	# Novo ENDPOINT
	public function getConsultaPacienteByMedicoID(int $id_paciente): Response {

		$pagination = $this->getPaginationFromRequest();
		if ($_GET ['sort'] === null) {
			$_GET ['sort'] = "data_nascimento";
		}
		$profileId = UsuarioLogado::getProfileId();
		$filters = $_GET;
		if ($profileId === 4) // cliente
		{
			$filters ['id_usuario'] = UsuarioLogado::getUsuarioId();
		} else {
			unset( $filters ['id_usuario'] );
		}

		$query_filter_collection = new QueryFilterCollection( $filters, QueryFilterTranslator::pet() );
		$query_order_collection = new QueryOrderCollection( $_GET, QueryOrderTranslator::pet() );
		$formulario_service_response = (new PetService())->getPetList( $pagination, $query_filter_collection, $query_order_collection );

		$response_messages = [ 
			ServiceResponseInterface::SUCESS => [ 
				'code' => ResponseInterface::HTTP_OK,
				'message' => 'Os dados da consulta 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 getConsultaByPacienteID(int $id_paciente): Response {

		$pagination = $this->getPaginationFromRequest();
		$query_filter_collection = new QueryFilterCollection( $_GET, QueryFilterTranslator::formulario() );
		$query_order_collection = new QueryOrderCollection( $_GET, QueryOrderTranslator::formulario() );
		$formulario_service_response = (new ConsultaService())->getConsultaList( $id_paciente, $pagination, $query_filter_collection, $query_order_collection );
		$response_messages = [ 
			ServiceResponseInterface::SUCESS => [ 
				'code' => ResponseInterface::HTTP_OK,
				'message' => 'Os dados da consulta 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 getMinhasConsultas(int $id_paciente): Response {

		$pagination = $this->getPaginationFromRequest();
		$query_filter_collection = new QueryFilterCollection( $_GET, QueryFilterTranslator::formulario() );
		$query_order_collection = new QueryOrderCollection( $_GET, QueryOrderTranslator::formulario() );
		$formulario_service_response = (new ConsultaService())->getMinhasConsultasList( $id_paciente, $pagination, $query_filter_collection,
			$query_order_collection );
		$response_messages = [ 
			ServiceResponseInterface::SUCESS => [ 
				'code' => ResponseInterface::HTTP_OK,
				'message' => 'Os dados da consulta 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 getMinhasConsultasTelevet(int $id_paciente): Response {

        $pagination = $this->getPaginationFromRequest();
        $query_filter_collection = new QueryFilterCollection( $_GET, QueryFilterTranslator::formulario() );
        $query_order_collection = new QueryOrderCollection( $_GET, QueryOrderTranslator::formulario() );
        $formulario_service_response = (new ConsultaService())->getMinhasConsultasListTelevet( $id_paciente, $pagination, $query_filter_collection,
            $query_order_collection );
        $response_messages = [
            ServiceResponseInterface::SUCESS => [
                'code' => ResponseInterface::HTTP_OK,
                'message' => 'Os dados da consulta 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 getConsultaByPetID(int $id_pet): Response {

		$pagination = $this->getPaginationFromRequest();
		$query_filter_collection = new QueryFilterCollection( $_GET, QueryFilterTranslator::formulario() );
		$query_order_collection = new QueryOrderCollection( $_GET, QueryOrderTranslator::formulario() );
		$formulario_service_response = (new ConsultaService())->getConsultaListByPet( $id_pet, $pagination, $query_filter_collection, $query_order_collection );
		$response_messages = [ 
			ServiceResponseInterface::SUCESS => [ 
				'code' => ResponseInterface::HTTP_OK,
				'message' => 'Os dados da consulta 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 getConsultaByPetIDByUnidadeID(int $idPet, int $idUnidade): Response {
		
		$pagination = $this->getPaginationFromRequest();
		$query_filter_collection = new QueryFilterCollection( $_GET, QueryFilterTranslator::formulario() );
		$query_order_collection = new QueryOrderCollection( $_GET, QueryOrderTranslator::formulario() );
		$formulario_service_response = (new ConsultaService())->getConsultaListByPetIDByUnidadeID( $idPet, $idUnidade, $pagination, $query_filter_collection, $query_order_collection );
		$response_messages = [
				ServiceResponseInterface::SUCESS => [
						'code' => ResponseInterface::HTTP_OK,
						'message' => 'Os dados da consulta 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 getConsultaByID(int $id_consulta): Response {

		$formulario_service_response = (new ConsultaService())->getConsultaByID( $id_consulta );
		$response_messages = [ 
			ServiceResponseInterface::SUCESS => [ 
				'code' => ResponseInterface::HTTP_OK,
				'message' => 'Os dados do consulta 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 );

	}

}