<?php

namespace App\Services;

use App\DAO\AgendaEspecialidadeDAO;
use App\DAO\DAOResponse\DAOResponseInterface;
use App\DAO\Pagination\Pagination;
use App\Entities\AgendaEspecialidade\AgendaEspecialidade;
use App\Mappers\AgendaEspecialidadeDisponibilidadeMapper;
use App\Mappers\AgendaEspecialidadeMapper;
use App\Services\ServiceResponse\ServiceResponse;
use App\Services\ServiceResponse\ServiceResponseInterface;
use App\Utils\DateUtils;
use App\Utils\ResponseException;
use App\Utils\Collections\GeneralCollection;
use App\Utils\Collections\QueryFilterCollection;
use App\Utils\Collections\QueryOrderCollection;
use App\ViewModels\AgendaEspecialidade\AgendaEspecialidadeMultipleRegistrationViewModel\AgendaEspecialidadeMultipleRegistrationViewModel;
use App\ViewModels\AgendaEspecialidade\AgendaEspecialidadeRegistrationViewModel\AgendaEspecialidadeRegistrationViewModel;
use App\DAO\AgendaEspecialidadeDisponibilidadeDAO;

class AgendaEspecialidadeService extends Service
{

    public function registerAgendaEspecialidade(array $agenda_array): ServiceResponse
    {

        try {
            $agenda_registration_vm = AgendaEspecialidadeMapper::getAgendaEspecialidadeRegistrationVMFromArray($agenda_array);
        } catch (ResponseException $exception) {
            return ServiceResponse::builder()->setStatus(ServiceResponseInterface::VALIDATION_PARAMS_ERROR)
                ->setErrors($exception->getData())
                ->build();
        }
        $agenda_dao = new AgendaEspecialidadeDAO();
        $schedules_conflicts = $this->getSchedulesConflicts($agenda_dao, $agenda_registration_vm);
        if ($schedules_conflicts->length > 0) {
            $service_response = ServiceResponse::builder()->setStatus(ServiceResponseInterface::HAVE_CONFLICTS)
                ->setErrors([
                    'conflitos' => $schedules_conflicts->toArray()
                ])
                ->build();
        } else {
            $dao_response = $agenda_dao->persistAgendaEspecialidadeRegistrationVM($agenda_registration_vm);
            $service_response = new ServiceResponse();
            switch ($dao_response->getStatus()) {
                case DAOResponseInterface::SUCESS :
                    $service_response->setStatus(ServiceResponseInterface::SUCESS);
                    $service_response->setData($this->getRegisterAgendaEspecialidadeDataResponse($dao_response->getData()));
                    break;
                case DAOResponseInterface::FOREIGN_KEY_DONT_EXISTS :
                    $service_response->setStatus(ServiceResponseInterface::VALIDATION_PARAMS_ERROR);
                    $service_response->setErrors($dao_response->getErrors());
                    break;
                case DAOResponseInterface::DUPLICATED_UNIQUE_KEY :
                    $service_response->setStatus(ServiceResponseInterface::VALIDATION_PARAMS_ERROR);
                    $service_response->setErrors($dao_response->getErrors());
                    break;
                default :
                    $service_response->setStatus(ServiceResponseInterface::DATABASE_CONNECTION_ERROR);
                    break;
            }
        }
        return $service_response;

    }

    public function registerAgendaEspecialidadeDisponibilidade($request): ServiceResponse
    {

        $agenda_reg_base = AgendaEspecialidadeDisponibilidadeMapper::getAgendaEspecialidadeRegistrationVMFromArray($request);

        $dao = new AgendaEspecialidadeDisponibilidadeDAO();
        $agenda_datas_response = $dao->getDatasToRegister($agenda_reg_base);

        if ($agenda_datas_response->getStatus() == DAOResponseInterface::SUCESS) {
            $resultado = $agenda_datas_response->getData();
            $lista = [];
            for ($i = 0; $i < count($resultado); $i++) {
                $item = $resultado [$i];
                $obj = AgendaEspecialidadeDisponibilidadeMapper::getAgendaEspecialidadeRegistrationVMFromArray($request);
                $crc = $obj->getIdUnidade() . "-" . $obj->getIdEspecialidade() . "-" . $item ['data'];
                $obj->setCrc($crc);
                $obj->setDataDisponibilidade($item ['data']);
                array_push($lista, $obj);
            }

            $daoResponse = $dao->registerAgendaEspecialidadeDisponibilidade($lista);
            $service_response = new ServiceResponse();
            $service_response = $this->setServiceResponse($daoResponse);
        }

        return $service_response;

    }

    public function getAgendaEspecialidadeDisponibilidade(int $idUnidade, int $idEspecialidade, int $dataInicial, int $dataFinal): ServiceResponse
    {

        if ($dataInicial > $dataFinal) {
            $temp = $dataFinal;
            $dataFinal = $dataInicial;
            $dataInicial = $temp;
        }

        $dt_ini = DateUtils::requestInt_to_date($dataInicial);
        $dt_fim = DateUtils::requestInt_to_date($dataFinal);

        $service_response = new ServiceResponse();
        $agenda_dao = new AgendaEspecialidadeDisponibilidadeDAO();
        $daoResponse = $agenda_dao->getAgendaEspecialidadeDisponibilidade($idUnidade, $idEspecialidade, $dt_ini, $dt_fim);
        $service_response = $this->setServiceResponse($daoResponse);
        return $service_response;

    }

    public function updateAgendaEspecialidadeDisponibilidade(array $request): ServiceResponse
    {

        $idAgenda = $request ['id_agenda'];
        $ativo = $request ['ativo'];

        $service_response = new ServiceResponse();
        $agenda_dao = new AgendaEspecialidadeDisponibilidadeDAO();
        $daoResponse = $agenda_dao->updateAgendaEspecialidadeDisponibilidade($idAgenda, $ativo);
        $service_response = $this->setServiceResponse($daoResponse);
        return $service_response;

    }

    public function deleteAgendaEspecialidade(int $id_agenda)
    {

        $agenda_dao = new AgendaEspecialidadeDAO();
        $dao_response = $agenda_dao->deleteAgendaEspecialidade($id_agenda);
        $service_response_status = [
            DAOResponseInterface::RESTRICT_FK_UPDATE_OR_DELETION => ServiceResponseInterface::RECORD_IS_LINKED,
            DAOResponseInterface::SUCESS => ServiceResponseInterface::SUCESS,
            DAOResponseInterface::RECORD_NOT_FOUND => ServiceResponseInterface::RECORD_NOT_FOUND
        ] [$dao_response->getStatus()];
        $service_response = ServiceResponse::builder()->setStatus($service_response_status)
            ->build();
        return $service_response;

    }

    private function getRegisterAgendaEspecialidadeDataResponse(AgendaEspecialidade $agenda): array
    {

        return [
            'id_agenda' => $agenda->getId()
        ];

    }

    private function getSchedulesConflicts(AgendaEspecialidadeDAO $agenda_dao, AgendaEspecialidadeRegistrationViewModel $agenda_registration_vm): GeneralCollection
    {

        $dao_response = $agenda_dao->getAgendaEspecialidadeConflicts($agenda_registration_vm);
        if ($dao_response->getStatus() === DAOResponseInterface::SUCESS) {
            return $dao_response->getData();
        } else {
            return new GeneralCollection();
        }

    }

    public function getAgendaEspecialidadeListByMedicoID(QueryFilterCollection $query_filter_collection, ?Pagination $pagination,
                                                         QueryOrderCollection  $query_order_collection): ServiceResponse
    {

        $agenda_dao = new AgendaEspecialidadeDAO();
        // $query_filter_collection->push(QueryFilter::builder()
        // ->setTable('agenda')
        // ->setNameParam('id_MEDICO')
        // ->setValue($medico_id)
        // ->setIsExact(true)
        // ->build()
        // );
        $dao_response = $agenda_dao->getAgendaEspecialidadeList($query_filter_collection, $query_order_collection, $pagination);
        switch ($dao_response->getStatus()) {
            case DAOResponseInterface::SUCESS :
                $service_response_status = ServiceResponseInterface::SUCESS;
                break;
            case DAOResponseInterface::RECORD_NOT_FOUND :
                $service_response_status = ServiceResponseInterface::RECORD_NOT_FOUND;
                break;
            default :
                $service_response_status = ServiceResponseInterface::DATABASE_CONNECTION_ERROR;
                break;
        }
        $service_response = ServiceResponse::builder()->setStatus($service_response_status)
            ->build();
        if ($service_response_status === DAOResponseInterface::SUCESS) {
            $dao_response_data = $dao_response->getData();
            $agenda_details_array = AgendaEspecialidadeMapper::getAgendaEspecialidadeListingArrayFromAgendaEspecialidadeListingVMCollection($dao_response_data);
            $pagination = $dao_response->getPagination();
            $data = [
                'agendas' => $agenda_details_array,
                'pagination' => $pagination ? $pagination->toResponseArray() : null
            ];
            $service_response->setData($data);
        }
        return $service_response;

    }

    public function registerMultipleAgendaEspecialidade(array $agenda_array): ServiceResponse
    {

        try {
            $agenda_multiple_registration_vm = AgendaEspecialidadeMapper::getAgendaEspecialidadeMultipleRegistrationVMFromArray($agenda_array);
        } catch (ResponseException $exception) {
            return ServiceResponse::builder()->setErrors($exception->getData())
                ->setStatus(ServiceResponseInterface::VALIDATION_PARAMS_ERROR)
                ->build();
        }
        $daily_schedules_collection = AgendaEspecialidadeMapper::getDailySchedulesByAgendaEspecialidadeMultipleRegistrationVM($agenda_multiple_registration_vm);
        $service_dates_collection = AgendaEspecialidadeMapper::getServiceDatesCollectionByAgendaEspecialidadeMultipleRegistrationVM(
            $agenda_multiple_registration_vm);
        $agenda_dao = new AgendaEspecialidadeDAO();
        $potential_conflicts = $this->getMultipleRegisterAgendaEspecialidadeConflictsCollection($agenda_dao, $agenda_multiple_registration_vm,
            $service_dates_collection);
        $conflicts = new GeneralCollection();
        $agenda_collection = AgendaEspecialidadeMapper::getAgendaEspecialidadeCollectionBySchedulesAndDates($agenda_multiple_registration_vm,
            $daily_schedules_collection, $service_dates_collection, $potential_conflicts, $conflicts);
        if ($agenda_collection->length > 0) {
            $dao_response = $agenda_dao->persistAgendaEspecialidadeCollection($agenda_collection, $agenda_multiple_registration_vm->getEncaixe());
            $dao_response_status = $dao_response->getStatus();
            $service_response = new ServiceResponse();
            if (in_array($dao_response_status, [
                DAOResponseInterface::FOREIGN_KEY_DONT_EXISTS,
                DAOResponseInterface::DUPLICATED_UNIQUE_KEY
            ])) {
                $service_response->setStatus(ServiceResponseInterface::VALIDATION_PARAMS_ERROR);
                $service_response->setErrors($dao_response->getErrors());
            } else if ($dao_response_status === DAOResponseInterface::SUCESS) {
                if ($conflicts->length) {
                    $service_response->setStatus(ServiceResponseInterface::PARTIAL_SUCESS);
                    $service_response->setErrors([
                        'conflitos' => $conflicts->toArray()
                    ]);
                } else {
                    $service_response->setStatus(ServiceResponseInterface::SUCESS);
                }
            } else {
                $service_response->setStatus(ServiceResponseInterface::DATABASE_CONNECTION_ERROR);
            }
            return $service_response;
        } else {
            return ServiceResponse::builder()->setStatus(ServiceResponseInterface::HAVE_CONFLICTS)
                ->setErrors([
                    'conflitos' => $conflicts->toArray()
                ])
                ->build();
        }

    }

    private function getMultipleRegisterAgendaEspecialidadeConflictsCollection(AgendaEspecialidadeDAO                           $agenda_dao,
                                                                               AgendaEspecialidadeMultipleRegistrationViewModel $agenda_multiple_registration_vm, GeneralCollection $service_dates_collection): GeneralCollection
    {

        $dao_response = $agenda_dao->getAgendaEspecialidadeConflictsForMultipleRegistration($agenda_multiple_registration_vm, $service_dates_collection);
        return $dao_response->getStatus() === DAOResponseInterface::SUCESS ? $dao_response->getData() : new GeneralCollection();

    }

    public function updateAgendaEspecialidade(int $id_agenda, array $data): ServiceResponse
    {

        $agenda_update_vm = AgendaEspecialidadeMapper::getAgendaEspecialidadeUpdateVMFromArray($data);
        $agenda_dao = new AgendaEspecialidadeDAO();
        $dao_response = $agenda_dao->updateAgendaEspecialidade($id_agenda, $agenda_update_vm);
        $service_response = new ServiceResponse();
        $response_status = [
            DAOResponseInterface::SUCESS => ServiceResponseInterface::SUCESS,
            DAOResponseInterface::RECORD_NOT_FOUND => ServiceResponseInterface::RECORD_NOT_FOUND,
            DAOResponseInterface::DATABASE_CONNECTION_ERROR => ServiceResponseInterface::DATABASE_CONNECTION_ERROR,
            DAOResponseInterface::FOREIGN_KEY_DONT_EXISTS => ServiceResponseInterface::VALIDATION_PARAMS_ERROR
        ] [$dao_response->getStatus()];
        if (!$response_status) {
            (new LogService())->log_error($response_status, "Ocorreu um erro desconhecido durante a atualização da agenda", []);
            $response_status = ServiceResponseInterface::DATABASE_CONNECTION_ERROR;
        } else if ($response_status !== ServiceResponseInterface::SUCESS) {
            $service_response->setErrors($dao_response->getErrors());
        }
        $service_response->setStatus($response_status);
        return $service_response;

    }

    public function getAgendaUnidadeByEspecialidade(int $especialidade, int $unidade, int $data_inical, int $data_final, Pagination $pagination): ServiceResponse
    {

        if ($data_inical <= $data_final) {
            $data_inicio = DateUtils::requestInt_to_date($data_inical);
            $data_fim = DateUtils::requestInt_to_date($data_final);
        } else {
            $data_inicio = DateUtils::requestInt_to_date($data_final);
            $data_fim = DateUtils::requestInt_to_date($data_inical);
        }

        $dao = new AgendaEspecialidadeDAO();

        $dao_response = $dao->getAgendaUnidadeByEspecialidade($especialidade, $unidade, $data_inicio, $data_fim, $pagination);
        $service_response = new ServiceResponse();
        switch ($dao_response->getStatus()) {
            case DAOResponseInterface::SUCESS :
                $service_response->setStatus(ServiceResponseInterface::SUCESS);
                $service_response->setData($dao_response->getData());
                break;
            case DAOResponseInterface::FOREIGN_KEY_DONT_EXISTS :
                $service_response->setStatus(ServiceResponseInterface::VALIDATION_PARAMS_ERROR);
                $service_response->setErrors($dao_response->getErrors());
                break;
            case DAOResponseInterface::DUPLICATED_UNIQUE_KEY :
                $service_response->setStatus(ServiceResponseInterface::VALIDATION_PARAMS_ERROR);
                $service_response->setErrors($dao_response->getErrors());
                break;
            default :
                $service_response->setStatus(ServiceResponseInterface::DATABASE_CONNECTION_ERROR);
                break;
        }

        return $service_response;

    }

    public function getAgendaEspecialidadeByUnidadeByPeriodo(int $unidade, int $especialidade, string $data): ServiceResponse
    {

        $dao = new AgendaEspecialidadeDAO();
        $dao_response = $dao->getAgendaEspecialidadeByUnidadeByPeriodo($unidade, $especialidade, $data);
        $service_response = new ServiceResponse();
        switch ($dao_response->getStatus()) {
            case DAOResponseInterface::SUCESS :
                $service_response->setStatus(ServiceResponseInterface::SUCESS);
                $service_response->setData($dao_response->getData());
                break;
            case DAOResponseInterface::FOREIGN_KEY_DONT_EXISTS :
                $service_response->setStatus(ServiceResponseInterface::VALIDATION_PARAMS_ERROR);
                $service_response->setErrors($dao_response->getErrors());
                break;
            case DAOResponseInterface::DUPLICATED_UNIQUE_KEY :
                $service_response->setStatus(ServiceResponseInterface::VALIDATION_PARAMS_ERROR);
                $service_response->setErrors($dao_response->getErrors());
                break;
            default :
                $service_response->setStatus(ServiceResponseInterface::DATABASE_CONNECTION_ERROR);
                break;
        }

        return $service_response;

    }

    public function registerNewAgendamentoEspecialidadeByRecepcao(int $idAgenda, int $idProcedimento, int $idPet, int $idStatus, string $idObservacao): ServiceResponse
    {

        $dao = new AgendaEspecialidadeDAO();
        $dao_response = $dao->registerNewAgendamentoEspecialidadeByRecepcao($idAgenda, $idProcedimento, $idPet, $idStatus, $idObservacao);
        $service_response = new ServiceResponse();

        switch ($dao_response->getStatus()) {
            case DAOResponseInterface::SUCESS :
                $service_response->setStatus(ServiceResponseInterface::SUCESS);
                $service_response->setData($dao_response->getData());
                break;
            case DAOResponseInterface::FOREIGN_KEY_DONT_EXISTS :
                $service_response->setStatus(ServiceResponseInterface::VALIDATION_PARAMS_ERROR);
                $service_response->setErrors($dao_response->getErrors());
                break;
            case DAOResponseInterface::DUPLICATED_UNIQUE_KEY :
                $service_response->setStatus(ServiceResponseInterface::VALIDATION_PARAMS_ERROR);
                $service_response->setErrors($dao_response->getErrors());
                break;
            default :
                $service_response->setStatus(ServiceResponseInterface::DATABASE_CONNECTION_ERROR);
                break;
        }

        return $service_response;

    }

    public function updateStatusAgendamentoEspecialidade(int $idAgenda, int $idStatus, string $observacao): ServiceResponse
    {

        $dao = new AgendaEspecialidadeDAO();
        $dao_response = $dao->updateStatusAgendamentoEspecialidade($idAgenda, $idStatus, $observacao);
        $service_response = new ServiceResponse();

        switch ($dao_response->getStatus()) {
            case DAOResponseInterface::SUCESS :
                $service_response->setStatus(ServiceResponseInterface::SUCESS);
                break;
            case DAOResponseInterface::RECORD_NOT_FOUND :
                $service_response->setStatus(ServiceResponseInterface::RECORD_NOT_FOUND);
                break;
            case DAOResponseInterface::FOREIGN_KEY_DONT_EXISTS :
                $service_response->setStatus(ServiceResponseInterface::VALIDATION_PARAMS_ERROR);
                $service_response->setErrors($dao_response->getErrors());
                break;
            case DAOResponseInterface::DUPLICATED_UNIQUE_KEY :
                $service_response->setStatus(ServiceResponseInterface::VALIDATION_PARAMS_ERROR);
                $service_response->setErrors($dao_response->getErrors());
                break;
            default :
                $service_response->setStatus(ServiceResponseInterface::DATABASE_CONNECTION_ERROR);
                break;
        }

        return $service_response;

    }


    public function reagendarAgendamentoEspecialidadeByRecepcao(int $idAgendaAntiga, int $idAgendaNova): ServiceResponse
    {

        $dao = new AgendaEspecialidadeDAO();
        $dao_response = $dao->reagendarAgendamentoEspecialidadeByRecepcao($idAgendaAntiga, $idAgendaNova);
        $service_response = new ServiceResponse();

        switch ($dao_response->getStatus()) {
            case DAOResponseInterface::SUCESS :
                $service_response->setStatus(ServiceResponseInterface::SUCESS);
                $service_response->setData($dao_response->getData());
                break;
            case DAOResponseInterface::FOREIGN_KEY_DONT_EXISTS :
                $service_response->setStatus(ServiceResponseInterface::VALIDATION_PARAMS_ERROR);
                $service_response->setErrors($dao_response->getErrors());
                break;
            case DAOResponseInterface::DUPLICATED_UNIQUE_KEY :
                $service_response->setStatus(ServiceResponseInterface::VALIDATION_PARAMS_ERROR);
                $service_response->setErrors($dao_response->getErrors());
                break;
            default :
                $service_response->setStatus(ServiceResponseInterface::DATABASE_CONNECTION_ERROR);
                break;
        }

        return $service_response;

    }

    public function getAgendaByDate(?Pagination $pagination, ?QueryFilterCollection $query_filter_collection,
                                    ?QueryOrderCollection $query_order_collection, $id_procedimento, $data_agenda, $id_unidade): ServiceResponse
    {
        $agenda_dao = new AgendaEspecialidadeDAO();
        $dao_response = $agenda_dao->getAgendaDateList($pagination, $query_filter_collection, $query_order_collection, $id_procedimento, $data_agenda, $id_unidade);
        switch ($dao_response->getStatus()) {
            case DAOResponseInterface::SUCESS:
                $service_response_status = ServiceResponseInterface::SUCESS;
                break;
            case DAOResponseInterface::RECORD_NOT_FOUND:
                $service_response_status = ServiceResponseInterface::RECORD_NOT_FOUND;
                break;
            case DAOResponseInterface::DATABASE_CONNECTION_ERROR:
                $service_response_status = ServiceResponseInterface::DATABASE_CONNECTION_ERROR;
                break;
        }
        $service_response = ServiceResponse::builder()
            ->setStatus($service_response_status)
            ->build();
        if ($service_response_status === DAOResponseInterface::SUCESS) {
            $dao_response_data = $dao_response->getData();
            $agenda_details_array = AgendaEspecialidadeMapper::getAgendaDateArrayFromAgendaVMCollection($dao_response_data);
            $pagination = $dao_response->getPagination();
            $data = [
                'agendas' => $agenda_details_array,
                'pagination' => $pagination ? $pagination->toResponseArray() : null
            ];
            $service_response->setData($data);
        }
        return $service_response;
    }
}
