<?php
/**
 * Copyright 2005-2017 de Solis Soluções Livres Ltda.
 *
 * Este arquivo é parte do programa Gnuteca.
 *
 * O Gnuteca é um software de propriedade da SOLIS, sendo desenvolvido
 * e mantido exclusivamente por esta empresa.
 *
 * A licença de uso está disponível mediante aquisição exclusiva junto à
 * SOLIS. A licença é concedida sem caráter de exclusividade ao licenciado.
 * Os direitos de uso são perpétuos.
 *
 * Embora os códigos fontes sejam fornecidos, o software é de propriedade
 * da SOLIS, não sendo permitido ao adquirente da licença a sua revenda,
 * empréstimo ou cessão (onerosa ou não) à terceiros. Também não é permitido,
 * a qualquer título e tempo, promover no software qualquer tipo de alienação,
 * reprodução, distribuição, divulgação, registro, licenciamento, transferência
 * ou qualquer outro ato que prejudique ou comprometa os direitos de propriedade
 * de software, o nome e a imagem da sua proprietária e do próprio software,
 * além de configurar concorrência à SOLIS.
 *
 * O licenciado, com o acesso ao código fonte do software, terá o direito de
 * promover mudanças no respectivo código. No entanto, nas situações em que ele
 * contar com o suporte oficial prestado pela SOLIS, não poderá promover mudanças
 * no código fonte, sob pena de perda do referido suporte.
 *
 * Para conhecer em detalhes o Termo de Licenciamento do Software Gnuteca
 * leia o arquivo “LICENCA.txt” disponível junto ao código deste software.
 * 
 * 
 * DictionaryContent business
 *
 *
 *
 *
 *
 **/
$MIOLO = MIOLO::getInstance();
$MIOLO->usesBusiness('gnuteca3', 'BusMaterial');

class BusinessGnuteca3BusDictionaryContent extends GBusiness
{
    public $dictionaryContentId;
    public $dictionaryContentIdS;
    public $remissiveContentS;
    public $relatedContentS;
    
    public $dictionaryId;
    public $dictionaryContent;
	public $searchFormatAccess;

    public $busDictionaryRelatedContent;
    public $dictionaryRelatedContent;
    
    public $busDictionaryRemissive;
    public $dictionaryRemissive;

    public function __construct()
    {
        $this->MIOLO = MIOLO::getInstance();
        $table = 'gtcDictionaryContent';
        $pkeys = 'dictionaryContentId';
        $cols  = 'dictionaryId,
                  dictionaryContent';
        parent::__construct($table, $pkeys, $cols);
        $this->busDictionaryRelatedContent = $this->MIOLO->getBusiness($this->module, 'BusDictionaryRelatedContent');
        $this->busDictionaryRemissive = $this->MIOLO->getBusiness($this->module, 'BusDictionaryRemissive');
    }

    public function insertDictionaryContent()
    {
    	$this->dictionaryContentId = $this->db->getNewId('seq_dictionaryContentId');
        $insert = $this->autoInsert();
        if ($this->dictionaryRelatedContent)
        {
            foreach ($this->dictionaryRelatedContent as $v)
            {
                $this->busDictionaryRelatedContent->setData($v);
                $this->busDictionaryRelatedContent->dictionaryContentId = $this->dictionaryContentId;
                $this->busDictionaryRelatedContent->insertDictionaryRelatedContent();
            }
        }
        
        $line = 0;
        if ($this->dictionaryRemissive)
        {
            foreach ($this->dictionaryRemissive as $i => $v)
            {
                $this->busDictionaryRemissive->setData($v);
                $this->busDictionaryRemissive->dictionaryContentId = $this->dictionaryContentId;
                
                if ( $v->removeData )
                {
                    if ( $v->dictionaryRemissivetId )
                    {
                       $this->busDictionaryRelatedContent->deleteDictionaryRemissive($v->dictionaryRemissivetId ); 
                    }
                }
                else 
                {
                    $this->busDictionaryRelatedContent->line = $line;
                    $this->busDictionaryRemissive->insertDictionaryRemissive();
                    $line++;
                }
            }
        }

        return $insert;
    }


    public function updateDictionaryContent()
    {
        if ($this->dictionaryRelatedContent)
        {
            foreach ($this->dictionaryRelatedContent as $v)
            {
                $this->busDictionaryRelatedContent->setData($v);
                $this->busDictionaryRelatedContent->dictionaryContentId        = $this->dictionaryContentId;
                $this->busDictionaryRelatedContent->dictionaryRelatedContentId = $v->dictionaryRelatedContentId;
                $this->busDictionaryRelatedContent->updateDictionaryRelatedContent();
            }
        }
        
        $line = 0;
        if ($this->dictionaryRemissive)
        {
            foreach ($this->dictionaryRemissive as $v)
            {
                $this->busDictionaryRemissive->setData($v);
                $this->busDictionaryRemissive->dictionaryContentId = $this->dictionaryContentId;
                $this->busDictionaryRemissive->dictionaryRemissivetId = $v->dictionaryRemissivetId;
                
                if ( $v->removeData )
                {
                    if ( $v->dictionaryRemissiveId )
                    {
                       $this->busDictionaryRemissive->deleteDictionaryRemissive($v->dictionaryRemissiveId); 
                    }
                }
                else 
                {
                    $this->busDictionaryRemissive->line = $line;
                    $this->busDictionaryRemissive->updateDictionaryRemissive();
                    $line++;
                }
            }
        }

        return $this->autoUpdate();
    }   


    public function deleteDictionaryContent($dictionaryContentId)
    {
        // Apaga conteúdos relacionados.
    	$this->busDictionaryRelatedContent->dictionaryContentId = $dictionaryContentId;
    	$search = $this->busDictionaryRelatedContent->searchDictionaryRelatedContent(TRUE);
    	if ($search)
    	{
    		foreach ($search as $v)
    		{
    			$this->busDictionaryRelatedContent->deleteDictionaryRelatedContent($v->dictionaryRelatedContentId);
    		}
    	}
        
        // Apaga remissivas do conteúdo.
    	$this->busDictionaryRemissive->dictionaryContentId = $dictionaryContentId;
    	$search = $this->busDictionaryRemissive->searchDictionaryRemissive(TRUE);
    	if ($search)
    	{
    		foreach ($search as $v)
    		{
    			$this->busDictionaryRemissive->deleteDictionaryRemissive($v->dictionaryRemissiveId);
    		}
        }
        
        // Apaga conteúdos de materias.
        if ( $_SESSION['deleteMaterialContent'] == true )
        {
            $dictionaryContent = $this->getDictionaryContent($dictionaryContentId);

            $this->deleteMaterialContent($dictionaryContent->dictionaryId, $dictionaryContent->dictionaryContent);
        }

    	$c = $this->getDictionaryContent($dictionaryContentId);

        return $this->autoDelete($dictionaryContentId);
    }

    public function deleteDictionaryContentFromDictionary($dictionaryId)
    {
        if ( !$dictionaryId )
        {
            return null;
        }

        $sql = "DELETE FROM gtcDictionaryContent WHERE dictionaryId = $dictionaryId";
        return $result = $this->query($sql, true);
    }

    public function getDictionaryContent($dictionaryContentId)
    {
        $this->clear();
        $data = $this->autoGet($dictionaryContentId);
        $this->setData($data);
        
        // Obtém dados de conteúdo relacionado.
        $this->busDictionaryRelatedContent->dictionaryContentId = $dictionaryContentId;
        $this->dictionaryRelatedContent = $this->busDictionaryRelatedContent->searchDictionaryRelatedContent(TRUE);
        
        // Obtém dados de remissiva.
        $this->busDictionaryRemissive->dictionaryContentId = $dictionaryContentId;
        $this->dictionaryRemissive = $this->busDictionaryRemissive->searchDictionaryRemissive(TRUE);
        return $data;
    }


    public function searchDictionaryContent($toObject = false)
    {
        $this->clear();
        if ($this->dictionaryContentIdS)
        {
            $this->setWhere('A.dictionaryContentId = ?');
        	$args[] = $this->dictionaryContentIdS;
        }
        if ($this->dictionaryId)
        {
        	$this->setWhere('A.dictionaryId = ?');
        	$args[] = $this->dictionaryId;
        }
        if ($this->dictionaryContent)
        {
        	$this->setWhere('lower(unaccent(A.dictionaryContent)) LIKE lower(unaccent(?))');
        	$args[] = '%' . $this->dictionaryContent . '%';
        }
        $this->setTables('gtcDictionaryContent  A
                LEFT JOIN gtcDictionary         B
                       ON (A.dictionaryId = B.dictionaryId)');
        $this->setOrderBy('B.description, A.dictionaryContent');
        $this->setColumns('A.dictionaryContentId,
                           B.description,
                           A.dictionaryContent');
        $sql = $this->select($args);

        return $this->query($sql, $toObject);
    }
    
    public function searchDictionaryContentToGrid($toObject = false)
    {
        $this->clear();
        if ($this->dictionaryContentIdS)
        {
            $this->setWhere('A.dictionaryContentId = ?');
        	$args[] = $this->dictionaryContentIdS;
        }
        
        if ($this->dictionaryId)
        {
        	$this->setWhere('A.dictionaryId = ?');
        	$args[] = $this->dictionaryId;
        }
        
        if ($this->dictionaryContent)
        {
        	$this->setWhere('lower(unaccent(A.dictionaryContent)) LIKE lower(unaccent(?))');
        	$args[] = '%' . $this->dictionaryContent . '%';
        }
        
        if ($this->remissiveContentS)
        {
        	$this->setWhere('lower(unaccent(gtcdictionaryremissive.remissivecontent)) LIKE lower(unaccent(?))');
        	$args[] = '%' . $this->remissiveContentS . '%';
        }
        
        if ($this->relatedContentS)
        {
        	$this->setWhere('lower(unaccent(gtcdictionaryrelatedcontent.relatedcontent)) LIKE lower(unaccent(?))');
        	$args[] = '%' . $this->relatedContentS . '%';
        }

        $this->setTables('gtcDictionaryContent A
                LEFT JOIN gtcDictionary B
                       ON (A.dictionaryId = B.dictionaryId)
                LEFT JOIN gtcdictionaryremissive ON (A.dictionarycontentid = gtcdictionaryremissive.dictionarycontentid)
                LEFT JOIN gtcdictionaryrelatedcontent ON (A.dictionarycontentid = gtcdictionaryrelatedcontent.dictionarycontentid)');
        
        $this->setOrderBy('B.description, A.dictionaryContent');
        
        $this->setColumns("DISTINCT A.dictionaryContentId,
                           B.description,
                           A.dictionaryContent,
                           (SELECT string_agg(remissivecontent, '<br>') FROM gtcdictionaryremissive WHERE dictionarycontentid = A.dictionarycontentid) as remissivecontent,
                           (SELECT string_agg(relatedcontent, '<br>') FROM gtcdictionaryrelatedcontent WHERE dictionarycontentid = A.dictionarycontentid) as relatedcontent");
        
        $sql = $this->select($args);

        return $this->query($sql, $toObject);
    }

    public function getAllDictionaryContent($dictionaryId)
    {
        $this->clear();

        $this->setColumns   ('dictionaryContent');
        $this->setTables    ('gtcDictionaryContent');
        $this->setWhere     ('dictionaryId = ?');
        $this->setOrderBy   ('dictionaryContent');

        $sql = $this->select(array($dictionaryId));
        return $this->query($sql, true);
    }


    public function listDictionaryContent()
    {
        return $this->autoList();
    }


    function clean()
    {
        $this->dictionaryContentId = null;
        $this->dictionaryId = null;
        $this->dictionaryContent = null;
    }

    public function getUpdateMaterialContentCount($dictionaryId, $olderContent )
    {
        $busDictionary  = $this->MIOLO->getBusiness($this->module, 'BusDictionary');
        $dic            = $busDictionary->getDictionary( $dictionaryId );
        $tags           = explode( ',', $dic->tags);

        if ( is_array($tags) )
        {

            foreach ( $tags as $line => $tag )
            {
                $tag = explode('.', $tag); //separa campo e subcampo
                $tags[$line]=  "( fieldId='$tag[0]' and subfieldid='$tag[1]')";
            }

            $tags   = implode(' or ' , $tags);
            $sql    = "select count(*) from gtcMaterial where content = $$$olderContent$$ and ( $tags )";
            $result = $this->query($sql);

            return $result[0][0];
        }

        return 0;
    }
    
    public function updateMaterialContent($dictionaryId, $olderContent, $currentContent )
    {
        $busDictionary  = $this->MIOLO->getBusiness($this->module, 'BusDictionary');
        $dic            = $busDictionary->getDictionary( $dictionaryId );
        $tags           = explode( ',', $dic->tags);
        
        if ( is_array($tags) )
        {
            foreach ( $tags as $line => $tag )
            {
                $tag = explode('.', $tag); //separa campo e subcampo
                $tags[$line]=  "( fieldId='$tag[0]' and subfieldid='$tag[1]')";
            }

            $tags   = implode(' or ' , $tags);

            //atualizar históricos
            $sql = "INSERT INTO gtcMaterialHistory
                                (controlNumber,
                                revisionNumber,
                                operator,
                                data,
                                chancesType,
                                fieldId,
                                subfieldid,
                                previousLine,
                                previousIndicator1,
                                previousIndicator2,
                                previousContent,
                                currentLine,
                                currentIndicator1,
                                currentIndicator2,
                                currentContent)
                         SELECT controlNumber,
                                ( select coalesce(max(revisionnumber)+1,1) from gtcMaterialHistory where controlNumber = a.controlNumber),
                                'gnuteca3',
                                now()::date,
                                'U',
                                a.fieldId,
                                a.subfieldid,
                                a.line,
                                a.indicator1,
                                a.indicator2,
                                $$$olderContent$$,
                                a.line,
                                a.indicator1,
                                a.indicator2,
                                $$$currentContent$$
                           FROM gtcMaterial a
                          WHERE content = $$$olderContent$$
                            AND ( $tags );";

            $result = $this->query($sql);

            /* Alterado na data: 09/04/2014 por Tcharles Silva
             * Motivo: Comentado, pois não garante para o modo classificação.
             * Alterado para função abaixo.
             * $searchContent = GString::construct($currentContent)->toASCII()->generate();
             */
            $searchContent = BusinessGnuteca3BusMaterial::prepareSearchContent('', $currentContent);
            $searchContentModule = BusinessGnuteca3BusMaterial::prepareSearchContentForSearchModule('', $currentContent);
            $sql = "UPDATE gtcMaterial SET content = $$$currentContent$$ , searchContent = $$$searchContent$$ , searchcontentforsearchmodule = $$$searchContentModule$$  WHERE content = $$$olderContent$$ and ( $tags );";

            $result = $this->query($sql);

            return true;
        }
        
        return 0;
    }

    public function deleteMaterialContent($dictionaryId, $content)
    {
        $busDictionary  = $this->MIOLO->getBusiness($this->module, 'BusDictionary');
        $dic            = $busDictionary->getDictionary( $dictionaryId );
        $tags           = explode( ',', $dic->tags);
        
        if ( is_array($tags) )
        {
            foreach ( $tags as $line => $tag )
            {
                $tag = explode('.', $tag); //separa campo e subcampo
                $tags[$line]=  "( fieldId='$tag[0]' and subfieldid='$tag[1]')";
            }

            $tags   = implode(' or ' , $tags);

            //atualizar históricos
            $sql = "INSERT INTO gtcMaterialHistory
                                (controlNumber,
                                revisionNumber,
                                operator,
                                data,
                                chancesType,
                                fieldId,
                                subfieldid,
                                previousLine,
                                previousIndicator1,
                                previousIndicator2,
                                previousContent,
                                currentLine,
                                currentIndicator1,
                                currentIndicator2,
                                currentContent)
                         SELECT controlNumber,
                                ( select coalesce(max(revisionnumber)+1,1) from gtcMaterialHistory where controlNumber = a.controlNumber),
                                'gnuteca3',
                                now()::date,
                                'D',
                                a.fieldId,
                                a.subfieldid,
                                a.line,
                                a.indicator1,
                                a.indicator2,
                                $$$content$$,
                                a.line,
                                a.indicator1,
                                a.indicator2,
                                ''
                           FROM gtcMaterial a
                          WHERE content = $$$content$$
                            AND ( $tags );";

            $result = $this->query($sql);

            $sql = "DELETE FROM gtcMaterial WHERE content = $$$content$$ and ( $tags );";

            $result = $this->query($sql);

            return true;
        }
        
        return 0;
    }

    public function getAllDictionaryContentWithRemissives()
    {
        $sql = "SELECT DISTINCT gtcdictionary.dictionaryid, 
                                gtcdictionary.remissivetag, 
                                gtcdictionarycontent.dictionarycontentid, 
                                gtcdictionarycontent.dictionarycontent 
                           FROM gtcdictionary 
                     INNER JOIN gtcdictionarycontent 
                             ON (gtcdictionary.dictionaryid = gtcdictionarycontent.dictionaryid) 
                     INNER JOIN gtcdictionaryremissive 
                             ON (gtcdictionarycontent.dictionarycontentid = gtcdictionaryremissive.dictionarycontentid)   
                          WHERE gtcdictionary.remissivetag is not null
                       ORDER BY gtcdictionarycontent.dictionarycontentid";
        
        return $this->query($sql);
    }

    //begin;

    //Update gtcMaterial set content = 'Jamiel' where content = 'Eduardo' and (  ( fieldId='100' and subfieldid='a') or ( fieldId='110' and subfieldid='a'));

    //commit;
}
?>