<?php

namespace App\Controllers;

use App\DAO\Filter\QueryFilter;
use App\DAO\Filter\QueryFilterTranslator;
use App\DAO\Order\QueryOrderTranslator;
use App\DAO\SetorDAO;
use App\Services\SetorService;
use App\Services\ServiceResponse\ServiceResponseInterface;
use App\Utils\Collections\QueryFilterCollection;
use App\Utils\Collections\QueryOrderCollection;
use App\Validations\SetorValidation;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Model;

class SetorController extends BaseController {

	public function registerSetor(): Response {

		if (! $this->validate( SetorValidation::register() )) {
			return $this->response->setJSON( [
					'message' => 'Informe os dados corretamente.',
					'errors' => $this->validation->getErrors() ] );
		}
		$data_post = $_POST;
		$setor_service_response = (new SetorService())->registerSetor( $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 centro de custo foi cadastrado 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( $setor_service_response, $response_messages );

	}

	public function getSetorList(): Response {

		$pagination = $this->getPaginationFromRequest();

		if ($_GET ['sort'] === null) {
			$_GET ['sort'] = "descricao";
		}

		$query_filter_collection = new QueryFilterCollection( $_GET, QueryFilterTranslator::setor() );
		$query_order_collection = new QueryOrderCollection( $_GET, QueryOrderTranslator::setor() );
		$setor_service_response = (new SetorService())->getSetorList( $pagination, $query_filter_collection, $query_order_collection );
		$response_messages = [
				ServiceResponseInterface::SUCESS => [
						'code' => ResponseInterface::HTTP_OK,
						'message' => 'Os dados dos centros de custos 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( $setor_service_response, $response_messages );

	}

	public function searchSetorByID(int $id_setor): Response {
        $query_filter = QueryFilter::builder()
            ->setTable('setor')
            ->setNameParam('id')
            ->setValue($id_setor)
            ->setIsExact(true)
            ->build();

		$setor_service_response = (new SetorService())->getSetor( $query_filter );
		$response_messages = [
				ServiceResponseInterface::SUCESS => [
						'code' => ResponseInterface::HTTP_OK,
						'message' => 'Os dados do centro de custo 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( $setor_service_response, $response_messages );
	}

	public function updateSetor(int $id_setor): Response {

		if (! $this->validate( SetorValidation::update() )) {
			return $this->response->setJSON( [
					'message' => 'Informe os dados corretamente.',
					'errors' => $this->validation->getErrors() ] );
		}

		$setor_dao = new SetorDAO();
		$validation = $setor_dao->getSetorFromId( $id_setor );

		if ($validation == null) {
			return $this->response->setJSON( [
					'message' => 'O centro de custo não está registrado.',
					'errors' => $this->validation->getErrors() ] );
		}

		$setor_service_response = (new SetorService())->updateSetorData( $id_setor, $_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 centro de custo 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( $setor_service_response, $response_messages );
	}

    public function deleteSetor(int $id_erro) {
        $erro_service_response = (new SetorService())->deleteSetor($id_erro);
        $response_messages = [
            ServiceResponseInterface::SUCESS => [
                'code' => ResponseInterface::HTTP_OK,
                'message' => 'A exclusão foi efetuda com sucesso.'
            ],
            ServiceResponseInterface::RECORD_NOT_FOUND => [
                'code' => ResponseInterface::HTTP_PARTIAL_CONTENT,
                'message' => 'Nenhum registro foi encontrado.'
            ],
            ServiceResponseInterface::RECORD_IS_LINKED => [
                'code' => ResponseInterface::HTTP_BAD_REQUEST,
                'message' => 'Esse exame está vinculado a outros cadastros do sistema. Portanto, não pode ser excluído.'
            ],
            ServiceResponseInterface::DATABASE_CONNECTION_ERROR => [
                'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
                'message' => 'Erro interno do servidor.'
            ],
        ];
        return $this->getResponse($erro_service_response, $response_messages);
    }
}
