<?php

class Produto_ProdutoController extends Agro_Controller_Action {

	public function init() {
		$this->view->title = 'Produto » Configurações » Produto';
		//baca pra arrumar a tab certa ao voltar
		$arr = $this->getRequest()->getParams();
		if (array_key_exists('tab', $arr)) {
			$this->view->script = "$('#tabs').tabs('select', {$arr['tab']});";
		} else {
			$this->view->script = '';
		}
	}

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

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

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

		if ($this->getRequest()->getParam('id_produto_geral')) {
			$where[] = array(
				'field' => 'id_produto_geral',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_produto_geral')
			);
		}

		if ($this->getRequest()->getParam('id_safra')) {
			$where[] = array(
				'field' => 'id_safra',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_safra')
			);
		}

		if ($this->getRequest()->getParam('fl_ativo')) {
			$where[] = array(
				'field' => 'fl_ativo',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('fl_ativo')
			);
		}

		if ($this->getRequest()->getParam('id_seguradora')) {
			$where[] = array(
				'field' => 'id_seguradora',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_seguradora')
			);
		}

		return $where;
	}

	public function formAction()
    {
        $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
            ? 0
            : (int)$this->getRequest()->getParam('id');

        if ($id > 0) {
            $modelProdutosGeral = new Produto_Model_ProdutosGeral();
            $this->view->produtos_geral = $modelProdutosGeral->getProdutosGeralbyProduto($id);
            $this->view->produtos_geral_relacionado = $modelProdutosGeral->getProdutosGeralRelacionado($id);
            $this->view->produto = $this->getModel()->get($id);
        }

        parent::formAction();
    }
	
	public function produtosAction() {
		$result = array();
		$result['produtos'] = null;
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		$Produtos = $this->getModel();
		$produtos = $Produtos->getProdutosMobile();

		if (count($produtos) > 0) {
			$result['produtos'] = $produtos;
		}

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

	public function produtosvariedadesAction() {
		$result = array();
		$result['produtos_variedades'] = null;
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		$Produtos = $this->getModel();
		$produtosvariedades = $Produtos->getProdutosVariedadesMobile();

		if (count($produtosvariedades) > 0) {
			$result['produtos_variedades'] = $produtosvariedades;
		}

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

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

		$Model = new Produto_Model_Produtos();
		$Row = $Model->fetchRow("ds_nome_produto = '{$this->getRequest()->getParam('ds_nome_produto')}'");
		$result['status'] = true;

		if ($Row && ($Row->id != $this->getRequest()->getParam('id'))) {
			$result['message'] = 'O Nome escolhido ja existe em outra configuração. Por favor informe outro nome para a versão.';
			$result['execute'] = "$('#ds_nome_produto').focus();";
			$result['status'] = false;
		}

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

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

		$id_produto = $this->getRequest()->getParam('id_produto');
		$Model = new Produto_Model_ProdutosVariedades();
		$Rs = $Model->getProdutoVariedade($id_produto);

		$options = array();
		if ($Rs) {
			$options[] = '';
			foreach ($Rs as $row) {
				$options[] = array('id' => $row['id'], 'label' => $row['ds_nome_variedade']);
			}
			$Json = new Zend_Json();
			$this->getResponse()->setBody($Json->encode($options));
		} else {
			return false;
		}
	}

	public function copiarprodutoAction() {
	    set_time_limit(0);
	    
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$Model = $this->getModel();
		$return = array('status' => false);

		try {
			$idNewProduto = $Model->copiarProduto($this->getRequest()->getParams());

			if ($idNewProduto) {
				$return['message'] = "Novo produto criado com o código: $idNewProduto";
				$return['status'] = true;
			} else {
				$return['message'] = $Model->getMessages();
				$return['status'] = false;
			}
		} catch (Exception $e) {
			$return['message'] = 'Não foi possível copiar o produto.\nErro: ' . $Model->getMessages();
			$return['status'] = false;
		}

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

	public function geraxlsAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$dados = $this->getRequest()->getParams();
		$Model = $this->getModel();

		$ret = $Model->getDadosXls($dados);
		require_once(APPLICATION_PATH . "/../library/Agro/xls/PhpSimpleXlsGen.php");

		$myxls = new PhpSimpleXlsGen();
		$myxls->totalcol = 7;
		//( ID | NOME VERSAO | NOME PRODUTO GERAL |
		// CULTURA | SAFRA | COD SEGURADORA | ATIVO )
		$myxls->InsertText(utf8_decode('Código'));
		$myxls->InsertText('Nome Versão');
		$myxls->InsertText(utf8_decode('Produto Geral'));
		$myxls->InsertText(utf8_decode('Cultura'));
		$myxls->InsertText(utf8_decode('Safra'));
		$myxls->InsertText(utf8_decode('Código Seguradora'));
		$myxls->InsertText('Ativo');

		foreach ($ret as $linha) {
			$myxls->InsertText(utf8_decode($linha['id']) . ' ');
			$myxls->InsertText(utf8_decode($linha['ds_nome_produto']) . ' ');
			$myxls->InsertText(utf8_decode($linha['ds_nome_produto_geral']) . ' ');
			$myxls->InsertText(utf8_decode($linha['ds_nome_cultura']) . ' ');
			$myxls->InsertText(utf8_decode($linha['ds_nome_safra']) . ' ');
			$myxls->InsertText(utf8_decode($linha['cd_produto_seguradora']) . ' ');

			$myxls->InsertText($linha['fl_ativo'] ? 'Ativo' : 'Inativo' );
		}

		$myxls->SendFile();
	}

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

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

			$opt = array();
			$opt = $Safra->getComboProdutoSafraRequest($this->getRequest()->getParam('id'));

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

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

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

			$result = array();

			$Produtos = $Safra->getComboProdutoSafraRequest($this->getRequest()->getParam('id'));

			foreach ($Produtos as $key => $text) {
				$result[] = array('id' => $key, 'label' => $text);
			}

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

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

        $idsCultura = explode(',', $this->getRequest()->getParam('idCultura'));
		$idSafra = (int) $this->getRequest()->getParam('idSafra');
        $this->_return['coberturasProdutos'] = [];
        $this->_return['produtos'] = [];
        $idsProdutos = [];
		
		$produtos = (new Produto_Model_Produtos())->getProdutosByIdSafraIdCultura($idSafra, $idsCultura);

		foreach ($produtos as $pr) {
            $this->_return['produtos'][] = [
                'value' => $pr['id'],
                'text' => $pr['ds_nome_produto'],
                'id_cultura' => $pr['id_cultura']
            ];
            $idsProdutos[] = $pr['id'];
		}

        $coberturas = (new Produto_Model_Coberturas())->getCoberturasProduto($idsProdutos);

        foreach ($coberturas as $cobertura) {
            $this->_return['coberturasProdutos'][$cobertura['id_produto']][] = $cobertura['id_cobertura'];
        }
		
		$this->getResponse()->setBody(Zend_Json::encode($this->_return));
	}

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

		if ($this->getRequest()->getParam('id')) {
			$ProdutoHabilitacoes = new Produto_Model_Habilitacoes();
			$ProdutoHabilitacoes->desabilitaByProduto($this->getRequest()->getParam('id'));
		}

		$result = array();
		$this->getResponse()->setBody(Zend_Json::encode($result));
	}

	public function getprodutosconsultazoneamentoAction()
    {
        $this->isAjax();
        $retorno = ['erro' => false, 'produtos' => []];
        $parametros = $this->getRequest()->getParams();

        $validacaoZoneamento = "exists(select 1 ";
        $validacaoZoneamento .= "        from produto.produtos_validacoes ";
        $validacaoZoneamento .= "       where produto.produtos_validacoes.id_produto = produto.produtos.id ";
        $validacaoZoneamento .= "         and produto.produtos_validacoes.id_validacao = 4) ";

        $rowsProdutos = $this->getModel()->getComboProdutoProposta($parametros['id_safra'], [$validacaoZoneamento]);

        if (!empty($rowsProdutos)) {
            foreach ($rowsProdutos as $indice => $produto) {
                $retorno['produtos'][] = ['id' => $indice, 'descricao' => $produto];
            }
        }

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

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

        $this->_return['coberturas'] = [];
        $coberturas = (new Produto_Model_Coberturas())->getCoberturasProduto(
            explode(',', $this->getRequest()->getParam('idsProdutos'))
        );

        foreach ($coberturas as $cobertura) {
            $this->_return['coberturas'][] = [
                'value' => $cobertura['id_cobertura'],
                'text' => $cobertura['ds_nome_cobertura']
            ];
        }

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