<?php

class Default_Model_Propostas extends Agro_Db_Table_Abstract {
	protected $_name = 'propostas';
	protected $_schema = 'seguro';
	protected $_primary = 'id';

	public function getPropostas() {
		if (APPLICATION_ENV != 'production') {
			$Select = $this->select()->setIntegrityCheck(false)->where('id_versao is not null')->limit(10);
		} else {
			$Select = $this->select()->setIntegrityCheck(false)->where('id_versao is not null');
		}

		return $this->fetchAll($Select);
	}

	public function criaEndossos() {
		$Rs = $this->fetchAll($this->select()->from('seguro.propostas')->columns(array('id', 'id_endosso'))->where('id_endosso is null'));

		$this->getDefaultAdapter()->beginTransaction();
		try {
			if ($Rs->count()) {
				foreach ($Rs as $Row) {
					if (!$Row->id_endosso) {
						$Row->id_endosso = $this->_gera_endosso();

						if ($this->_inserir_endosso($Row)) {
							if ($Row->save()) {
								echo "Proposta OK: {$Row->id}<br>";
							} else {
								echo "Erro Propostas OK: {$Row->id}<br>";
							}
						}

						ob_flush();
						flush();
					}
				}
			}

			$this->getDefaultAdapter()->commit();
			return true;
		} catch (Exception $e) {
			$this->getDefaultAdapter()->rollBack();
			return false;
		}
	}

	private function _inserir_endosso($Row) {
		return $this->getDefaultAdapter()->insert('seguro.propostas_endosso', array(
			'id_endosso' => $Row->id_endosso,
			'id_proposta' => $Row->id,
			'id_usuario_criacao' => Zend_Auth::getInstance()->getIdentity()->id
		));
	}

	private function _gera_endosso() {
		$Select = $this->select()->setIntegrityCheck(false)->from('seguro.propostas_endosso', 'max(id_endosso)');
		return $this->getDefaultAdapter()->fetchOne($Select)+1;
	}
}