<?php

class Atendimento_Model_Proposta_Questionarios extends Agro_Db_Table_Abstract {
	protected $_primary = array('id_proposta', 'id_atributo_rn');
	protected $_name = 'propostas_questionario';
	protected $_schema = 'seguro';
	
	public function save(array $data, $fl_atendimento=false) {
		if ($data['id_proposta'] && count($data['questionario'])) {
			
			if($fl_atendimento == true){
				$stWhere = " and id_atributo_rn in (select id from produto.atributos_rn where fl_atendimento=true and id_atributo_modulo=2)";
			} else {
				$stWhere = " and id_atributo_rn in (select id from produto.atributos_rn where fl_atendimento=false and id_atributo_modulo=2)";
			}
			
			$this->getDefaultAdapter()->query("delete from seguro.propostas_questionario where id_proposta = {$data['id_proposta']} $stWhere");
			
			foreach ($data['questionario'] as $chave => $resposta) {
				$Row = $this->createRow();
				
				$Row->id_atributo_rn = $this->getIdAtributo($chave);
				$Row->id_proposta = $data['id_proposta'];
				$Row->ds_resposta = $resposta;
				
				$Row->save();
			}
			
			return true;
		}
	}
	
	private function getIdAtributo($chave) {
		$Select = $this->select()->setIntegrityCheck(false)->from('produto.atributos_rn', 'id')->where('ds_chave_rn = ?', $chave);
		return $this->getDefaultAdapter()->fetchOne($Select);
	}
}