<?php

class Produto_ProdutoGeralController extends Agro_Controller_Action {
	public $_columnList = array(
		'ds_nome_produto_geral' => 'Nome',
		'ds_tipo_produto' => 'Tipo',
		'ds_nome_cultura' => 'Cultura',
		'ds_nome_ramo' => 'Ramo',
	);
	
	public function init() {
		$this->view->title = 'Produto » Cadastro » Produtos Gerais';
	}
	
	public function getForm() {
		return new Produto_Form_ProdutoGeral();
	}
	
	public function getModel() {
		return new Produto_Model_ProdutosGeral();
	}
	
	public function getFilter() {
		$where = array();
		if ($this->getRequest()->getParam('ds_nome_produto_geral')) {
			$where[] = array(
				'field' => 'ds_nome_produto_geral',
				'operator' => 'ilike',
				'value' => '%'.$this->getRequest()->getParam('ds_nome_produto_geral').'%'
			);
		}
			
		if ($this->getRequest()->getParam('id_cultura')) {
			$where[] = array(
				'field' => 'id_cultura',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_cultura')
			);
		}
		
		if ($this->getRequest()->getParam('id_ramo')) {
			$where[] = array(
				'field' => 'id_ramo',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_ramo')
			);
		}
		
		if ($this->getRequest()->getParam('id_tipo_produto')) {
			$where[] = array(
				'field' => 'id_tipo_produto',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_tipo_produto')
			);
		}
		
		if($this->getRequest()->getParam('fl_ativo')) {
			$where[] = array(
				'field' => 'fl_ativo',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('fl_ativo')
			);
		}
		
		return $where;
	}
	
	public function save(array $post) {
		try {
			$Model = $this->getModel();
			
			$data = array();
			$data['id_tipo_produto'] = $post['id_tipo_produto'];
			$data['tp_epoca_cultivo'] = $post['tp_epoca_cultivo'];
			$data['id_cultura'] = $post['id_cultura'];
			$data['id_ramo'] = $post['id_ramo'];
			$data['ds_nome_produto_geral'] = $post['ds_nome_produto_geral'];
			$data['cd_produto_geral_seguradora'] = $post['cd_produto_geral_seguradora'];
			
			if ($post['id']) {
				$Model->update($data, "id = {$post['id']}");
			} else {
				$Model->insert($data);
			}
			
			$this->_redirect('/produto/produtogeral');
		} catch (Exception $e) {
			$this->view->showMessage(MSG_ERROR, 'error');
		}
	}
}
