<?php

class Produto_VariedadesciclosController extends Agro_Controller_Action {
	
	protected $_backAfterSave = false;

	public function init() {
		$this->view->title = 'Produto » Cadastro » Variedades Ciclos';
	}
		
	public function getModel() {
		return new Produto_Model_VariedadesCiclos();
	}
	
	public function getForm() {
		$Form = new Produto_Form_VariedadesCiclos();
		
		return $Form;
	}

	public function afterSave() {
		try {
			$modelSafra = new Produto_Model_Safras;
	        $safra = $modelSafra->getSafraByProduto($this->getRequest()->getParam('id_produto'));
	        $safraAtual = $modelSafra->getSafraAtual();
	        if ($safra >= ($safraAtual['id'] - 1)) {
		        if (!$this->updateVersionZoneamento($safraAtual['id'])) {
		            $this->view->showMessage('Ciclo salvo com sucesso, porém houve problemas ao indicar para gerar novo banco de zoneamento!', 'alert');
		        }
		    }

	        $this->_forward($this->_forwardSettings['action'], $this->_forwardSettings['controller'], $this->_forwardSettings['module'], array());
	    } catch (Exception $e) {
	    	$this->view->showMessage('Ciclo salvo com sucesso, porém houve problemas ao indicar para gerar novo banco de zoneamento!', 'alert');
	    }
	}
	
	private function updateVersionZoneamento($idSafra) {
	    try {
            $adp = Zend_Db_Table_Abstract::getDefaultAdapter();
            $user = Zend_Auth::getInstance()->getIdentity();

            $stat = $adp->query('SELECT id FROM sistema.versao_zoneamento WHERE fl_importado_zoneamento = TRUE AND fl_exportado_tablet = FALSE');
            $result = $stat->fetchAll();

            if (empty($result)) {
                $adp->query('
                INSERT INTO sistema.versao_zoneamento (
                    id_usuario_criacao,
                    id_usuario_alteracao,
                    dt_criacao,
                    dt_alteracao,
                    fl_ativo,
                    fl_del,
                    id,
                    id_safra,
                    ds_nome_arquivo,
                    md5,
                    fl_importado_zoneamento,
                    fl_exportado_tablet
                ) VALUES (
                    ' . $user->id . ',
                    NULL,
                    NOW(),
                    NULL,
                    FALSE,
                    FALSE,
                    NEXTVAL(\'sistema.versao_zoneamento_id_seq\'),
                    ' . $idSafra . ',
                    \'\',
                    \'\',
                    TRUE,
                    FALSE
                );');
            }

            return true;
        } catch (Exception $e) {
	        Agro_Util::zf_debug($e->getMessage());
	        return false;
        }
    }

	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')) {
			$where[] = array(
				'field' => 'id_produto',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_produto')
			);
		}
		
		if ($this->getRequest()->getParam('id_variedade')) {
			$where[] = array(
				'field' => 'id_variedade',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_variedade')
			);
		}
		if ($this->getRequest()->getParam('id_ciclo')) {
			$where[] = array(
				'field' => 'id_ciclo',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_ciclo')
			);
		}
		if ($this->getRequest()->getParam('id_estado')) {
			$where[] = array(
				'field' => 'id_estado',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_estado')
			);
		}
		if ($this->getRequest()->getParam('fl_ativo')) {
			$where[] = array (
				'field' => 'vce.fl_ativo',
				'operator' => ' = ',
				'value' => $this->getRequest()->getParam('fl_ativo')
			);
		}
		return $where;
	}
}