<?php
/**
 * @package Joomla
 * @subpackage Abook
 * @copyright (C) 2010 Ugolotti Federica
 * @license GNU/GPL, see LICENSE.php
 * Abook is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License 2
 * as published by the Free Software Foundation.

 * Abook is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with Abook; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

defined('_JEXEC') or die('Restricted access');
require_once (JPATH_SITE.DS.'components'.DS.'com_abook'.DS.'helpers'.DS.'route.php');

class modAbookAllinoneHelper
{
        static function getList(&$params)
        {
                $db             =  JFactory::getDBO();
                $user           =  JFactory::getUser();
                $userId         = (int) $user->get('id');
		$groups         = implode(',', $user->getAuthorisedViewLevels());
		$sort		= (int) $params->get('sort', 0);
                $catid          = $params->get('catid', 0);
		$itemid         = (int) $params->get('itemid', '');
                $count          = (int) $params->get('count', 5);
		$show_image     = (int) $params->get('show_image', 1);
                $position       = (int) $params->get('position', 1);
		$desc_length	= (int) $params->get('desc_length', 50);
		$title_length   = (int) $params->get('title_length', 20);

		$temp           = JRequest::getString('id');
                $temp           = explode(':', $temp);
                $idbook         = $temp[0];

		$query          = $db->getQuery(true);
                $query->select("a.*");
                $query->select('CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(":", a.id, a.alias) ELSE a.id END as slug');
                $query->from('#__abbook AS a');
		$query->select("cc.title AS catname");
		$query->select('CASE WHEN CHAR_LENGTH(cc.alias) THEN CONCAT_WS(":", cc.id, cc.alias) ELSE cc.id END as catslug');
                $query->join('INNER', '#__abcategories AS cc ON cc.id = a.catid');
		if ($params->get('show_author', 0)) {
			$query->select("GROUP_CONCAT(bb.name ORDER BY bb.name ASC SEPARATOR ', ') AS author");
			$query->leftjoin('#__abbookauth AS aa ON aa.idbook = a.id ');
                	$query->leftjoin('#__abauthor AS bb ON bb.id=aa.idauth ');
		}
                $query->where('a.access IN ('.$groups.')');
		$query->where('cc.published = 1');
		$query->where('a.published = 1 ');
		if (count($catid)>1) {
			$query->where('cc.id IN ('.implode(', ', $catid).')');
		} else if ($catid==0){
			$query->where('cc.id ='.implode('', $catid));
		}
		switch ($sort){
			case 0:
				$query->order('a.dateinsert DESC');
			break;
			case 1:
				$query->select('ROUND( r.rating_sum / r.rating_count ) AS rating');
				$query->join('INNER', '#__abrating AS r ON r.book_id = a.id');
                                $query->order ('rating DESC');
                        break;
			case 2:
                                $query->order ('a.hits DESC');
                        break;
			case 3:
                                $query->order ('RAND()');
                        break;
			case 4:
				$query->where('a.id != '.(int) $idbook);
				$option                         = JRequest::getCmd('option');
                                $view                           = JRequest::getCmd('view');

                                if ($option == 'com_abook' && $view == 'book' && $idbook){
					$query1 = $db->getQuery(true);
					$query1->clear();
					$query1->select('metakey');
					$query1->from('#__abbook');
                        		$query1->where('id = ' . (int) $idbook);
                	                $db->setQuery($query1);
                        	        if ($metakey = trim($db->loadResult())){
                                		// explode the meta keys on a comma
		                                $keys = explode(',', $metakey);
        		                        $likes = array();
                		                foreach ($keys as $key){
                        		                $key = trim($key);
                                		        if ($key) {
                                        		        // surround with commas so first and last items have surrounding commas
                                                		$likes[] = ',' . $db->getEscaped($key) . ',';
		                                        }
        		                        }
                		                if (count($likes)){
							$query->where('( CONCAT(",", REPLACE(a.metakey,", ",","),",") LIKE "%'.implode('%" OR CONCAT(",", REPLACE(a.metakey,", ",","),",") LIKE "%', $likes).'%" )');
                                		        $query->order('RAND()');
                        	        	}else{
                                 		       return;
                                		}
					}else{
                                        	return;
                                	}
                                	$query->order('RAND()');
				}else{
					return;
				}
                        break;
			case 5:
				$option		= JRequest::getCmd('option');
                                $view           = JRequest::getCmd('view');
				$query->where('a.id != '.(int) $idbook);

                                if ($option == 'com_abook' && $view == 'book' && $idbook){
                                        $query1 = $db->getQuery(true);
                                        $query1->clear();
                                        $query1->select('idtag');
                                        $query1->from('#__abbooktag');
                                        $query1->where('idbook = ' . (int) $idbook);
                                        $db->setQuery($query1);
					$tags = $db->loadResultArray();
					$query->join('LEFT', '#__abbooktag AS at ON at.idbook = a.id');
                			$query->where('at.idtag IN ('.implode(', ', $tags).')');
                			$query->order('RAND()');
				} else {
					return;
				}
			break;
		}

		$query->group('a.id');
                $db->setQuery($query, 0, $count);
                $rows = $db->loadObjectList();
		//$params = &JComponentHelper::getParams( 'com_abook' );
                $i              = 0;
                $lists  = array();
		if (count($rows)>0){
                foreach ( $rows as $row )
                {
			$lists[$i]=new stdClass();
			if ($show_image==1){
                        	$cover=$row->image!=''?$row->image:'components/com_abook/assets/images/nocover.png';
                                $lists[$i]->image=$cover;
                        }
			if ($itemid!=''){
                               	$lists[$i]->link = JRoute::_('index.php?option=com_abook&view=book&id='.$row->slug.'&catid='.$row->catslug.'&Itemid='.$itemid);
                        }else{
                                $lists[$i]->link = JRoute::_(AbookHelperRoute::getBookRoute($row->slug, $row->catslug));
                        }
			if ($params->get('show_author', 0)) {
                        	$lists[$i]->author=$row->author;
			}
			$lists[$i]->catlink = JRoute::_(AbookHelperRoute::getCategoryRoute($row->catslug));
                        $lists[$i]->catname = $row->catname;
                        $lists[$i]->title = (strlen($row->title)>$title_length)?substr_replace(htmlspecialchars( $row->title ),"...",$title_length):$row->title;
			$row->description=strip_tags($row->description);
			$lists[$i]->text = (strlen($row->description)>$desc_length)?substr_replace($row->description,"...",$desc_length):$row->description;
                        $i++;
                }
		}
			
                return $lists;
        }
}
