<?php

class Produto_ValidacoeszoneamentoController extends Agro_Controller_Action {
	
	public function init() {
		$this->view->title = 'Nome da Validação: VALIDACAO_ZONEAMENTO ';
		$this->view->id_validacao = $this->getRequest()->getParam('id_validacao');
		$this->id_validacao = $this->getRequest()->getParam('id_validacao');
		$this->view->back = 'javascript:history.back()';
	}
	
	public function getModel() {
		return new Produto_Model_Validacoeszoneamento();
	}
	
	public function getForm() {
		$Form = new Produto_Form_Validacoeszoneamento($this->getRequest()->getParam('id_safra'));
		$Form->populate($this->getRequest()->getParams());
		return $Form;
	}
	
	public function indexAction() {
		$this->view->id_validacao = $this->getRequest()->getParam('id_validacao');
		parent::indexAction();
	}

	/*
	public function save(array $post) {
		try {
			$Model = $this->getModel();
			
			$data = array();
			$data['id_ciclo'] = $post['id_ciclo'];
			$data['id_produto'] = $post['id_produto'];
			$data['id_tipo_solo'] = $post['id_tipo_solo'];
			$data['id_validacao'] = $post['id_validacao'];
			$data['dt_inicial'] = Agro_Util::formatDate($post['dt_final'], Zend_Date::W3C);
			$data['dt_final'] = Agro_Util::formatDate($post['dt_inicial'], Zend_Date::W3C);
			
			if ($post['id']) {
				$Model->update($data, "id = {$post['id']}");
			} else {
				$Model->insert($data);
			}
			$this->_redirect('/produto/validacoeszoneamento/index/id_validacao/'. $post['id_validacao']);
		} catch (Exception $e) {
			$this->view->showMessage(MSG_ERROR, 'error');
		}
	}
	*/
	
	public function getFilter() {
		$where = array();
		
		if ($this->getRequest()->getParam('id_safra')) {
			$where[] = array(
				'field' => 's.id',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_safra')
			);
		}
		if ($this->getRequest()->getParam('id_produto')) {
			if ($this->getRequest()->getParam('id_produto')) {
				$where[] = array(
					'field' => 'zg.id_produto',
					'operator' => '=',
					'value' => $this->getRequest()->getParam('id_produto')
				);
			}
		}
		if ($this->getRequest()->getParam('id_ciclo')) {
			if ($this->getRequest()->getParam('id_ciclo')) {
				$where[] = array(
					'field' => 'zg.id_ciclo',
					'operator' => '=',
					'value' => $this->getRequest()->getParam('id_ciclo')
				);
			}
		}
		if ($this->getRequest()->getParam('id_tipo_solo')) {
			if ($this->getRequest()->getParam('id_tipo_solo')) {
				$where[] = array(
					'field' => 'zg.id_tipo_solo',
					'operator' => '=',
					'value' => $this->getRequest()->getParam('id_tipo_solo')
				);
			}
		}
		if ($this->getRequest()->getParam('dt_inicial')) {
			if ($this->getRequest()->getParam('dt_inicial')) {
				$where[] = array(
					'field' => 'dt_inicial',
					'operator' => '>',
					'value' => $this->getRequest()->getParam('dt_inicial')
				);
			}
		}
		if ($this->getRequest()->getParam('dt_final')) {
			if ($this->getRequest()->getParam('dt_final')) {
				$where[] = array(
					'field' => 'dt_final',
					'operator' => '<',
					'value' => $this->getRequest()->getParam('dt_final')
				);
			}
		}
		if ($this->getRequest()->getParam('id_municipio')) {
			if ($this->getRequest()->getParam('id_municipio')) {
				$where[] = array(
					'field' => 'zgm.id_municipio',
					'operator' => '=',
					'value' => $this->getRequest()->getParam('id_municipio')
				);
			}
		}
		return $where;
	}
	
	public function formAction() {
		
		$this->view->form = $this->getForm();
		$this->view->title .= ' » Formulário';
		
		$Model = $this->getModel();
		
		$this->view->form->populate($this->getRequest()->getParams());
		
		if ($this->getRequest()->isPost()) {
			if ($this->view->form->isValid($this->getRequest()->getPost())) {
				if (method_exists($Model, 'save')) {
					if ($Model->save($this->getRequest()->getParams())) {
						$this->view->showMessage(MSG_SUCCESS, 'success');
					} else {
						$this->view->showMessage(MSG_ERROR, 'error');
					}
				} else {
					$this->save($this->getRequest()->getParams());
				}
			} else {
				$Errors = $this->view->form->getMessages();
				$this->view->showMessage($this->getHtmlFormError($Errors), 'error');
			}
		} else if ($this->getRequest()->getParam('id')) {
			$row = $this->getRow();
			$row['dt_inicial'] = date('d/m/Y', strtotime($row['dt_inicial']));
			$row['dt_final'] = date('d/m/Y', strtotime($row['dt_final']));
			$this->view->form->populate($row);
		}
	}
	
	public function relacionarmunicipiosAction() {
		if ($this->getRequest()->isPost()) {
			$Model = new Produto_Model_ValidacoesRelacionarMunicipios();
			
			try {
				$insert = array();
				$params = $this->getRequest()->getParams();
				$insert['id_validacao_zoneamento_graos'] = $params['id_validacao_zoneamento'];
				$id_municipios = $this->getRequest()->getParam('id_municipios');
				$Model->removeAll($insert['id_validacao_zoneamento_graos'], $params['nome_estado']);
				foreach($id_municipios as $key => $id_municipio) {
					$Model->removeMunicipio($id_municipio);
					$insert['id_municipio'] = $id_municipio;
					$Model->insert($insert);
				}
				
				$this->view->showMessage(MSG_SUCCESS, 'success');
			} catch (Exception $e) {
				$this->view->showMessage(MSG_ERROR, 'error');
			}
		}
		
		$this->view->formRelacionar = new Produto_Form_RelacionarMunicipioZoneamento();
		$this->view->formRelacionar->populate(array("id_validacao" => $this->getRequest()->getParam('id_validacao'),
										  "id_validacao_zoneamento" => $this->getRequest()->getParam('id_validacao_zoneamento')));
		$Estado = new Sistema_Model_Estados();
		$this->view->estados = $Estado->getCombo();
	}
	
	public function buscamunicipiosAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$Model = new Sistema_Model_Municipios();
		$ModelZoneamento = new Produto_Model_ValidacoesRelacionarMunicipios();
		$estado = $this->getRequest()->getParam('estado');
		$municipios = $Model->getMunicipiosEstado($estado);
		
		$html = '<table style="width:650px"><tr>';
		$i = 0;
		foreach($municipios as $key => $val) {
			if($i % 3 == 0) {
				$html .= "
				</tr><tr>
				";
			}
			$i++;
			$extra = '';
			$vinculo = $ModelZoneamento->verificaVinculo($this->getRequest()->getParam('id_validacao_zoneamento'), $val['id']);
			
			$html .= "<td><input name='id_municipios[]' value='{$val['id']}' id='id_municipios{$val['id']}' class='class_id_municipios' $vinculo type='checkbox'></td>
			<td align='left'  width='30%'><label for='id_municipios{$val['id']}'><b>{$val['ds_nome_municipio']}</b> $extra</label></td>";
		}
		//weeeeeeeeeeeeeee bacalhau pra Brasilia
		if($estado == 'DF') {
			$html .= "<td></td><tdwidth='35%'></td><td width='35%'></td><td width='35%'></td>";
		}
		$html .= "</tr></table><br><input type='button' id='liberarchecks' name='liberarchecks' value='Liberar registros Bloqueados'>";
		return $this->getResponse()->setBody($html);
		
	}
}