<?php
/**
 *
 * News business
 *
 * @author Sandro Roberto Weisheimer [sandrow@solis.coop.br]
 *
 * @version $Id$
 *
 * \b Maintainers \n
 * Eduardo Bonfandini   [eduardo@solis.coop.br]
 * Jamiel Spezia        [jamiel@solis.coop.br]
 * Luiz Gregory Filho   [luiz@solis.coop.br]
 * Moises Heberle       [moises@solis.coop.br]
 * Sandro Roberto Weisheimer [sandrow@solis.coop.br]
 *
 * @since
 * Class created on 06/01/2009
 *
 * \b Organization: \n
 * SOLIS - Cooperativa de Solucoes Livres \n
 * The Gnuteca3 Development Team
 *
 * \b CopyLeft: \n
 * CopyLeft (L) 2008 SOLIS - Cooperativa de Solucoes Livres \n
 *
 * \b License: \n
 * Licensed under GPL (for further details read the COPYING file or http://www.gnu.org/copyleft/gpl.html )
 *
 * \b History: \n
 * See history in SVN repository: http://gnuteca.solis.coop.br
 */
class BusinessGnuteca3BusNews extends GnutecaBusiness
{
   // public $colsNoId;

    public $newsId;
	public $place;
    public $title;
    public $title1;
	public $news;
	public $date;
    public $beginDate;
	public $endDate;
    public $operator;
	public $isRestricted;
	public $isActive;
    public $busNewsAccess;
    public $busAuthenticate;
    public $busLibraryGroup;
    public $busBond;
    public $group;
    public $libraryUnitId;

    public $newsIdS;
	public $placeS;
    public $titleS;
	public $newsS;
    public $beginDateS;
	public $endDateS;
    public $beginBeginDateS;
	public $endBeginDateS;
    public $beginEndDateS;
	public $endEndDateS;
    public $operatorS;
	public $isRestrictedS;
	public $isActiveS;


    public function __construct()
    {
        parent::__construct();
        $this->tables   = 'gtcNews';
        $this->colsNoId = 'place,
                           title1,
                           news,
                           date,
                           beginDate,
                           endDate,
                           operator,
                           isRestricted,
                           isActive';
        $this->columns  = 'newsId, ' . $this->colsNoId;
        $this->busNewsAccess   = $this->MIOLO->getBusiness($this->module, 'BusNewsAccess');
        $this->busAuthenticate = $this->MIOLO->getBusiness($this->module, 'BusAuthenticate');
        $this->busBond         = $this->MIOLO->getBusiness($this->module, 'BusBond');
    }


    /**
     * List all records from the table handled by the class
     *
     * @param: None
     *
     * @returns (array): Return an array with the entire table
     *
     **/
    public function listNews($object=FALSE)
    {
        $this->clear();
        $this->setColumns($this->colsNoId);
//        $this->setColumns($this->columns);
        $this->setTables($this->tables);
        //$this->setOrderBy('newsId');
        $sql = $this->select();
        $rs  = $this->query($sql, $object);
        return $rs;
    }


    /**
     * Return a specific record from the database
     *
     * @param $moduleConfig (integer): Primary key of the record to be retrieved
     * @param $parameter (integer): Primary key of the record to be retrieved
     *
     * @return (object): Return an object of the type handled by the class
     *
     **/
    public function getNews($newsId)
    {
        $data = array($newsId);

        $this->clear();
        $this->setColumns($this->colsNoId);
//        $this->setColumns($this->columns);
        $this->setTables($this->tables);
        $this->setWhere('newsId = ?');
        $sql = $this->select($data);
        $rs  = $this->query($sql, $toObject=true);
        $this->setData($rs[0]);

        $this->busNewsAccess->newsIdS = $newsId;
        $this->group = $this->busNewsAccess->searchNewsAccess(TRUE);

        return $this;
    }

    //Mostra as noticias na Minha biblioteca, Pesquisa e Página inicial
    public function getNewsPlace($place, $isActive = 'TRUE')
    {
        $beginDate = $endDate = GnutecaDate::now(GnutecaDate::getDbMask('DATE'));
        $userCode = $this->busAuthenticate->getUserCode();
        $userGroup = $this->busBond->getAllPersonLink($userCode);
        foreach ($userGroup as $key => $group)
        {
            $allGroup[] = $group->linkId;
        }
        $allGroup = ($allGroup) ? implode(',', $allGroup) : 'null';

        if ( ($userCode) && !(GnutecaOperator::isLogged()) )
        {
            $whereRestricted = "A.isRestricted = 'FALSE'";
            $whereLinkId = "B.linkId in (".$allGroup.") or B.linkId is null";
        }

        if ( (!$userCode) && !(GnutecaOperator::isLogged()) )
        {
            $whereRestricted = "A.isRestricted = 'F'";
            $whereLinkId = "B.linkId is null";
        }

        $data = array($place, $beginDate, $endDate, $isActive);

        $this->clear();
//        $this->setColumns($this->colsNoId);
        $this->setTables('gtcNews            A
                LEFT JOIN gtcNewsAccess      B
                       ON (A.newsId = B.newsId)');
        $this->setColumns("A.news");
        $this->setWhere('A.place = ?');
        $this->setWhere('A.beginDate <= ?');
        $this->setWhere('A.endDate >= ?');
        //$this->setWhere('A.isRestricted = ?');
        $this->setWhere($whereRestricted);
        $this->setWhere('A.isActive = ?');
        //$this->setWhere('B.linkId in ('.$allGroup.")");
        $this->setWhere($whereLinkId);
        $sql = $this->select($data);
        $rs  = $this->query($sql);

        return $rs;
    }


    /**
     * Do a search on the database table handled by the class
     *
     * @param $filters (object): Search filters
     *
     * @return (array): An array containing the search results
     **/
    public function searchNews()
    {
        $this->clear();

        if ($v = $this->newsIdS)
        {
            $this->setWhere('newsId = ?');
            $data[] = $v;
        }
        if ($v = $this->placeS)
        {
            $this->setWhere('place = ?');
            $data[] = $v;
        }
        if ($v = $this->titleS)
        {
            $this->setWhere('lower(title1) LIKE lower(?)');
            $data[] = $v . '%';
        }
        if ($v = $this->newsS)
        {
            $this->setWhere('lower(news) LIKE lower(?)');
            $data[] = '%' . $v . '%';
        }

        if ($this->dateS)
        {
            $this->setWhere('date(date) = ?');
            $data[] = $this->dateS;
        }
        if ($this->beginDateS)
        {
            $this->setWhere('date(date) >= ?');
            $data[] = $this->beginDateS;
        }
        if ($this->endDateS)
        {
            $this->setWhere('date(date) <= ?');
            $data[] = $this->endDateS;
        }
        if ($this->beginBeginDateS)
        {
            $this->setWhere('date(beginDate) >= ?');
            $data[] = $this->beginBeginDateS;
        }
        if ($this->endBeginDateS)
        {
            $this->setWhere('date(beginDate) <= ?');
            $data[] = $this->endBeginDateS;
        }
        if ($this->beginEndDateS)
        {
            $this->setWhere('date(endDate) >= ?');
            $data[] = $this->beginEndDateS;
        }
        if ($this->endEndDateS)
        {
            $this->setWhere('date(endDate) <= ?');
            $data[] = $this->endEndDateS;
        }

        if ($v = $this->operatorS)
        {
            $this->setWhere('lower(operator) LIKE lower(?)');
            $data[] = $v . '%';
        }
        if ( $v = $this->isRestrictedS )
        {
        	$this->setWhere('isRestricted = ?');
        	$data[] = $v;
        }
        if ( $v = $this->isActiveS )
        {
        	$this->setWhere('isActive = ?');
        	$data[] = $v;
        }

        $this->setColumns($this->columns);
        $this->setTables($this->tables);
        $this->setOrderBy('date DESC');
        $sql = $this->select($data);
        $rs  = $this->query($sql);

        return $rs;
    }


    /**
     * Insert a new record
     *
     * @param $data (object): An object of the type handled by the class
     *
     * @return True if succed, otherwise False
     *
     **/
    public function insertNews()
    {
        $this->clear();
        $data = $this->associateData( $this->colsNoId );

        $this->setColumns($this->colsNoId);
        $this->setTables($this->tables);
        $data= array($this->place,
                     $this->title1,
                     $this->news,
                     $this->date,
                     $this->beginDate,
                     $this->endDate,
                     $this->operator,
                     $this->isRestricted,
                     $this->isActive);
        $sql = $this->insert($data);
        $rs  = $this->execute($sql);

        if ($this->group && $rs)
        {
            foreach ($this->group as $value)
            {
                $this->busNewsAccess->setData($value);
                $this->busNewsAccess->newsId = $this->getNextNewsId();
                $this->busNewsAccess->insertNewsAccess();
            }
        }
        return $rs;
    }


    /**
     * Update data from a specific record
     *
     * @param $data (object): Data which will replace the old record data
     *
     * @return (boolean): True if succeed, otherwise False
     *
     **/
    public function updateNews()
    {
    //    $data = $this->associateData( $this->colsNoId . ', newsId' );
       /* $data= array($this->place,
                     $this->title1,
                     $this->news,
                     $this->date,
                     $this->beginDate,
                     $this->endDate,
                     $this->operator,
                     $this->isRestricted,
                     $this->isActive,
                     $this->newsId);
        $this->clear();
        $this->setColumns($this->colsNoId);
        $this->setTables($this->tables);
        $this->setWhere('newsId = ?');
        $sql = $this->update($data);
        $rs  = $this->execute($sql);*/

        $data = $this->associateData( $this->colsNoId . ', newsId' );
        $this->clear();
        $this->setWhere('newsId = ?');
        $this->setColumns($this->colsNoId);
        $this->setTables($this->tables);
        $sql = $this->update($data);
        $rs  = $this->execute($sql);

        if ($this->group && $rs)
        {
            $this->busNewsAccess->deleteByGroup($this->newsId);
            foreach ($this->group as $value)
            {
                $this->busNewsAccess->setData($value);
                $this->busNewsAccess->insertNewsAccess();
            }
        }
        return $rs;
    }


    /**
     * Delete a record
     *
     * @param $moduleConfig (string): Primary key for deletion
     * @param $parameter (string): Primary key for deletion
     *
     * @return (boolean): True if succeed, otherwise False
     *
     **/
    public function deleteNews($newsId)
    {
        $data = array($newsId);

        if ($newsId)
        {
            $this->busNewsAccess->deleteByGroup($newsId);
        }

        $this->clear();
        $this->setTables($this->tables);
        $this->setWhere('newsId = ?');
        $sql = $this->delete($data);
        $rs  = $this->execute($sql);

        return $rs;
    }


    public function listPlace()
    {
        $listPlace = array(
            1 => _M('Minha biblioteca', $this->module),
            2 => _M('Tela inicial', $this->module),
            3 => _M('Pesquisa', $this->module)
        );
        return $listPlace;
    }

    public function getNextNewsId()
    {
        $query = $this->query("SELECT currval('seq_newsid')");
        return $query[0][0];
    }
}
?>
