﻿<?php
class Sistema_Model_VistoriasItensSegurados extends Agro_Db_Table_Abstract {
	protected $_schema = "sistema";
	protected $_name = "vistorias_itens_segurados";	
	protected $_primary = array("id_vistoria","id_item_segurado");
	
	public function save($data) {
		try {
			$Row = $this->find($data["id_vistoria"], $data["id_item_segurado"])->current();
		
			if (!$Row){
				$Row = $this->createRow();
			}

			$Row->id_vistoria = $data["id_vistoria"];
			$Row->id_item_segurado = $data["id_item_segurado"];
			
			if($Row->save()){
				return true;
			} 
			
		} catch (Exception $e) {
			$this->setMessage($e->getMessage());
			return false;
		}
		
	}
	
	public function getItensSegurados($id){
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array('v'=>'sistema.v_vistorias_itens_segurados'));
		$select->where('id_vistoria = ?', $id);
		
		return $this->fetchAll($select);
	}
	
	public function getItensByVistoria($idVistoria){
		$data = array();
		
		if($idVistoria){
			$select = $this->select();
			$select->setIntegrityCheck(false);
			
			$select->from(array('vi'=>'sistema.vistorias_itens_segurados'),'id_item_segurado');
			if (is_array($idVistoria)) {
				$select->where('vi.id_vistoria in ('.implode(',',$idVistoria).')');
			} else {
				$select->where($this->getAdapter()->quoteInto('vi.id_vistoria = ?',$idVistoria));
			}
			$select->group('vi.id_item_segurado');
			
			$data = $this->_db->fetchCol($select);
		}
		
		return $data;
	}
	
	public function delete($idVistoria, $idItem = null) {
		$select = "	delete
					from
						sistema.vistorias_itens_segurados
					where
						id_vistoria = $idVistoria";
		if ($idItem) {
			$select .= " and id_item_segurado = $idItem";
		}
		
		$this->_db->query($select);
	}
}