<?php


namespace App\DAO;



use App\DAO\DAOResponse\DAOResponse;
use App\DAO\DAOResponse\DAOResponseInterface;
use App\DAO\Pagination\Pagination;
use App\Entities\Medicamento\Medicamento;
use App\Mappers\MedicamentoMapper;
use App\Models\MedicamentoModel;
use App\Services\LogService;
use App\Utils\Collections\QueryFilterCollection;
use App\Utils\Collections\QueryOrderCollection;
use App\ViewModels\Medicamento\MedicamentoRegistrationViewModel\MedicamentoRegistrationViewModel;
use App\ViewModels\Medicamento\MedicamentoUpdateViewModel\MedicamentoUpdateViewModel;
use Exception;

class MedicamentoDAO extends DAO
{
    public function persistMedicamentoRegistrationVM (MedicamentoRegistrationViewModel $exame_registration_vm) : DAOResponse {
        $dao_response = new DAOResponse();
        try {
            $exame = $this->persistMedicamento($exame_registration_vm);
            $error = $this->db->error();
            if ($error && $error['code']) {
                $status_persistence = $error['code'];
                $dao_response_errors = [];
//                if (strpos($error['message'],'PROCEDIMENTO.descricao') !== false) {
//                    $dao_response_errors['descricao'] = 'Esse procedimento já existe';
//                }
                $dao_response->setErrors($dao_response_errors);
                log_message('error', json_encode($error));
            } else {
                $status_persistence = !!$exame->getId()
                    ? DAOResponseInterface::SUCESS
                    : DAOResponseInterface::DATABASE_CONNECTION_ERROR;
            }
        } catch (Exception $exception) {
            log_message('error', json_encode($this->db->error()));
            $status_persistence = DAOResponseInterface::DATABASE_CONNECTION_ERROR;
            $exame = null;
        }
        $this->db->close();
        $dao_response->setStatus($status_persistence);
        if ($status_persistence === DAOResponseInterface::SUCESS) {
            $dao_response->setData($exame);
        }
        return $dao_response;
    }

    private function persistMedicamento (MedicamentoRegistrationViewModel $exame_registration_vm) : Medicamento {
        $exame_model = new MedicamentoModel();
        $exame = MedicamentoMapper::getMedicamentoFromMedicamentoRegistrationVM($exame_registration_vm);
        $exame_model->registerMedicamento($exame);
        return $exame;
    }

    public function getMedicamentoList (?Pagination $pagination, ?QueryFilterCollection $query_filter_collection, ?QueryOrderCollection $query_order_collection = null) : DAOResponse {
        $sql = '
            SELECT
                medicamento.id AS id,
                medicamento.nome AS nome,
                medicamento.quantidade AS quantidade,
                medicamento.posologia AS posologia,
                medicamento.id_clinica AS id_clinica
            FROM
                medicamento
        ';
        return $this->getDAOResponseFromPaginatedSelect([], $pagination, $query_filter_collection, $query_order_collection, $sql, function (array $result_array) {
            return MedicamentoMapper::getMedicamentoDetailsVMCollectionFromArray($result_array);
        });
    }

    public function deleteMedicamento (int $id_procedimento) : DAOResponse {
        $exame_model = new MedicamentoModel ();
        $dao_response = $this->getDAOResponseForDeletion($exame_model, $id_procedimento);
        return $dao_response;
    }

    public function getMedicamento (QueryFilterCollection $query_filter_collection) : DAOResponse {
        $sql = '
            SELECT
                medicamento.id AS id,
                medicamento.nome AS nome,
                medicamento.quantidade AS quantidade,
                medicamento.posologia AS posologia,
                medicamento.id_clinica AS id_clinica
            FROM
                medicamento
        ';
        $binds = [];
        return $this->getDAOResponseFromUniqueRowSelect($binds, $query_filter_collection, $sql, function (array $result_array) {
            return MedicamentoMapper::getMedicamentoDetailsVMFromArray($result_array[0]);
        });
    }

    public function persistMedicamentoUpdateVM (int $id_procedimento, MedicamentoUpdateViewModel $exame_update_vm) : DAOResponse {
        $status_persistence = $this->persistMedicamentoFromMedicamentoUpdateVM($id_procedimento, $exame_update_vm);
        $error = $this->db->error();
        $this->db->close();
        $dao_response = new DAOResponse;
        if ($error && $error['code']) {
            $status_response = $error['code'];
            $dao_response_errors = [];
            $dao_response->setErrors($dao_response_errors);
            (new LogService)->log_error($status_response, "Ocorreu um erro durante a atualização do procedimento $id_procedimento", $exame_update_vm->toArray());
        } else {
            $status_response = $status_persistence ? DAOResponseInterface::SUCESS :  DAOResponseInterface::RECORD_NOT_FOUND;
        }
        $dao_response->setStatus($status_response);
        return $dao_response;
    }

    private function persistMedicamentoFromMedicamentoUpdateVM (int $id_procedimento, MedicamentoUpdateViewModel $exame_update_vm) : bool {
        $exame_model = new MedicamentoModel();
        $exame = MedicamentoMapper::getMedicamentoFromMedicamentoUpdateVM($exame_update_vm);
        $sucess_update = $exame_model->updateMedicamentoByID($id_procedimento, $exame);
        return $sucess_update;
    }

}