<?php
/**
 * @license		GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
 */

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

jimport('joomla.html.html');
jimport('joomla.form.formfield');
jimport('joomla.form.helper');


class JFormFieldK2Categories extends JFormField{


	public $type = 'k2categories';

	protected function getInput()
	{
		$attr = '';

		// Initialize some field attributes.
		$attr .= $this->element['class'] ? ' class="'.(string) $this->element['class'].'"' : '';

		// To avoid user's confusion, readonly="true" should imply disabled="true".
		if ( (string) $this->element['readonly'] == 'true' || (string) $this->element['disabled'] == 'true') {
			$attr .= ' disabled="disabled"';
		}

		$attr .= $this->element['size'] ? ' size="'.(int) $this->element['size'].'"' : '';
		$attr .= $this->multiple ? ' multiple="multiple"' : '';

		// Initialize JavaScript field attributes.
		$attr .= $this->element['onchange'] ? ' onchange="'.(string) $this->element['onchange'].'"' : '';
		
		
		$db = JFactory::getDBO();
		$tables = $db->getTableList();
		$k2installed = false;
		foreach($tables as $table)
		{
			$pos = stripos($table,'k2_categories');
			if($pos !== false)
			{
				$k2installed = true;
			}
		}
		if(!$k2installed){return '';}
		$query = $db->getQuery(true);
		$query->select('id, name as title, parent as parent_id');
		$query->from('#__k2_categories');
		$query->where('published=1 AND trash=0');
        $query->order('parent, ordering');		
		$db->setQuery( $query );
		
		if(!$results = $db->loadObjectList())
		{
			return JTEXT::_('K2NOCATEGORIES');
		}
		if(count($results) == 0)
		{
			return JTEXT::_('K2NOCATEGORIES');
		}
		
		$mitems = array();
		$mitem = new stdClass();
		$mitem->id = '';
		$mitem->title = JText::_("ALLCATEGORIES");
		$mitems[] = $mitem;
		
		
		foreach($results as &$result)
		{
		  if($result->parent_id >0)
		  {
			 break; //we have exhausted all the top level categories, the rest are children that should already be in tree
		  }
		  $result->level = 0;
		  $mitems[] = $result;
		  $level = 0;
		  self::getChildren($mitems, $results, $result->id, $level); 
		}
		
		
		return JHTML::_('select.genericlist',  $mitems, $this->name, trim($attr), 'id', 'title', $this->value );
		
		
	}
	
	
    private function getChildren(&$rows, &$results, $parent_id, $level)
	{
		$localLevel = $level+1;
		$found = false;
		foreach($results as $result)
		{
			if($result->parent_id == $parent_id)
			{
				$found = true;
				$result->level = $localLevel;
				$result->title = str_repeat("-",$localLevel).$result->title;
				$rows[] = $result;
				$this->getChildren($rows, $results, $result->id, $localLevel);
			}
			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
				}
			}
		}
		
	}
	
}
