<?php
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.application.component.modeladmin');

class igModelcategory extends JModelAdmin
{
	function __construct()
	{
		parent::__construct();
	}
	
	public function getForm($data = array(), $loadData = true)
	{
		return;
	}
	
	function getCategory($id)
	{
		$query = $this->_db->getQuery(true);

		$query->select('c.*');
		$query->from('#__igallery AS c');
		
		$query->where('c.id = '.(int)$id);
		$query->where('c.published = 1');
		$query->where('c.moderate = 1');
		
		$nullDate = $this->_db->Quote($this->_db->getNullDate());
		$nowDate = $this->_db->Quote(JFactory::getDate()->toMySQL());
		$query->where('(c.publish_up = ' . $nullDate . ' OR c.publish_up <= ' . $nowDate . ')');
		$query->where('(c.publish_down = ' . $nullDate . ' OR c.publish_down >= ' . $nowDate . ')');
		
		$this->_db->setQuery($query);
		$category = $this->_db->loadObject();
	    return $category;
    }
    
	function getProfile($id)
	{
		$query = 'SELECT * FROM #__igallery_profiles WHERE published = 1 AND id = '.(int)$id;
		$this->_db->setQuery($query);
		$profile = $this->_db->loadObject();
	    return $profile;
    }

	function getPagination($total, $limit)
	{
		jimport('joomla.html.pagination');
		$pagination = new JPagination($total, JRequest::getInt('limitstart', 0), $limit );
		return $pagination;
	}

	function getCategoryChildren($catId, $profile)
	{
		$user =& JFactory::getUser();
		$query = $this->_db->getQuery(true);

		$query->select('c.*');
		$query->from('#__igallery AS c');
		
		$query->select('p.menu_max_width, p.menu_max_height, p.img_quality, p.menu_access');
		$query->join('INNER', '`#__igallery_profiles` AS p ON p.id = c.profile');
		
		$query->where('c.published = 1');
		$query->where('c.moderate = 1');
		$query->where('c.parent = '.(int)$catId);
		
		$groups	= implode(',', $user->authorisedLevels() );
		$query->where('p.menu_access IN ('.$groups.')');
		
		$nullDate = $this->_db->Quote($this->_db->getNullDate());
		$nowDate = $this->_db->Quote(JFactory::getDate()->toMySQL());
		$query->where('(c.publish_up = ' . $nullDate . ' OR c.publish_up <= ' . $nowDate . ')');
		$query->where('(c.publish_down = ' . $nullDate . ' OR c.publish_down >= ' . $nowDate . ')');
		
		
		$query->order('ordering');

		if($profile->menu_pagination == 1)
		{
			$categoryChildren = $this->_getList($query, JRequest::getInt('limitstart', 0), $profile->menu_pagination_amount );
		}
		else
		{
			$categoryChildren = $this->_getList($query);
		}
		
		$this->menuTotal = $this->_getListCount($query);
		
		$count = count($categoryChildren);
		
		$categoryChildren = array_values($categoryChildren);
		
		for($i=0; $i<count($categoryChildren); $i++ )
		{
			if( empty($categoryChildren[$i]->parent) )
			{
				$profileId = $categoryChildren[$i]->profile;
			}
			else
			{
				$parentCat = $this->getCategory($categoryChildren[$i]->parent);
				$profileId = $parentCat->profile;
			}
			
			$profile = $this->getProfile($profileId);
			
			$categoryChildren[$i]->menu_max_width = $profile->menu_max_width;
			$categoryChildren[$i]->menu_max_height = $profile->menu_max_height;
			
			if( strlen($categoryChildren[$i]->menu_image_filename) > 1)
			{
				$menuPhoto = new stdClass();
				$menuPhoto->filename = $categoryChildren[$i]->menu_image_filename;
				$menuPhoto->rotation = 0;
			}
			else
			{
				$query = 'SELECT * from #__igallery_img WHERE gallery_id = '.(int)$categoryChildren[$i]->id.
				' AND menu_image = 1 LIMIT 1';
				$this->_db->setQuery($query);
				$menuPhoto = $this->_db->loadObject();
				
				if(empty($menuPhoto) && $profile->menu_image_defaults == 1)
				{
					$query = 'SELECT * from #__igallery_img WHERE gallery_id = '.(int)$categoryChildren[$i]->id.
					' ORDER BY ordering LIMIT 1';
					$this->_db->setQuery($query);
					$menuPhoto = $this->_db->loadObject();
				}
			 }
				
			if( !empty($menuPhoto->filename) )
			{
				$categoryChildren[$i]->fileArray = igFileHelper::originalToResized($menuPhoto->filename, 
	            $profile->menu_max_width, $profile->menu_max_height, $profile->img_quality, $profile->crop_menu,
	            $menuPhoto->rotation, $profile->round_menu, $profile->round_fill);
	        }
			
        }
		
		return $categoryChildren;
	}
	
	function addCategoryHit($catid)
	{
		$this->addTablePath(IG_ADMINISTRATOR_COMPONENT.DS.'tables');
		$row =& $this->getTable('igallery');
		$row->load( (int)$catid );
		$row->hits = $row->hits + 1;
		
		if(!$row->store())
		{
			$this->setError($this->_db->getErrorMsg());
		}
	}
	
	function getImagesList($select, $profile, $catid, $tags, $where, $order, $child, $limit)
	{
		$query = $this->_db->getQuery(true);
		
		$query->select('i.*');
		$query->from('#__igallery_img AS i');
		
		$query->select('c.name');
		$query->join('INNER', '`#__igallery` AS c ON c.id = i.gallery_id');
		
		$query->select('p.thumb_pagination_amount, p.thumb_pagination');
		$query->join('INNER', '`#__igallery_profiles` AS p ON p.id = c.profile');
		
		if(!empty($where))
		{
			$query->where($where);
		}
		
		if($child)
		{
			$children = $this->getChildList($catid);
			$children[] = (int)$catid;
			$query->where('FIND_IN_SET(i.gallery_id,"'.implode(',',$children).'")');
		}
		else
		{
			$query->where('i.gallery_id = '.(int)$catid);
		}
		
		if(!empty($tags))
		{
			$tagsArray = explode(',', $tags);
			$tagsLikeSql = array();
			
			foreach($tagsArray as $key => $value)
			{
			   $tagsLikeSql[] = 'i.tags LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( trim($value), true ).'%', false );
			}
			$tagClauses = implode( ' OR ', $tagsLikeSql );
			$query->where($tagClauses);
		}
		
		$query->where('i.published = 1');
		$query->where('i.moderate = 1');
		
		$nullDate = $this->_db->Quote($this->_db->getNullDate());
		$nowDate = $this->_db->Quote(JFactory::getDate()->toMySQL());
		$query->where('(i.publish_up = ' . $nullDate . ' OR i.publish_up <= ' . $nowDate . ')');
		$query->where('(i.publish_down = ' . $nullDate . ' OR i.publish_down >= ' . $nowDate . ')');
		
		$user	= JFactory::getUser();
		$groups	= implode(',', $user->authorisedLevels() );
		$query->where('i.access IN ('.$groups.')');
		
		$query->order($order);
		
		if($profile->thumb_pagination == 1)
		{
			$photoList = $this->_getList($query, JRequest::getInt('limitstart', 0), (int)$profile->thumb_pagination_amount);
		}
		else
		{
			if(!empty($limit))
			{
				$photoList = $this->_getList($query, 0 , $limit);
			}
			else
			{
				$photoList = $this->_getList($query);
			}
		}
		
		$this->thumbTotal = $this->_getListCount($query);
		
		return $photoList;
	}

	function getCategoryImagesList($profile, $catid, $tags, $child, $limit)
	{
		$this->addCategoryHit($catid);
		
		$select = 'i.*';
		$where = '';
		if(empty($tags))
		{
			$where = 'i.gallery_id = '.(int)$catid;
		}
		$order = 'i.ordering';
		$photoList = $this->getImagesList($select, $profile, $catid, $tags, $where, $order, $child, $limit);
		
		return $photoList;
	}

	function getRandomList($profile, $catid, $tags, $child, $limit)
	{
		$select = 'DISTINCT i.*';
		$where = null;
		$order = 'RAND()';
		$photoList = $this->getImagesList($select, $profile, $catid, $tags, $where, $order, $child, $limit);
		
		return $photoList;
	}

	function getLatestList($profile, $catid, $tags, $child, $limit)
	{
		$select = 'i.*';
		$where = null;
		$order = 'date DESC';
		$photoList = $this->getImagesList($select, $profile, $catid, $tags, $where, $order, $child, $limit);
		
		return $photoList;
	}
	
	function getHitsList($profile, $catid, $tags, $child, $limit)
	{
		$select = 'i.*';
		$where = null;
		$order = 'hits DESC';
		$photoList = $this->getImagesList($select, $profile, $catid, $tags, $where, $order, $child, $limit);
		
		return $photoList;
	}
	
	function getChildList($parentId)
	{
	    $query = $this->_db->getQuery(true);

		$query->select('c.*');
		$query->from('#__igallery AS c');
		$query->where('c.published = 1');
		$query->where('c.moderate = 1');
		$query->order('c.parent, c.ordering');
	    
	    $this->_db->setQuery($query);
		$categories = $this->_db->loadObjectList();

        $children = array();

        if($categories)
        {
            $list = array();

            foreach($categories as $v)
            {
                $pt = $v->parent;
                $list = @$children[$pt] ? $children[$pt] : array();
                array_push($list,$v);
                $children[$pt] = $list;
            }

            $collection = $this->gTreeRecurse(0, array(), $children, 9999, 0);

            if( isset($collection[$parentId]->children) )
            {
                $result = $collection[$parentId]->children;
				$result = $this->flattenNestedList($result);
            }
            else
            {
                $result = array();
            }
        }

        JArrayHelper::toInteger($result);

        return $result;
	}
	
	function gTreeRecurse($id, $list, &$children, $maxlevel=9999, $level=0)
	{
	    if (@$children[$id] && $level <= $maxlevel)
    	{
    		foreach ($children[$id] as $v)
    		{
    			$id = $v->id;

    			$list[$id] = $v;

    	        if($v->parent != $id)
    	        {
    		        $list[$v->parent]->children[$v->id] = $v;
    			}
    			else
    			{
        			$list[$id]->children = array();
    			}

    			$list = $this->gTreeRecurse($id, $list, $children, $maxlevel, $level+1);
    		}
    	}
    	return $list;
	}

	function flattenNestedList($children, $needle = false, $collection = array())
	{
	    foreach($children as $k => $v)
        {
            if(!empty($v->children))
            {
                $collection = $this->flattenNestedList($v->children,$needle,$collection);
            }

            if(is_array($needle)) {
                $ret = array();
                foreach($needle as $n)
                {
                    $ret[$n] = $v->$n;
                }
                $collection[] = $ret;
            }
            else
            {
                $collection[] = $v->id;
            }
        }

        return $collection;
    }

}