<?php
/**
 * @package Joomla
 * @subpackage Abook
 * @copyright (C) 2010-now Federica Ugolotti
 * @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 3
 * 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');
use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper;
//jimport( 'joomla.html.html.content' );
require_once (JPATH_SITE.'/components/com_abook/helpers/route.php');

class modAbookAllinoneHelper
{
        static function getList(&$params)
        {
		$db             =  JFactory::getDBO();
		$app     = Factory::getApplication();
		$input     = $app->input;
                $user           =  JFactory::getUser();
                $userId         = (int) $user->get('id');
		$groups         = implode(',', $user->getAuthorisedViewLevels());
		$sort		= (int) $params->get('sort', 0);
                $catid          = $params->get('catid', array(0 => 0));
		$tag_id          = (array)$params->get('idtag', array());
		$doi_only	= (int) $params->get('doi_only', 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);
		$name_display	= (int) $params->get('name_display', 0);
		$show_text     = (int) $params->get('show_text', 1);
		$offset		= (int) $params->get('offset', 0);

		$temp           = $input->get('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)) {
			if ($name_display == 1){
                        	$query->select('GROUP_CONCAT(bb.name, " ", bb.lastname ORDER BY bb.lastname ASC SEPARATOR ", ") AS author');
               		}else{
                        	$query->select('GROUP_CONCAT(bb.lastname, " ", bb.name ORDER BY bb.lastname 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.state = 1 ');
		if (count($catid)>0 && $catid[0]>0) {
			$query->where('cc.id IN ('.implode(', ', $catid).')');
		}
		if (isset($tag_id) && count($tag_id)>0) {
			$query->leftjoin('#__abbooktag AS bt ON bt.idbook = a.id');
                        $query->where('bt.idtag IN ('.implode(', ', $tag_id).')');
                }
		switch ($sort){
			case 0:
				$query->order('a.dateinsert DESC, a.title');
			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_count 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                         = $input->getCmd('option');
                                $view                           = $input->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;
                                	}
				}else{
					return;
				}
                        break;
			case 5:
				$option		= $input->getCmd('option');
                                $view           = $input->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->loadColumn();
					$query->join('LEFT', '#__abbooktag AS at ON at.idbook = a.id');
                			$query->where('at.idtag IN ('.implode(', ', $tags).')');
				} else {
					return;
				}
			break;
		}
		if ($doi_only){
			$query->where('a.doi != ""');
		}

		$query->group('a.id');
                $db->setQuery($query, $offset, $count);
                $rows = $db->loadObjectList();
		//$params = &JComponentHelper::getParams( 'com_abook' );
		if (count($rows)>0){
                foreach ( $rows as $row )
                {
                       	//$row->image=$row->image!=''?$row->image:'components/com_abook/assets/images/nocover.png';
			if ($itemid!=''){
                               	$row->link = JRoute::_('index.php?option=com_abook&view=book&id='.$row->slug.'&catid='.$row->catslug.'&Itemid='.$itemid);
                        }else{
                                $row->link = JRoute::_(AbookHelperRoute::getBookRoute($row->slug, $row->catslug));
                        }
                        $row->dateinsert=JHtml::_('date', $row->dateinsert, 'd/m/Y');
			$row->catlink = JRoute::_(AbookHelperRoute::getCategoryRoute($row->catslug));
                        $row->title = (strlen($row->title)>$title_length)?substr_replace(htmlspecialchars( $row->title ),"...",$title_length):$row->title;
			if ($show_text){
				/*$row->description=strip_tags($row->description);
	                        $temp = explode(' ',$row->description);
				$cutted='';
                	        if(count($temp) > $desc_length){
                        	        for($i=0; $i<$desc_length; $i++) $cutted[$i] = $temp[$i];
                                		$cutted = implode(' ', $cutted);
	                	                $row->description = $cutted.'...';
        	                }
				$row->text = $row->description;*/
				$row->text = HTMLHelper::_('string.truncate', $row->description, $desc_length, $noSplit = true, $allowHtml = false);
			}
			//$row->text = (strlen($row->description)>$desc_length)?substr_replace($row->description,"...",$desc_length):$row->description;
                }
		}
			
                return $rows;
        }
}
