<?php

class Sistema_Service_TermosContratacao
{
    private Agro_Db_Table_Abstract $model;
    private Sistema_Collection_TermosContratacao $collectionTermosContratacao;

    public function __construct(
        ?Agro_Db_Table_Abstract                 $model = null
        , ?Sistema_Collection_TermosContratacao $collectionTermosContratacao = null
    )
    {
        $this->model = $model ?? new Sistema_Model_TermosContratacao();
        $this->collectionTermosContratacao = $collectionTermosContratacao ?? new Sistema_Collection_TermosContratacao();
    }

    public function getTermos(array $where = [], string $order = ''): Zend_Db_Table_Rowset_Abstract
    {
        return $this->model->fetchAll($where, $order);
    }

    public function getTermosByChave(string $chave, bool $comIndiceChave = true): Sistema_Collection_TermosContratacao
    {
        $termos = $this->getTermos(["ds_chave = '{$chave}'"], 'dt_inicio_validade DESC')->toArray();
        return $this->organizarTermos($termos, $comIndiceChave);
    }

    public function getTodosTermos(): Sistema_Collection_TermosContratacao
    {
        $termos = $this->getTermos([], 'id DESC')->toArray();
        return $this->organizarTermos($termos, false);
    }

    /**
     * @param Agro_Utils_Date $date
     * @return Sistema_Collection_TermosContratacao
     * @throws Zend_Validate_Exception
     */
    public function getTermosValidadeIgualMaior(Agro_Utils_Date $date): Sistema_Collection_TermosContratacao
    {
        $termos = $this->getTermos(["dt_inicio_validade >= '{$date->toString()}'"])->toArray();
        return $this->organizarTermos($termos);
    }

    private function organizarTermos(array $termos, bool $comIndiceChave = true): Sistema_Collection_TermosContratacao
    {
        $mapperTermoContratacao = new Sistema_Mapper_TermosContratacao();

        foreach ($termos as $termosContratacao) {
            $this->collectionTermosContratacao->add(
                $mapperTermoContratacao->toEntity($termosContratacao)
                , $comIndiceChave
            );
        }

        return $this->collectionTermosContratacao;
    }
}
