<?php


namespace App\DAO;

use App\DAO\DAOResponse\DAOResponse;
use App\DAO\DAOResponse\DAOResponseInterface;
use App\DAO\Pagination\Pagination;
use App\Entities\Galeria\Galeria;
use App\Mappers\GaleriaMapper;
use App\Models\GaleriaModel;
use App\Utils\Collections\QueryFilterCollection;
use App\Utils\Collections\QueryOrderCollection;
use App\ViewModels\Galeria\GaleriaRegistrationViewModel\GaleriaRegistrationViewModel;
use Exception;

class GaleriaDAO extends DAO
{
    public function persistGaleriaRegistrationVM (GaleriaRegistrationViewModel $galeria_registration_vm) : DAOResponse {
        $dao_response = new DAOResponse();
        try {
            $galeria = $this->persistGaleria($galeria_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';
                }
                if (strpos($error['message'],'fk_procedimento_id_tipo_procedimento') !== false) {
                    $dao_response_errors['id_tipo_procedimento'] = 'O tipo de procedimento não existe';
                }
                if (strpos($error['message'],'fk_procedimento_criado_por') !== false) {
                    $dao_response_errors['criado_por'] = 'Esse usuário não existe.';
                }
                $dao_response->setErrors($dao_response_errors);
                log_message('error', json_encode($error));
            } else {
                $status_persistence = !!$galeria->getId()
                    ? DAOResponseInterface::SUCESS
                    : DAOResponseInterface::DATABASE_CONNECTION_ERROR;
            }
        } catch (Exception $exception) {
            log_message('error', json_encode($this->db->error()));
            $status_persistence = DAOResponseInterface::DATABASE_CONNECTION_ERROR;
            $galeria = null;
        }
        $this->db->close();
        $dao_response->setStatus($status_persistence);
        if ($status_persistence === DAOResponseInterface::SUCESS) {
            $dao_response->setData($galeria);
        }
        return $dao_response;
    }

    private function persistGaleria (GaleriaRegistrationViewModel $galeria_registration_vm) : Galeria {
        $galeria_model = new GaleriaModel ();
        $galeria = GaleriaMapper::getGaleriaFromGaleriaRegistrationVM($galeria_registration_vm);
        $galeria_model->registerGaleria($galeria);
        return $galeria;
    }

#----------------------------------------------------------------------------------------------------------------#

    public function getGaleriaList (?Pagination $pagination, ?QueryFilterCollection $query_filter_collection, ?QueryOrderCollection $query_order_collection = null) : DAOResponse {
        $sql = '
            SELECT
                galeria.id as id,
                galeria.id_clinica as id_clinica,
                galeria.id_medico as id_medico,
                galeria.id_paciente as id_paciente,
                galeria.id as imagem,
                galeria.descricao as descricao
            FROM
                galeria
            WHERE galeria.id NOT IN (
                SELECT 
                    galeria.id as id 
                FROM galeria_classificacao
                WHERE 
                    antes = galeria.id OR
                    depois = galeria.id
                )
        ';
        return $this->getDAOResponseFromPaginatedSelect([], $pagination, $query_filter_collection, $query_order_collection, $sql, function (array $result_array) {
            return GaleriaMapper::getGaleriaListVMCollectionFromArray($result_array);
        });
    }

    public function getGaleria (QueryFilterCollection $query_filter_collection) : DAOResponse {
        $sql = '
            SELECT
                galeria.id as id,
                galeria.id_clinica as id_clinica,
                galeria.id_medico as id_medico,
                galeria.id_paciente as id_paciente,
                galeria.imagem as imagem,
                galeria.descricao as descricao
            FROM
                galeria
        ';
        $binds = [];
        return $this->getDAOResponseFromUniqueRowSelect($binds, $query_filter_collection, $sql, function (array $result_array) {
            return GaleriaMapper::getGaleriaDetailsVMCollectionFromArray($result_array);
        });
    }

    public function deleteGaleria (int $id_galeria) : DAOResponse {
        $galeria_model = new GaleriaModel ();
        $dao_response = $this->getDAOResponseForDeletion($galeria_model, $id_galeria);
        return $dao_response;
    }

# -------------------------------------------------------------------------------------------------------------------------#

    public function getGaleriaId (int $id_galeria) {
        $sql = '
            SELECT
                galeria.id as id,
                galeria.id_clinica as id_clinica,
                galeria.id_medico as id_medico,
                galeria.id_paciente as id_paciente,
                galeria.imagem as imagem,
                galeria.descricao as descricao
            FROM
                galeria
            WHERE
                galeria.id = :id_galeria:
        ';
        $binds = ['id_galeria' => $id_galeria];
        $query = $this->db->query($sql, $binds);
        $result_array = $query->getResultArray();
        return ($result_array[0]['imagem']);
    }



}