<?php

class Produto_SafraController extends Agro_Controller_Action {

	public function init() {
		$this->view->title = 'Produto » Cadastro » Safra';
	}

	public function getModel() {
		return new Produto_Model_Safras();
	}

	public function getForm() {
		return new Produto_Form_Safra();
	}

	public function getFilter() {
		$where = array();

		if ($this->getRequest()->getParam('ds_nome_safra')) {
			$where[] = array(
				'field' => 'ds_nome_safra',
				'operator' => 'ilike',
				'value' => '%'.$this->getRequest()->getParam('ds_nome_safra').'%'
			);
		}
		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) {

		$data1 = explode('/', $post['dt_termino']);
		$data1 = '' .$data1[2] . $data1[1] . $data1[0];

		$data2 = explode('/', $post['dt_inicio']);
		$data2 = '' . $data2[2] .$data2[1] . $data2[0];

		if ($data1 <= $data2) {
			$this->view->showMessage(MSG_ERROR_DATE, 'alert');
			return false;
		}

		try {
			$Date = new Zend_Date();
			$Model = $this->getModel();

			$data = array();
			$data['ds_nome_safra'] = $post['ds_nome_safra'];
			$data['ds_chave'] = $post['ds_chave'];

			$Date->set($post['dt_inicio']);
			$data['dt_inicio'] = $Date->toString(Zend_Date::W3C);

			$Date->set($post['dt_termino']);
			$data['dt_termino'] = $Date->toString(Zend_Date::W3C);

			if ($post['id']) {
				$Model->update($data, "id = {$post['id']}");
			} else {
				$Model->insert($data);
			}

			$this->_redirect('/produto/safra');
		} catch (Exception $e) {
			$this->view->showMessage(MSG_ERROR, 'error');
		}
	}

	public function getprodutosAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$params = $this->getRequest()->getParams();

		if (isset($params['id']) && $params['id'] > 0) {
			$Safra = new Produto_Model_Safras();
			if (isset($params['first'])) {
				if (isset($params['id_cultura'])) {
					$produto = $Safra->getComboProdutoBySafraAndCultura($params['id'], $params['id_cultura'], $params['first']);
				} else {
					$produto = $Safra->getComboProdutoSafraRequest($params['id'], $params['first']);
				}
			} else {
				if (isset($params['id_cultura'])) {
					$produto = $Safra->getComboProdutoBySafraAndCultura($params['id'], $params['id_cultura'], $params['first']);
				} else {
					$produto = $Safra->getComboProdutoSafraRequest($params['id']);
				}
			}

			$this->getResponse()->setBody(Zend_Json::encode($produto));

		} elseif (isset($params['multiSafra'])) {
            $produtos = (new Produto_Model_Safras())->getComboProdutoSafraRequest(explode(',', $params['multiSafra']), 1, true);

            $produtosRetorno = [];
            foreach ($produtos as $key => $value) {
                $produtosRetorno[] = [
                    'value' => $key,
                    'text' => $value
                ];
            }

            array_shift($produtosRetorno);

            $this->getResponse()->setBody(Zend_Json::encode($produtosRetorno));
        } else{
			$Produto = new Produto_Model_Produtos();
			$this->getResponse()->setBody(Zend_Json::encode($Produto->getCombo()));
		}
	}

	public function getprodutosbysafraandculturaAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		$idSafra = $this->getRequest()->getParam('id') ?: $this->getRequest()->getParam('id_safra');
        $idsCultura = $this->getRequest()->getParam('id_cultura_multiple') ?? $this->getRequest()->getParam('id_cultura');

		$Safra = new Produto_Model_Safras();
		$produtos = $Safra->getComboProdutoBySafraAndCultura($idSafra, $idsCultura, $this->getRequest()->getParam('first'));
		$retorno = [];

		foreach ($produtos as $indice => $produto) {
            $retorno[] = ['value' => $indice, 'text' => $produto];
        }

		$this->getResponse()->setBody(Zend_Json::encode($retorno));
	}

	public function getprodutoscomboAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		if ($this->getRequest()->getParam('id')) {

			$Safra = new Produto_Model_Safras();
			$combo = $Safra->getComboProdutoSafraRequest($this->getRequest()->getParam('id'), $this->getRequest()->getParam('first'));

			$opt = array();
			if (is_array($combo)) {
				foreach ($combo as $key => $text) {
					$opt[] = array('id'=>$key,'label'=>$text);
				}
			}

			$this->getResponse()->setBody(Zend_Json::encode($opt));
		}
	}

	public function getprodutosabreviadocomboAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		if ($this->getRequest()->getParam('id')) {

			$Safra = new Produto_Model_Safras();
			$combo = $Safra->getComboProdutoAbreviadoSafraRequest($this->getRequest()->getParam('id'), $this->getRequest()->getParam('first'));

			$opt = array();
			if (is_array($combo)) {
				$opt[0] = array('id'=>0, 'label'=>'');
				foreach ($combo as $key => $text) {
					$opt[] = array('id'=>$key,'label'=>$text);
				}
			}

			$this->getResponse()->setBody(Zend_Json::encode($opt));
		}
	}

	public function getprodutosabreviadocombocomercialAction() {
	    $this->getHelper('ViewRenderer')->setNoRender();
	    $this->getHelper('layout')->disableLayout();
	    
	    if ($this->getRequest()->getParam('id')) {
	        
	        $Safra = new Produto_Model_Safras();
	        $combo = $Safra->getComboProdutoAbreviadoSafraRequest($this->getRequest()->getParam('id'), $this->getRequest()->getParam('first'), true, true);
	        
	        $opt = array();
	        if (is_array($combo)) {
	            $opt[0] = array('id'=>0, 'label'=>'');
	            foreach ($combo as $key => $text) {
	                $opt[] = array('id'=>$key,'label'=>$text);
	            }
	        }
	        
	        $this->getResponse()->setBody(Zend_Json::encode($opt));
	    }
	}
	
	public function getprodutogeralAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		if ($this->getRequest()->getParam('id')) {
			$Produto = new Produto_Model_Produtos();
			$produto = $Produto->getComboProdutoGeral($this->getRequest()->getParam('id'));

			$Json = new Zend_Json();
			$this->getResponse()->setBody($Json->encode($produto));
		}
	}

	public function padraoAction() {
		$this->isAjax();

		if ($this->getRequest()->getParam('id')) {
			$id = $this->getRequest()->getParam('id');

			$Safras = new Produto_Model_Safras();
			$Safras->update(array('id_usuario_alteracao' => Zend_Auth::getInstance()->getIdentity()->id, 'dt_alteracao' => 'now()', 'fl_vigente' => 0), null);
			$Safras->update(array('id_usuario_alteracao' => Zend_Auth::getInstance()->getIdentity()->id, 'dt_alteracao' => 'now()', 'fl_vigente' => 1), "id = $id");
		}
	}

	public function deleteAction() {
		parent::deleteAction();
	}

	public function getcomboprodutospgAction()
	{
		$this->isAjax();
		$modelProdutos = new Relatorio_Model_Produtos();
		$produtos = $modelProdutos->getComboPorTipo($this->getRequest()->getParam('id'), 3, '');
		$this->getResponse()->setBody(Zend_Json::encode($produtos));
	}
}
