<?php

class Endosso_Model_Proposta_Questionarios extends Agro_Db_Table_Propostas {
	protected $_primary = array('id_proposta', 'id_atributo_rn');
	protected $_name = 'propostas_questionario';
	protected $_schema = 'seguro';
	
	public function add($idProposta, $row) {
		$Row = $this->createRow();
		
		$Row->id_proposta = $idProposta;
		$Row->id_atributo_rn = $row['id_atributo_rn'];
		$Row->ds_resposta = $row['ds_resposta'];
		$Row->id_usuario_criacao = $row['id_usuario_criacao'];
		$Row->id_usuario_alteracao = $row['id_usuario_alteracao'];
		$Row->fl_ativo = $row['fl_ativo'] ? 1 : 0;
		$Row->fl_del = $row['fl_del'] ? 1 : 0;
		
		return $Row->save();
	}
	

	public function save($rs) {
		$this->getDefaultAdapter()->beginTransaction();
		$idProposta = $rs['id_proposta'];
		$modelProposta = new Seguro_Model_PropostasPropriedades();
		$dsSigla = $modelProposta->get($idProposta)->toArray()['ds_sigla'];
		
		try {
			if($rs['q-CADPRO'] && $dsSigla == 'PR' && (preg_match('/0000000000/', $rs['questionario']['QUEST_CADPRO_VALOR']) || strlen($rs['questionario']['QUEST_CADPRO_VALOR']) < 10)){
				throw new Exception("Necessário informar 10 dígitos no campo Cadastro do Produtor Rural (CADPRO).");
			}
			$this->delete($rs['id_proposta'], 'id_proposta');
			
			if (is_array($rs['questionario'])) {
				foreach ($rs['questionario'] as $chave => $resposta) {
					$Row = $this->createRow();
					
					$Row->id_proposta = $rs['id_proposta'];
					$Row->id_atributo_rn = $this->getIdChave($chave);
					$Row->ds_resposta = $resposta;
					
					$Row->save();
				}

			}
			
			$this->getDefaultAdapter()->commit();
			return true;
		} catch (Exception $e) {
			$this->getDefaultAdapter()->rollBack();
			return false;
		}
	}
	
	public function getIdChave($chave) {
		return $this->getDefaultAdapter()->fetchOne("select id from produto.atributos_rn where ds_chave_rn = '$chave'");
	}
}