<?php

namespace App\Controllers;

use App\ChameFacil\AuthBaseServiceCF;
use App\Services\AuthService;
use App\Services\LogsysService;
use App\Services\ServiceResponse\ServiceResponse;
use App\Services\ServiceResponse\ServiceResponseInterface;
use App\Services\UnidadeService;
use App\Validations\AuthValidation;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;
use App\Services\LogService;

class AuthController extends BaseController {
	private $controller = 'AuthController';
	
	public function confirmEmailRegistration(string $token): Response {
		
		$auth_service = new AuthService();
		$auth_service_response = $auth_service->confirmEmail( $token );
		$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 email foi confirmado com sucesso.'
				],
				ServiceResponseInterface::RECORD_NOT_FOUND => [
						'code' => ResponseInterface::HTTP_BAD_REQUEST,
						'message' => 'Não foi encontrado nenhum email correspondente a esse token.'
				],
				ServiceResponseInterface::TOKEN_EXPIRED => [
						'code' => ResponseInterface::HTTP_BAD_REQUEST,
						'message' => 'O seu email de confirmação expirou.'
				],
				ServiceResponseInterface::SERVICE_INTERNAL_ERROR => [
						'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
						'message' => 'Erro interno do servidor.'
				]
		];
		return $this->getResponse( $auth_service_response, $response_messages );
	}
	
	public function authenticatePaciente() {
		
//		$params = [
//				'controller' => $this->controller,
//				'observacao' => 'login: ' . $_POST ['email'] . ' - Paciente ',
//				'id_usuario' => 0
//		];
		
		/**
		 * Gravção de Log
		 * */
		
//		$this->logsysService->register( $this->path_into, $this->request_method, $params );
		
		return $this->authenticateUser( function (string $email, string $senha): ServiceResponse {
			return (new AuthService())->authenticatePaciente( $_POST ['email'], $_POST ['senha'] );
		} );
	}
	
	public function authenticateMedico() {
		
//		$params = [
//				'controller' => $this->controller,
//				'observacao' => 'login: ' . $_POST ['email'] . ' - Medico ',
//				'id_usuario' => 0
//		];
		
		/**
		 * Gravção de Log
		 * */
		
//		$this->logsysService->register( $this->path_into, $this->request_method, $params );
		
		return $this->authenticateUser( function (string $email, string $senha): ServiceResponse {
			return (new AuthService())->authenticateMedico( $_POST ['email'], $_POST ['senha'] );
		} );
	}
	
	public function authenticateAssistente() {
		
//		$params = [
//				'controller' => $this->controller,
//				'observacao' => 'login: ' . $_POST ['email'] . ' - Assistente ',
//				'id_usuario' => 0
//		];
		
		/**
		 * Gravção de Log
		 * */
		
//		$this->logsysService->register( $this->path_into, $this->request_method, $params );
		
		return $this->authenticateUser( function (string $email, string $senha): ServiceResponse {
			return (new AuthService())->authenticateAssistente( $_POST ['email'], $_POST ['senha'] );
		} );
	}
	
	public function authenticateRecepcionista() {
		
//		$params = [
//				'controller' => $this->controller,
//				'observacao' => 'login: ' . $_POST ['email'] . ' - Recepcionista ',
//				'id_usuario' => 0
//		];
		
		/**
		 * Gravção de Log
		 * */
		
//		$this->logsysService->register( $this->path_into, $this->request_method, $params );
		
		return $this->authenticateUser( function (string $email, string $senha): ServiceResponse {
			return (new AuthService())->authenticateRecepcionista( $_POST ['email'], $_POST ['senha'] );
		} );
	}
	
	public function authenticateAdministrativo() {
		
//		$params = [
//				'controller' => $this->controller,
//				'observacao' => 'login: ' . $_POST ['email'] . ' - Administrativo ',
//				'id_usuario' => 0
//		];
		
		/**
		 * Gravção de Log
		 * */
		
//		$this->logsysService->register( $this->path_into, $this->request_method, $params );
		
		return $this->authenticateUser( function (string $email, string $senha): ServiceResponse {
			return (new AuthService())->authenticateAdministrativo( $_POST ['email'], $_POST ['senha'] );
		} );
	}
	
	private function authenticateUser(callable $authenticate) {
		
		if (! $this->validate( AuthValidation::auth() )) {
			return $this->response->setJSON( [
					'message' => 'Informe os dados corretamente.',
					'errors' => $this->validation->getErrors()
			] );
		}
		
		$auth_service_response = (function (ServiceResponse $service_response): ServiceResponse {
			return $service_response;
		})( $authenticate( $_POST ['email'], $_POST ['senha'] ) );
		
		if ($auth_service_response->getStatus() == 1) {
			$data = $auth_service_response->getData();
			$response_auth_cf = null;
			if ($data ['id_perfil'] != 4) {
				$unidade_service_response = (new UnidadeService())->getUnidadeListByUsuario( null, null, null, $data ['id_usuario'] );
				$auth_chame_facil = new AuthBaseServiceCF();
				$response_auth_cf = $auth_chame_facil->authUserService( $_POST ['email'], $_POST ['senha'] );
			} else {
				$unidade_service_response = (new UnidadeService())->getUnidadeList( null, null, null );
			}
			
			if ($response_auth_cf->Token) {
				$data = array_merge( $data, [
						'token_chamefacil' => $response_auth_cf->Token
				] );
			}

            // Gravação do LogSys
            $params = [
                'controller' => $this->controller,
                'observacao' => 'login: ' . $_POST ['email'] . ' - '.$data['descricao'],
                'id_usuario' => $data['id_usuario']
            ];

            $this->logsysService->register( $this->path_into, $this->request_method, $params );
			
			$data = array_merge( $data, $unidade_service_response->getData() );
			$auth_service_response->setData( $data );
		}
		
		$response_messages = [
				ServiceResponseInterface::EMAIL_NOT_VERIFIED => [
						'code' => ResponseInterface::HTTP_UNAUTHORIZED,
						'message' => 'Confirme o seu email.'
				],
				ServiceResponseInterface::UNAUTHORIZED => [
						'code' => ResponseInterface::HTTP_UNAUTHORIZED,
						'message' => 'Acesso não permitido.'
				],
				ServiceResponseInterface::SUCESS => [
						'code' => ResponseInterface::HTTP_OK,
						'message' => 'Acesso permitido.'
				],
				ServiceResponseInterface::DATABASE_CONNECTION_ERROR => [
						'code' => ResponseInterface::HTTP_BAD_REQUEST,
						'message' => 'Erro interno do servidor. Tente novamente dentro de alguns minutos. Se o serviço continuar sem funcionar, contate o administrador do sistema.'
				]
		];
		return $this->getResponse( $auth_service_response, $response_messages );
	}
}
