<?php

declare(strict_types=1);


class Comercializacao_Model_TaxaAgrupamentoOrcamentoItem extends Agro_Db_Table_Abstract
{
    protected $_schema = 'comercializacao';
	protected $_name = 'taxa_agrupamento_orcamento_item';
	protected $_primary = array('id_taxa_agrupamento', 'id_item_segurado');

    public function save(array $data): ?Zend_Db_Table_Row
    {
        $row = $this->find($data['id_taxa_agrupamento'], $data['id_item_segurado'])->current();

        if (empty($row)) {
            $row = $this->createRow();
        }

        $row->id_taxa_agrupamento = $data['id_taxa_agrupamento'];
        $row->id_item_segurado = $data['id_item_segurado'];
        $row->vl_produtividade_estimada = empty($data['vl_produtividade_estimada']) 
            ? 0
            : $data['vl_produtividade_estimada'];

        $row->save();

        return $row == false ? null : $row;
    }

    public function findByIdTaxaAgrupamento(int $idTaxaAgrupamento): array
    {
        $rs = $this->fetchAll(
            $this->select()
                ->from(array('taoi' => "{$this->_schema}.{$this->_name}"))
                ->setIntegrityCheck(false)
                ->where('id_taxa_agrupamento = ?', $idTaxaAgrupamento)
        )->toArray();
            
        return $rs;
    }

    public function findByIdProposta(int $idProposta): array
    {
        $rs = $this->fetchAll(
            $this->select()
                ->setIntegrityCheck(false)
                ->from(array('taoi' => "{$this->_schema}.{$this->_name}"), 'vl_produtividade_estimada')
                ->join(
                    array('tao' => 'comercializacao.taxas_agrupamento_orcamentos'),
                    'tao.id_taxa_agrupamento = taoi.id_taxa_agrupamento',
                    false
                )
                ->join(
                    array('sis' => 'seguro.itens_segurados'),
                    'sis.id = taoi.id_item_segurado',
                    'nr_item_segurado'
                )
                ->where('tao.id_proposta = ?', $idProposta)
        )->toArray();
            
        return $rs;
    }
}
?>