<?php

class Sistema_AcaoController extends Agro_Controller_Action {
	protected $_backAfterSave = false;
	protected $_paginator = false;
	
	public function init() {
		$this->view->title = 'Sistema » Configurações » Ações';
	}
	
	public function setBack() {
		$this->view->back = '/sistema/acao';
	}
	
	public function getForm() {
		return new Sistema_Form_Acao();
	}
	
	public function getModel() {
		return new Sistema_Model_Acoes();
	}
	
	public function getFilter() {
		$where = array();
		
		if ($this->getRequest()->getParam('id_parent')) {
			$where[] = array(
				'field' => 'id_parent',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_parent')
			);
		} else {
			$where[] = 'id_parent is null';
		}
		
		if ($this->getRequest()->getParam('ds_label')) {
			$where[] = array(
				'field' => 'ds_label',
				'operator' => 'ilike',
				'value' => '%'.$this->getRequest()->getParam('ds_label').'%'
			);
		}
		
		if ($this->getRequest()->getParam('fl_tipo')) {
			$where[] = array(
				'field' => 'fl_tipo',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('fl_tipo')
			);
		}
		
		return $where;
	}
	
	public function ordenaAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$Model = $this->getModel();
		
		$this->getResponse()->setBody($Model->reOrder($this->getRequest()->getParam('id'), $this->getRequest()->getParam('order')));
	}
	
	public function copiaracaoAction(){
    	$this->view->title = 'Sistema » Açoes » Copiar Ação';    	
    	$this->view->form = new Sistema_Form_CopiarAcao();
    	
    	if ($this->getRequest()->isPost()){
    		$params = $this->getRequest()->getParams();
    		
    		if ($this->view->form->isValid($params)){    			
    			Zend_Db_Table::getDefaultAdapter()->beginTransaction();
    			
    			try {
    				$Model = new Sistema_Model_Acoes();

    				$Row = $Model->find($params["id_acao"])->current();
    				$Acao = $Row->toArray();
    				
					unset($Acao["id"]);
					unset($Acao["id_usuario_criacao"]);
					unset($Acao["id_usuario_alteracao"]);
					unset($Acao["dt_criacao"]);
					unset($Acao["dt_alteracao"]);
					unset($Acao["fl_ativo"]);
					unset($Acao["fl_del"]);
					unset($Acao["fl_somente_responsavel"]);
    				
    				$Acao["ds_module"] = $params["ds_module"];
    				$Acao["ds_controller"] = $params["ds_controller"];
    				$Acao["ds_action"] = $params["ds_action"];
    				
    				$Acao["ds_label"] = $params["ds_label"];
    				$Acao["ds_descricao"] = $params["ds_descricao"];
    				
    				$Nova = $Model->createRow($Acao);
    					
    				$Nova->save();
    				
    				if ($Model->temFilhos($params["id_acao"])){
    					$this->salvaFilhos($params["id_acao"], $Nova->id, $Row->ds_module, $Nova->ds_module);
    				}
    				
    				$this->view->showMessage("Ação copiada com sucesso", 'success');
    				
    				Zend_Db_Table::getDefaultAdapter()->commit();
    				
    			} catch (Exception $e) {
    				Zend_Db_Table::getDefaultAdapter()->rollBack();
    				Agro_Util::informaErroAgronet($e->getMessage());
					$this->view->form->populate($params);
					$this->view->showMessage("Não foi possível realizar a operação", 'error');
    			}
    			
    		} else {
    			$Errors = $this->view->form->getMessages();
				$this->view->showMessage($this->getHtmlFormError($Errors), 'error');
				$this->view->form->populate($this->getRequest()->getParams());
    		}
    	}
    }
    
	public function salvaFilhos($id_acao, $id_acao_nova, $old_modulo, $new_modulo){
		$Model = new Sistema_Model_Acoes();
		
		$Acoes = $Model->fetchAll("id_parent=$id_acao");
		
		foreach ($Acoes as $acao){
			$Acao = $Model->find($acao->id)->current()->toArray();
	    	
			unset($Acao["id"]);
			unset($Acao["id_usuario_criacao"]);
			unset($Acao["id_usuario_alteracao"]);
			unset($Acao["dt_criacao"]);
			unset($Acao["dt_alteracao"]);
			unset($Acao["fl_ativo"]);
			unset($Acao["fl_del"]);
			unset($Acao["fl_somente_responsavel"]);
	    	
			$Acao["id_parent"] = $id_acao_nova;
			
			if ($old_modulo != $new_modulo){
				if ($Acao["ds_module"] == $old_modulo){
					$Acao["ds_module"] = $new_modulo;
				}
			}
			
	    	$Nova = $Model->createRow($Acao);
	    		
	    	$Nova->save();
	    	
	    	if ($Model->temFilhos($acao->id)){
	    		$this->salvaFilhos($acao->id, $Nova->id, $old_modulo, $new_modulo);
	    	}
		}
    }
    
    public function getAction(){
    	$this->isAjax();
    	$Model = new Sistema_Model_Acoes();
    	$Row = $Model->find($this->getRequest()->getParam("id_acao"))->current();
    	$this->getResponse()->setBody(Zend_Json::encode($Row->toArray()));
    }

    public function afterSave()
    {
        $profiler = Agro_Db_Table_Abstract::getDefaultAdapter()->getProfiler();
        $arrayZendProfilerQuery = $profiler->getQueryProfiles(Zend_Db_Profiler::INSERT | Zend_Db_Profiler::UPDATE);

        $this->geraSqlMigration($arrayZendProfilerQuery);
    }

    private function geraSqlMigration($arrayZendProfilerQuery)
    {
        if (empty($arrayZendProfilerQuery)) {
            return false;
        }

        foreach ($arrayZendProfilerQuery as $zendProfilerQuery) {
            $query = $zendProfilerQuery->getQuery();
            $valores = $zendProfilerQuery->getQueryParams();
            $pattern = '/\?/';
            $ultimaChaveArray = count($valores);

            foreach ($valores as $chave => $valor) {
                $queryType = $zendProfilerQuery->getQueryType();
                $valor = $this->tratarTipoCampo($chave, $valor, $queryType);

                if ($queryType === Zend_Db_Profiler::INSERT && $chave === $ultimaChaveArray) {
                    $valor = 'nextval(\'sistema.acao_id_seq\'::regclass)';
                }

                $query = preg_replace($pattern, $valor, $query, 1);
            }

            $arquivo = APPLICATION_PATH . '/upload_files/temp/acaosql_' . date('Ymd') . '.sql';
            file_put_contents($arquivo, $query . ";\n", FILE_APPEND);
        }

        return true;
    }

    private function tratarTipoCampo($chave, $valor, $queryType)
    {
        $valoresTipo = [
          Zend_Db_Profiler::INSERT => [
            'string',
            'string',
            'string',
            'string',
            'string',
            'integer',
            'string',
            'string',
            'char',
            'date',
            'integer',
            'integer'
          ],
          Zend_Db_Profiler::UPDATE => [
            'string',
            'string',
            'string',
            'string',
            'string',
            'integer',
            'string',
            'string',
            'char',
            'integer',
            'date'
          ]
        ];

        $indice = $chave - 1;

        if (in_array($valoresTipo[$queryType][$indice], ['string','char', 'date'])) {
            return "'{$valor}'";
        }

        if ($valoresTipo[$queryType][$indice] === 'integer' && empty($valor)) {
            return null;
        }

        return $valor;
    }
}