<?php

class Manual_Model_Manual extends Agro_Db_Table_Abstract {
    protected $_schema = 'sistema';
    protected $_name = 'manual';
    protected $_primary = 'id';
    public $_order = 'ds_nome_arquivo';

    public function save($data) {
        try {
        	$User = Zend_Auth::getInstance()->getIdentity();
            $Adapter = new Zend_File_Transfer_Adapter_Http();
            $Adapter->setDestination(APPLICATION_PATH.'/upload_files/manual/');
            $file =$Adapter->getFileInfo();

            $Row = $this->getRow($data['id']);
            $Row->id_tipo = $data['id_tipo'];
            $Row->ds_nome = $data['ds_nome'];
            $Row->ds_descricao = $data['ds_descricao'];
            
            /*adiciona o id do usuario também no usuario de alteração
            para que mostre sempre o último usuário a alterar o manual (solicitação 2281)*/
            $Row->id_usuario_alteracao = $User->id;

            if ($file['ds_nome_arquivo']['name']) {
                if ($Row->ds_nome_arquivo) {
                    $sanitizedPath = realpath(APPLICATION_PATH.'/upload_files/manual/'.$Row->ds_nome_arquivo);
                    if (file_exists($sanitizedPath)) {
                        unlink($sanitizedPath);
                    }
                }
                if ($Adapter->receive($file['ds_nome_arquivo']['name'])) {
                    $Row->ds_nome_arquivo = $file['ds_nome_arquivo']['name'];
                } else {
                    $this->setMessage("Não foi possível salvar o manual.<br>Erro: {$Adapter->getErrors()}");
                    return true;
                }
            }

            return $Row->save();
        } catch (Exception $e) {
            $this->setMessage($e->getMessage().'<br><pre>'.$e->getTraceAsString().'</pre>');
            return false;
        }
    }

    public function getManual($id) {
        $select = $this->select();
        $select->setIntegrityCheck(false);
        $select->from(array('m' => 'sistema.manual'), array('id','id_tipo','ds_nome_arquivo','ds_descricao','ds_nome', 'fl_ativo'));
        $select->join(array('t' => 'sistema.tipo_manual'), 'm.id_tipo = t.id', array('ds_nome_tipo'));
        $select->where('m.id = ?', $id);

        $Row = $this->fetchRow($select);

        if ($Row) {
            return $Row->toArray();
        }
        return;
    }

    public function getData($where) {
        $User = Zend_Auth::getInstance()->getIdentity();
        $select = $this->select()->distinct();
        $select->setIntegrityCheck(false);
        $select->from(array('m' => 'sistema.manual'), array('id','id_tipo','ds_nome_arquivo','ds_descricao','ds_nome', 'fl_ativo'));
        $select->join(array('t' => 'sistema.tipo_manual'), 'm.id_tipo = t.id', array('ds_nome_tipo'));

        if ($User->ds_chave != 'ADMIN')  {
            $select->joinLeft(array('mu' => 'sistema.manual_usuarios'), 'mu.id_manual = m.id', null);
            $select->where('mu.id_usuario = ? OR m.id_usuario_criacao = ?', $User->id);
        }

        if (is_array($where)) {
            foreach ($where as $clause) {
                $field = $clause['field'];
                $operator = $clause['operator'];
                $value = $clause['value'];

                $select->where("$field $operator ?", $value);
            }

        } elseif ($where != '') {
            $select->where($where);
        }

        $select->order('ds_nome');
        return $select;
    }
    
    public function getInformativos($where='') {
    	$User = Zend_Auth::getInstance()->getIdentity();
    	
    	$case = 'CASE ';
    	$sqlCase = $this->getAdapter();
    	$case .= $sqlCase->quoteInto('WHEN m.dt_alteracao is null THEN m.dt_criacao ', '', Zend_Db::INT_TYPE); 
    	$case .= 'ELSE m.dt_alteracao END';
    	    	
    	$select = $this->select();
    	$select->setIntegrityCheck(false);
    	$select->from(array('m' => 'sistema.manual'), array('id','id_tipo','ds_nome_arquivo','ds_descricao','ds_nome', 'fl_ativo', 'dt_criacao' => new Zend_Db_Expr($case)));
    	$select->join(array('t' => 'sistema.tipo_manual'), 'm.id_tipo = t.id', array('ds_nome_tipo'));
    	$select->join(array('u' => 'sistema.usuarios'), 'm.id_usuario_alteracao = u.id', array('ds_nome_usuario'));
    
    	if ($User->ds_chave != 'ADMIN') {
    		$select->join(array('mu' => 'sistema.manual_usuarios'), 'mu.id_manual = m.id', null);
    		$select->where('mu.id_usuario = ?', $User->id);
    	}
    
    	if (is_array($where)) {
    		foreach ($where as $clause) {
    			$field = $clause['field'];
    			$operator = $clause['operator'];
    			$value = $clause['value'];
    
    			$select->where("$field $operator ?", $value);
    		}
    
    	} elseif ($where != '') {
    		$select->where($where);
    	}
       
    	$select->order('dt_criacao desc');
        
    	$result = $this->_db->fetchAll($select);

        return $result;
    }    
}
