<?php

class Agro_Db_Table_Produtos extends Agro_Db_Table_Abstract {
	protected $_rowClass = 'Agro_Db_Table_Row_Produto';
	protected $_schema = 'produto';
	protected $_name = 'produtos';
	protected $_primary = 'id';
	public $_columnExcel = array(
		'id' => 'Cód',
		'ds_nome_produto' => 'Versão',
		'ds_nome_safra' => 'Safra',
		'ds_nome_produto_geral' => 'Produto Geral'
	);

	public function getCombo($safra=null, $first=true, $fl_renovacao=false, $emptyChoiceLabel = '--- Selecione um produto ---') {
		$return = array();

		if (!$safra)  $safra = $this->getDefaultAdapter()->fetchOne("select id from produto.safras where fl_vigente is true order by dt_inicio desc limit 1");

		if($fl_renovacao){
		    $Rs = $this->getDefaultAdapter()->fetchPairs("select id, case when ds_nome_abreviado <> '' then ds_nome_abreviado else ds_nome_produto end as ds_nome_produto from produto.produtos where fl_ativo=true and id_safra = $safra order by ds_nome_abreviado");
		} else {
		    $Rs = $this->getDefaultAdapter()->fetchPairs("select id, case when ds_nome_abreviado <> '' then ds_nome_abreviado else ds_nome_produto end as ds_nome_produto from produto.produtos where fl_ativo=true and id_safra = $safra order by ds_nome_abreviado");
		}

		if ($first) $return = array(0 => $emptyChoiceLabel);
		if (count($Rs)) {
			foreach ($Rs as $value => $text) {
				$return[$value] = $text;
			}
		}

		return $return;
	}

	public function getComboPorTipo(int $idSafra = null, int $idTipoProduto, $labelPrimeiraPosicao = '--- Selecione um produto ---')
	{
		if (empty($idSafra)) {
			$modelSafras = new Relatorio_Model_Safras();
			$idSafra = $modelSafras->safraCurrent;
		}

		$where = ["prod.fl_ativo = true", "prod.id_safra = {$idSafra}"];

		if (!empty($idTipoProduto)) {
			$where[] = "pg.id_tipo_produto = {$idTipoProduto}";
		}

		$where = implode(" AND ", $where);

		$rs = $this->getDefaultAdapter()->fetchPairs("
			SELECT prod.id, 
				   case when prod.ds_nome_abreviado <> '' then prod.ds_nome_abreviado else prod.ds_nome_produto end as ds_nome_produto 
			  FROM produto.produtos prod
			  JOIN produto.produtos_geral pg ON pg.id = prod.id_produto_geral 
			 WHERE {$where} 
			 ORDER BY prod.ds_nome_abreviado
		");

		if ($labelPrimeiraPosicao) $return = array(0 => $labelPrimeiraPosicao);

		foreach ($rs as $value => $text) {
			$return[$value] = $text;
		}
		
		return $return;
	}

    public function getComboDescricaoSafra(int $idSafra = null)
    {
        $modelSafras = new Produto_Model_Safras();
        $idSafraPesquisa = !empty($idSafra) ? $idSafra : $modelSafras->safraCurrent;
        $produtos = $modelSafras->getComboProdutoSafraRequest($idSafraPesquisa, 1, true);

        if (array_key_exists(0, $produtos)) {
            unset($produtos[0]);
        }

        return $produtos;
    }
}