<?php
/*
 * @package Sj K2 Filter
 * @version 1.1.0
 * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @copyright (c) 2016 YouTech Company. All Rights Reserved.
 * @author YouTech Company http://www.smartaddons.com
 *
 */

defined('_JEXEC') or die('Restricted access');

class JFormFieldK2Category extends JFormField
{
    var $type = 'K2category';

    function getInput()
    {
    	$document = JFactory::getDocument();
		if($this->multiple) {
			$document->addScriptDeclaration('
			function selectedparents(obj){
				var percats = obj.getSelected().getProperty("percat").toString().split(",");
				percats.unique().each(function(parentsid){
					if(parentsid >0){
						for (var i = 0; i < obj.options.length; i++)
						{
							if (obj.options[i].value === parentsid)
							{
								if(!obj.options[i].selected){
									obj.options[i].set("selected","selected");
									selectedparents(obj);
									break;
								}
							}
						}
					}
				});
			}');
		}

        $flag = false;
        if (!$this->checkComponent('com_k2')) {
			return '<input type="hidden" name="' . $this->name . '" id="' . $this->id . '"/>
					<span style="color:red; float:left">K2 component is not installed!</span>';
        }

		$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'] . '"' : '';

        $categories = JFormFieldK2Category::_fetchElement(0, '', array());
        $HTMLSelect = '<select onchange="return selectedparents(this);" name="' . $this->name . '" id="' . $this->id . '" '.$attr.'>';

        $HTMLCats = '';
        $value = $this->value;
        foreach ($categories as $item) {
			if(isset($item->id) && $item->id > 0){
				$check = '';
				if ((is_array($value) && in_array($item->id, $value)) || (!is_array($value) && $item->id == $value)) {
					$flag = true;
					$check = 'selected="selected"';
				}

				$class = ' percat="'.$item->parent.'"';

				if ($item->parent != 0)
					$class = ' class="subcat" percat="'.$item->parent.'" ';

				$HTMLCats .= '<option value="' . $item->id . '" ' . $check . ' ' . $class . '>' . '&nbsp;&nbsp;&nbsp;' . $item->treename . ' (ID: ' . $item->id . ')' . '</option>';
			}	
        }
        if ($flag == true) {
            $HTMLSelect .= '<option value="0">' . JText::_("MOD_K2_FILTER_ALL_CATEGORY") . '</option>';
        } else {
            $HTMLSelect .= '<option value="0" selected="selected">' . JText::_("MOD_K2_FILTER_ALL_CATEGORY") . '</option>';
        }
        $HTMLSelect .= $HTMLCats;
        $HTMLSelect .= '</select>';
        return $HTMLSelect;
    }


    function fetchChild($parent)
    {
        $mainframe = JFactory::getApplication();
    	$user = JFactory::getUser();
        $aid = (int)$user->get('aid');
    	$db = JFactory::getDBO();
        $query = "SELECT * FROM #__k2_categories WHERE parent = '{$parent}' ";
    	$query .= " AND published=1 
								AND trash=0";
        $query .=" ORDER BY ordering ASC";
        $db->setQuery($query);
        $cats = $db->loadObjectList();

        return $cats;
    }


    function _fetchElement($id, $indent, $list, $maxlevel = 9999, $level = 0, $type = 1)
    {
        $children = JFormFieldK2Category::fetchChild($id);

        if (@$children && $level <= $maxlevel) {
            foreach ($children as $v) {
                $id = $v->id;

                if ($type) {
                    $pre = '<sup>|_</sup>&nbsp;';
                    $spacer = '.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                } else {
                    $pre = '- ';
                    $spacer = '&nbsp;&nbsp;';
                }

                if ($v->parent == 0) {
                    $txt = $v->name;
                } else {
                    $txt = $pre . $v->name;
                }
                $pt = $v->parent;
                $list[$id] = $v;
                $list[$id]->treename = "{$indent}{$txt}";
                $list[$id]->children = count(@$children);
                $list[$id]->haschild = true;
                $list = JFormFieldK2Category::_fetchElement($id, $indent . $spacer, $list, $maxlevel, $level + 1, $type);
            }
        } else {
			if(isset($list[$id])) {
				$list[$id]->haschild = false;
			}
        }
        return $list;
    }


    function checkComponent($component)
    {
        $db = JFactory::getDBO();
        $query = " SELECT Count(*) FROM #__extensions as e WHERE e.element ='$component' and e.enabled=1";
        $db->setQuery($query);
	    return $db->loadResult();
    }
}