<?php
/*
copyright 2015 Fiona Coulter http://www.iswebdesign.co.uk

This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

*/
// no direct access
defined('_JEXEC') or die('Restricted access');

if(file_exists(JPATH_SITE.'/components/com_k2/helpers/route.php'))
{
  require_once (JPATH_SITE.'/components/com_k2/helpers/route.php');
  require_once (JPATH_SITE.'/components/com_k2/helpers/utilities.php');
}


class modArticlesCountK2Helper
{

	public static function getList(&$params)
	{
		//$mainframe = &JFactory::getApplication();

		$db			= JFactory::getDBO();
		$nullDate	= $db->getNullDate();
		$dateFormat = $db->getDateFormat();

		$date = JFactory::getDate();
		$now = $date->format($date);
		$menuitemid = trim($params->get('menuitemid',''));
		$showEmpty = true;
		if($params->get('show_empty','yes') == 'no' && $params->get('show_tree','yes') == 'no')
		{
			$showEmpty = false;
		}
		
		

		
		$where = 'cc.published = 1 && cc.trash = 0';
		
		if ($params->get('show_unpublished','no')=='no')
		{
			if(!$showEmpty)
			{
				$where		.= ' AND (a.published = 1)'
				. ' AND (a.publish_up = '.$db->Quote($nullDate).' OR a.publish_up <= '.$db->Quote($now).')'
				. ' AND (a.publish_down = '.$db->Quote($nullDate).' OR a.publish_down >= '.$db->Quote($now).')';				
			}
		}
		
		$user	= JFactory::getUser();
		$groups	= implode(',', $user->getAuthorisedViewLevels());
		
		if($params->get('show_no_access_categories','no')=='no')
		{
	        $where .= ' AND (cc.access IN ('.$groups.')) ';
		}
		
		if($params->get('show_no_access_articles','no')=='no')
		{
			if(!$showEmpty)
			{
			  $where .= ' AND (a.access IN ('.$groups.')) ';
			}
		}
		
		  
	   $lists = new StdClass();
	   $lists->artcount = array();
	   $lists->names = array();
	   
	   $catid = '';
	   $ids = array(); //to store category ids in
	   
	   
	   
	   $catCondition = '';
	   
	   if( $params->get('use_request','no') == 'yes')
	   {
		    $input = JFactory::getApplication()->input;
	      	if ($input->get('view') == 'category') {
			  $id = intval($input->get('id',0,'int'));
			}
			else if ($input->get('view') == 'article') {
			  $id = intval($input->get('id','','int'));				
			}
			if($id > 0)
			{
			  if($params->get('show_child','no') == 'yes')
			  {
				  $catCondition = ' AND (cc.id='.$id.' OR cc.parent='.$id.')';
			  }
			  else
			  {
				  $catCondition = ' AND (cc.id='.$id.')';
			  }
			  
			  $ids[] = $id;
			  
			}
	   
	   }	
		else 
		{
	        $catParam = $params->get('catid','0');
			
			if(is_array($catParam))
			{
				if(! in_array('0',$catParam))
				{
				   $catid	= implode(',', $catParam );
					
				}
			}
			else
			{
				if($catParam != '0') //0 is the root category
				{
				   $catid = trim($catParam);
				}
			}
			  
			if ($catid)
			{
				$ids = explode( ',', $catid );
				JArrayHelper::toInteger( $ids );
				if($params->get('show_child','no') == 'yes')
				{
				  $catCondition = ' AND (cc.id IN('.implode(',',$ids).') OR cc.parent IN('.implode(',',$ids).'))';					
				}
				else
				{
				  $catCondition = ' AND (cc.id IN('.implode(',',$ids).'))';
				}
			}
		}
	   
		$groupby = 'cc.id';
			
		  $query = $db->getQuery(true);
		  $query->select('COUNT(a.id) AS artcount, cc.id AS catid, cc.name AS cattitle, cc.parent as parent_id');
		  $query->from('#__k2_categories AS cc');
		  $query->leftJoin('#__k2_items AS a ON cc.id = a.catid');
		  $query->where($where.$catCondition);
		  $query->group($groupby);
		  $query->order('cc.parent, cc.ordering ASC');
		  
			
		  $db->setQuery($query);
		  if (! $db->query() )
		  {
		    //echo $db->getErrorMsg();
			return array();
		  }
		  
		  /*we need to get levels, and re-arrange into tree.
		  This means line up categories so parent first, then followed by their children, note that categories are currently ordered by parent id, so root categories first, once we have checked all these, we should have exhausted all the possibilities
		  */
          
		  $results = $db->loadObjectList();		
		 // var_dump($results);
		  $rows = array();//this will contain tree
		  $found = array();
		  $maxLevels = (int)$params->get('maxLevels',0);
		  
		  foreach($results as &$result)
		  {
			if($result->parent_id > 0 && (in_array($result->parent_id,$ids)||count($ids)==0))
			{
			   continue; //the parent id is in our array of ids, so it is not a top-level category
			}
			$result->level = 0;
			$rows[] = $result;
			$level = 0;
			self::getChildren($rows, $results, $result->catid, $level, $maxLevels); 
		  }
		  $prevParent = 0;
		  $prevLevel = 0;
		  $prevId = 0;
		  $currTag = "";
		  $lists->items = array();
		  $depth = 0;
		  
		  foreach ($rows as $row)
		  {
			   $item = new stdClass();
			   $item->name = $row->cattitle;	
			   $item->subTotal = 0;
			   $item->artcount = $row->artcount;
			   $item->level = $row->level;
			   $item->parent_id = $row->parent_id;
			   $item->children = array();
			   $item->id = $row->catid;
			   
			   if($params->get('link_cat','yes')=='yes' || $params->get('show_tree','yes') == 'yes')
			   {
				  if($row->catid > 0)
				  {
					  $link = K2HelperRoute::getCategoryRoute($row->catid);
					  if(($menuitemid != '') && (strpos($link,'Itemid=') === FALSE))
					  {
						$link .= '&amp;Itemid='.$menuitemid;
						$link = JRoute::_($link);
					  }
					  $item->startLink = '<a href="'.$link.'">';
					  $item->endLink = '</a>';
				  }
				  else
				  {
					  $item->startLink = "";
					  $item->endLink = "";
					  $link = "";
				  }
				  
				   
				   //$item->name = '<a href="'. $link .'">'.$row->cattitle.'</a>';
			   }
			   else
			   {
				   $item->startLink = "";
				   $item->endLink = "";				   
			   }
			   
			   $item->startTag = $currTag . '<li>';
			   //$currTag = '</li>';
			   if($prevParent > 0 && $prevParent != $row->parent_id)
			   {
				 if($row->parent_id == $prevId)
				 {
					 $item->startTag = '<ul><li>';
					 $depth++;
				 }
				 else //its not a child so close up
				 {
					 //new level must be lower
					 $levels = $prevLevel - $row->level;
					 $item->startTag = str_repeat('</li></ul>',$levels).'</li><li>';
					 $depth = $depth - $levels;
				 }
			   }
			   $currTag = '</li>';   
			   
			   
			   $lists->items[$row->catid] = $item;
			   
			   $prevParent = $row->parent_id;
			   $prevLevel = $row->level;
			   $prevId = $row->catid;
		  
		  }
		  if($depth>0)
		  {
			$lists->closeTag = str_repeat('</li></ul>',$depth).'</li>';
		  }
		  $lists->id = uniqid('artcount');
		  $lists->layout = 'default';
		  if( $params->get('show_tree','yes') == 'yes')
		  {
			JHTML::_('behavior.tree',$lists->id, array(),array('text'=>JText::_('ARTCOUNTROOTNAME'),'data'=>array('url'=>'')));
			$lists->layout = 'tree';
		  }
		  
		  if($params->get('show_cumul','no') == 'yes')
		  {
			  //sort out parent child relationships
			  foreach($lists->items as $item)
			  {
				  if($item->id > 0 && isset($lists->items[$item->parent_id]))
				  {
					 $lists->items[$item->parent_id]->children[] = $item->id;
				  }
			  }
			  
			  foreach($lists->items as $item)
			  {
				  if(count($item->children) == 0)
				  {
					  $item->subTotal = $item->artcount;
					  self::addTotal($lists,$item, $item->artcount);
				  }
			  }
			  
			  foreach($lists->items as $item)
			  {
				 $item->artcountText = sprintf(JText::_('ARTCOUNTTEXT'),$item->subTotal);
				 if($params->get('show_zero_blank','yes') == 'yes' && $item->subTotal == 0)
				 {
					$item->artcountText = ""; 
				 }
			  }
		  }
		  else
		  {
			  foreach($lists->items as $item)
			  {
				 $item->artcountText = sprintf(JText::_('ARTCOUNTTEXT'),$item->artcount);
				 if($params->get('show_zero_blank','yes') == 'yes' && $item->artcount == 0)
				 {
					$item->artcountText = ""; 
				 }
			  }
		  }
		  
		  return $lists;		
			
		
    }
	
	private static function addTotal(&$lists, &$item, $amount)
	{
		 if($item->parent_id > 0 && isset($lists->items[$item->parent_id]))
		 {
			 $lists->items[$item->parent_id]->subTotal += $amount;
			 self::addTotal($lists, $lists->items[$item->parent_id], $amount);
		 }
	}

    private static function getChildren(&$rows, &$results, $parent_id, $level, $maxLevels = 0)
	{
		$localLevel = $level+1;
		if($maxLevels > 0 && $localLevel >= $maxLevels)
		{
			return;
		}
		$found = false;
		foreach($results as $result)
		{
			if($result->parent_id == $parent_id)
			{
				$found = true;
				$result->level = $localLevel;
				$rows[] = $result;
				self::getChildren($rows, $results, $result->catid, $localLevel, $maxLevels);
			}
			else
			{
				if($found)
				{
					break; //we are taking advantage of the fact that results are ordered by parent id, children have already been found, no point in checking further
				}
			}
		}
		
	}
	
	public static function getAdditionalLink($params)
	{
		$addcat = (int)$params->get('addcatid',0);
		if($addcat>0)
		{
			$menuitemid = trim($params->get('menuitemid',''));			
			$link = K2HelperRoute::getCategoryRoute($addcat);
			if(($menuitemid != '') && (strpos($link,'Itemid=') === FALSE))
			{
			  $link .= '&amp;Itemid='.$menuitemid;
			  $link = JRoute::_($link);
			}
			$linkText = '<a href="'.$link.'">'.JText::_('ADDITIONALCATLINKTEXT').'</a>';
			return $linkText;
		}
		return "";
	}

}
