<?php

declare(strict_types=1);

class Produto_Model_CondicaoPagamentoProposta extends Agro_Db_Table_Abstract {
    
	protected $_schema = 'produto';
	protected $_name = 'condicao_pagamento_proposta';
	protected $_primary = 'id_proposta';

    public function save(int $idProposta, int $idCondicaoPagamento): Zend_Db_Table_Row
    {
        $row = $this->createRow();

        $row->id_proposta = $idProposta;
        $row->id_condicao_pagamento = $idCondicaoPagamento;
        
        $row->save();

        return $row;
    }

    public function propostaPossuiCondicaoPagamento(int $idProposta): bool
    {
        return !!$this->fetchRow(
            $this->select()
                ->from(array('cpp' => "{$this->_schema}.{$this->_name}"), 'id_proposta')
                ->setIntegrityCheck(false)
                ->where('id_proposta = ?', $idProposta)
        );
    }

    public function getCondicaoPagamentoByIdProposta(int $idProposta): ?Zend_Db_Table_Row 
    {
        return $this->fetchRow(
            $this->select()
                ->from(array('cpp' => "{$this->_schema}.{$this->_name}"), false)
                ->join(array('cp' => 'produto.condicoes_pagamento'), 'cp.id = cpp.id_condicao_pagamento')
                ->setIntegrityCheck(false)
                ->where('cpp.id_proposta = ?', $idProposta)
        );
    }

    public function getIdsPropostasVinculadas(int $idCondicaoPagamento): array
    {
        $rs = $this->fetchAll(
            $this->select()
                ->from(array('cpp' => "{$this->_schema}.{$this->_name}"), 'id_proposta')
                ->setIntegrityCheck(false)
                ->where('id_condicao_pagamento = ?', $idCondicaoPagamento)
        )->toArray();

        $idsPropostaVinculadas = array_map(function ($row) {
            return $row['id_proposta'];
        }, $rs);

        return $idsPropostaVinculadas;
    }
}
?>