<?php

namespace App\Controllers;

use App\DAO\PetDAO;
use App\DAO\Filter\QueryFilter;
use App\DAO\Filter\QueryFilterTranslator;
use App\DAO\Order\QueryOrderTranslator;
use App\Services\PetService;
use App\Services\ServiceResponse\ServiceResponseInterface;
use App\Utils\Collections\QueryFilterCollection;
use App\Utils\Collections\QueryOrderCollection;
use App\Validations\PetValidation;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Model;
use App\Services\JWT\UsuarioLogado;

class PetController extends BaseController {

	public function register(): Response {

		if (!$this->validate( PetValidation::register() )) {
			return $this->response->setJSON( [ 
				'message' => 'Informe os dados corretamente.',
				'errors' => $this->validation->getErrors()
			] );
		}
		$data_post = $_POST;
		$pet_service_response = (new PetService())->registerPet( $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 pet foi cadastrado com sucesso.'
			],
			ServiceResponseInterface::VALIDATION_PARAMS_ERROR => [ 
				'code' => ResponseInterface::HTTP_BAD_REQUEST,
				'message' => $pet_service_response->getErrors()
			],
			ServiceResponseInterface::FOREIGN_KEY_DONT_EXISTS => [ 
				'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( $pet_service_response, $response_messages );

	}

	public function getPetByID(int $id_pet): Response {

		$query_filter = QueryFilter::builder()->setNameParam( 'id' )
			->setTable( 'pet' )
			->setValue( $id_pet )
			->setIsExact( true )
			->build();
		$pet_service_response = (new PetService())->getPet( $query_filter );
		$response_messages = [ 
			ServiceResponseInterface::SUCESS => [ 
				'code' => ResponseInterface::HTTP_OK,
				'message' => 'Os dados do pet 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( $pet_service_response, $response_messages );

	}

	public function getPetByIDAndClient(int $id_pet): Response {

		// $query_filter = QueryFilter::builder()->setNameParam( 'id' )->setTable( 'pet' )->setValue( $id_pet )->setIsExact( true )->build();
		$pet_service_response = (new PetService())->getPetByClient( $id_pet );
		$response_messages = [ 
			ServiceResponseInterface::SUCESS => [ 
				'code' => ResponseInterface::HTTP_OK,
				'message' => 'Os dados do pet 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( $pet_service_response, $response_messages );

	}

	public function getPetList(): 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() );
		$pet_service_response = (new PetService())->getPetList( $pagination, $query_filter_collection, $query_order_collection );
		$response_messages = [ 
			ServiceResponseInterface::SUCESS => [ 
				'code' => ResponseInterface::HTTP_OK,
				'message' => 'Os dados do pet 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( $pet_service_response, $response_messages );

	}

	public function getPetListByTutorId(int $id_tutor): Response {

		$query_filter = QueryFilter::builder()->setNameParam( 'id_cliente' )
			->setTable( 'pet_cliente' )
			->setValue( $id_tutor )
			->setIsExact( true )
			->build();
		$query_filter_collection = new QueryFilterCollection();
		$query_filter_collection->push( $query_filter );
		$pet_service_response = (new PetService())->getPetListByTutorId( null, $query_filter_collection, null );
		$response_messages = [ 
			ServiceResponseInterface::SUCESS => [ 
				'code' => ResponseInterface::HTTP_OK,
				'message' => 'Os dados do pet 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( $pet_service_response, $response_messages );

	}

	public function updatePetData(int $id_pet): Response {

		if (!$this->validate( PetValidation::update( $id_pet ) )) {
			return $this->response->setJSON( [ 
				'message' => 'Informe os dados corretamente.',
				'errors' => $this->validation->getErrors()
			] );
		}
		$paciente_dao = new PetDAO();
		$validation = $paciente_dao->getPetFromId( $id_pet );
		if ($validation == null) {
			return $this->response->setJSON( [ 
				'message' => 'O pet não está registrado.',
				'errors' => $this->validation->getErrors()
			] );
		}
		$pet_service_response = (new PetService())->updatePetData( $id_pet, $_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 pet 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( $pet_service_response, $response_messages );

	}

	public function getDadosCartaoVoucherByPetId(int $id_pet): Response {

		$service = new PetService();

		$service_response = $service->getDadosCartaoVoucherByPetId( $id_pet );
		$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 pet 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( $service_response, $response_messages );

	}

}
