<?php declare(strict_types=1);

class Produto_Model_ConfiguracaoDataCorte extends Agro_Db_Table_Abstract
{
    protected $_schema = 'produto';
	protected $_name = 'configuracao_data_corte';
	protected $_primary = 'id';

    public function getDataCorteAConsiderar(DateTime $dateTime): DateTime
    {
        $rs = $this->fetchRow(
            $this->select()
                ->from(
                    ['config' => 'produto.configuracao_data_corte'],
                    ["dt_corte"]
                )
                ->where('dt_corte <= ?', $dateTime->format('Y-m-d'))
                ->order('dt_corte DESC')
                ->limit(1)
        );
        
        return new DateTime($rs['dt_corte']);
    }

    public function getUltimaData(): DateTime
    {
        $rs = $this->fetchRow(
            $this->select()
                ->from(
                    ['config' => 'produto.configuracao_data_corte'],
                    ["dt_corte"]
                )
                ->order('dt_corte DESC')
                ->limit(1)
        );
        
        return new DateTime($rs['dt_corte']);
    }

    public function getCombo($first = true, $field = null): array
    {
        $rs = $this->_db->fetchAll(
            $this->select()
                ->from(
                    ['config' => 'produto.configuracao_data_corte'],
                    ['id', "to_char(dt_corte, 'DD/MM/YYYY') AS dt_corte"]
                )
                ->order('dt_corte ASC')
        );

        $map = [];
        foreach ($rs as $row) {
            $map[$row['id']] =  $row['dt_corte'];
        }

        return $map;
    }
}
