<?php
/**
 * FW Food menu 5.1.1
 * @copyright (C) 2020 Fastw3b
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
 * @link http://www.fastw3b.net/ Official website
 **/

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

class menuModelAdmin extends JModelLegacy {
    function login() {
        //
    }
    function _collectCategoriesWhere() {
		$where = array();
		$db = JFactory::getDBO();
        $app = JFactory::getApplication();
		if ($search = $db->escape($app->input->getString('search'))) {
			if ($buff = $app->triggerEvent('onGetCategoryNameSearch', array('com_fwfoodmenu', $search))) {
				foreach ($buff as $row) {
					if ($row) {
						$where[] = $row;
					}
				}
			} else {
				$where[] = "(c.name LIKE '%${search}%' OR c.description LIKE '%${search}%')";
			}
		}
		if ($category = (int)$app->input->getInt('category')) {
			$where[] = 'c.parent = '.$category;
		}
		if ($state = $app->input->getCmd('state')) {
			if ($state == 'published') {
				$where[] = 'c.published = 1';
			} elseif ($state == 'unpublished') {
				$where[] = 'c.published = 0';
			}
		}
		return $where?(' WHERE '.implode(' AND ', $where)):'';
    }
    function loadCategories() {
        $app = JFactory::getApplication();
		$input = $app->input;
		$where = $this->_collectCategoriesWhere();
		$db = JFactory::getDBO();
		$db->setQuery('SELECT c.id FROM `#__fwfoodmenu_category` AS c WHERE c.parent <> 0 AND NOT EXISTS(SELECT * FROM `#__fwfoodmenu_category` AS cc WHERE cc.id = c.parent)');
		if ($ids = $db->loadColumn()) {
			$db->setQuery('UPDATE `#__fwfoodmenu_category` SET parent = 0  WHERE id IN ('.implode(',', $ids).')');
			$db->execute();
		}
		$db->setQuery('
SELECT
    c.*,
	c.name AS treename,
	(SELECT COUNT(*) FROM #__fwfoodmenu_menu AS m WHERE m.category_id = c.id) AS _menu_qty
FROM
    #__fwfoodmenu_category AS c
'.$where.'
ORDER BY
	c.parent,
	c.ordering'
		);

		if ($rows = $db->loadObjectList()) {
			$ids = array();
			foreach ($rows as $i=>$row) {
				$ids[] = $row->id;
				$rows[$i]->params = new JRegistry($row->params);
			}
			JFactory::getApplication()->triggerEvent('onCalculateCategoryListExtraFields', array('com_fwfoodmenu', &$rows, $ids));
			if ($where) {
				return $rows;
			} else {
				$children = array();
				foreach ($rows as $v) {
					$pt = $v->parent;
					$list = @$children[$pt] ? $children[$pt] : array();
					array_push( $list, $v );
					$children[$pt] = $list;
				}
				$levellimit = 10;
				$list = JHTML::_('fwfCategory.treerecurse', 0, '', array(), $children, max( 0, $levellimit-1 ) );
//				if ($limit = $input->getInt('limit', $app->getCfg('list_limit'))) $list = array_slice($list, $input->getInt('limitstart'), $limit);
				return $list;
			}
		}
    }
    function saveCategory() {
        $category = $this->getTable('category');
		$input = JFactory::getApplication()->input;
        if ($id = $input->getInt('id') and !$category->load($id)) $input->set('id', 0);

        if ($category->bind($input->getArray(array(), null, 'RAW')) and $category->check() and $category->store()) {
            $this->setError(fwFoodMenuHelper::jtext('FWFM_CATEGORY_STORED_SUCCESSFULLY'));
            return $category->id;
        } else
        	$this->setError($category->getError());
    }
    function publishCategory() {
		$input = JFactory::getApplication()->input;
        if ($cid = (array)$input->getVar('cid')) {
            $category = $this->getTable('category');
            $category->publish($cid, 1);
            $this->setError(fwFoodMenuHelper::jtext('FWFM_CATEGORY_PUBLISHED'));
            return true;
        }
        $this->setError(fwFoodMenuHelper::jtext('FWFM_NO_CATEGORY_ID_PASSED_TO_PUBLISH'));
    }
    function unpublishCategory() {
		$input = JFactory::getApplication()->input;
        if ($cid = (array)$input->getVar('cid')) {
            $category = $this->getTable('category');
            $category->publish($cid, 0);
            $this->setError(fwFoodMenuHelper::jtext('FWFM_CATEGORY_UNPUBLISHED'));
            return true;
        }
        $this->setError(fwFoodMenuHelper::jtext('FWFM_NO_CATEGORY_ID_PASSED_TO_UNPUBLISH'));
    }
}