<?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 menuModelItems extends JModelLegacy {
	function _collectWhere() {
		$where = array();
		$db = JFactory::getDBO();
		$app = JFactory::getApplication();
		if ($search = $app->input->getString('search')) {
			$search = $db->escape(trim($search));
			if ($buff = $app->triggerEvent('onGetMealNameSearch', array('com_fwfoodmenu', $search))) {
				foreach ($buff as $row) {
					if ($row) {
						$where[] = $row;
					}
				}
			} else {
				$where[] = "(m.name LIKE '%${search}%' OR m.description LIKE '%${search}%')";
			}
		}
		if ($state = $app->input->getCmd('state')) {
			if ($state == 'published') {
				$where[] = 'm.published = 1';
			} elseif ($state == 'unpublished') {
				$where[] = 'm.published = 0';
			}
		}
		if ($buff = (int)$app->input->getInt('category')) $where[] = 'm.category_id = '.$buff;
		return $where?(' WHERE '.implode(' AND ', $where)):'';
	}
	function loadList() {
        $app = JFactory::getApplication();
		$input = $app->input;
		$db = JFactory::getDBO();

        $extras = $app->triggerEvent('onGetMenuListExtraFields', array('com_fwfoodmenu'));

        $db->setQuery('
SELECT
    m.*,
	(SELECT mi.image FROM `#__fwfoodmenu_menu_image` AS mi WHERE mi.menu_id = m.id ORDER BY mi.ordering LIMIT 1) AS image,
	c.name AS _category_name,
	\'\' AS _prices
    '.implode('', $extras).'
FROM
    #__fwfoodmenu_menu AS m
    LEFT JOIN #__fwfoodmenu_category AS c ON m.category_id = c.id
'.$this->_collectWhere().'
ORDER BY
	m.ordering',
			$input->getInt('limitstart'),
			$input->getInt('limit', $app->getCfg('list_limit'))
		);
        if ($list = $db->loadObjectList()) {
			$ids = array();
			foreach ($list as $i=>$row) {
				$ids[] = $row->id;
				$list[$i]->_prices = array();
			}
			$db = JFactory::getDBO();
			$db->setQuery('SELECT * FROM `#__fwfoodmenu_menu_price` WHERE menu_id IN ('.implode(',', $ids).') ORDER BY ordering');
			if ($buff = $db->loadObjectList()) {
				foreach ($buff as $row) {
					$key = array_search($row->menu_id, $ids);
					$list[$key]->_prices[] = $row;
				}
			}
			$app->triggerEvent('onCalculateMenuListExtraFields', array('com_fwfoodmenu', &$list, $ids));
			return $list;
		}
	}
	function loadQty() {
		$db = JFactory::getDBO();
        $db->setQuery('
SELECT
    COUNT(*)
FROM
    #__fwfoodmenu_menu AS m
    LEFT JOIN #__fwfoodmenu_category AS c ON m.category_id = c.id
'.$this->_collectWhere());
        return $db->loadResult();
	}
	function getPagination() {
        $app = JFactory::getApplication();
		$input = $app->input;
        jimport('joomla.html.pagination');
		return new JPagination(
			$this->loadQty(),
			$input->getInt('limitstart'),
			$input->getInt('limit', $app->getCfg('list_limit'))
		);
	}
	function loadObject() {
        $menu = $this->getTable('menu');
		$input = JFactory::getApplication()->input;
        if (($ids = (array)$input->getVar('cid') and $id = JArrayHelper::getValue($ids, 0)) or $id = $input->getInt('id', 0)) {
            $menu->load($id);
        } else if ($category_id = $input->getInt('category')) {
        	$menu->category_id = $category_id;
        }
        return $menu;
	}
    function save() {
        $menu = $this->getTable('menu');
		$input = JFactory::getApplication()->input;
        if ($id = $input->getInt('oid')) {
			$menu->load($id);
		}
        if ($menu->bind($input->getArray(array(), null, 'RAW'), array('id')) and $menu->check() and $menu->store()) {
            $this->setError(JText::_('FWFM_MENU_STORED_SUCCESSFULLY'));
            return $menu->id;
        } else
        	$this->setError($menu->getError());
    }
	function save2copy() {
		$app = JFactory::getApplication();
		$id = $app->input->getInt('oid');

		$menu = $this->getTable('menu');
		if ($menu->bind($app->input->getArray(array(), null, 'RAW'), array('id', 'published', 'ordering'))) {
			$menu->id = 0;
			$menu->published = 0;
			$menu->name .= ' (copy)';
			/* copy prices */
			if ($prices = $app->input->getVar('prices')) {
				foreach ($prices as $i=>$price) {
					if (!empty($price['id'])) {
						$prices[$i]['src_id'] = $price['id'];
						$prices[$i]['id'] = 0;
					}
				}
				$app->input->set('prices', $prices);
			}
			if ($menu->check() and $menu->store()) {
				$app->triggerEvent('onSave2copyMenuExtraFields', array('com_fwfoodmenu', $menu, $id));
				$this->setError(JText::_('FWFM_MENU_COPIED'));
				return $menu->id;
			} else $this->setError($menu->getError());
		} else $this->setError($menu->getError());
	}
	function batch() {
		$app = JFactory::getApplication();

		$input = $app->input;
		if ($cid = (array)$input->getVar('cid')) {
			$db = JFactory::getDBO();
			JArrayHelper::toInteger($cid, 0);
			$changes_requested = false;

			if ($data = $input->getInt('category_id')) {
				$changes_requested = true;
				$db->setQuery('UPDATE `#__fwfoodmenu_menu` SET `category_id` = '.(int)$data.' WHERE id IN ('.implode(',', $cid).')');
				$db->execute();
			}
			if ($data = $input->getInt('published')) {
				$changes_requested = true;
				$db->setQuery('UPDATE `#__fwfoodmenu_menu` SET published = '.(($data == 1)?1:0).' WHERE id IN ('.implode(',', $cid).')');
				$db->execute();
			}

			$app->triggerEvent('onDoBatchProcessing', array('com_fwfoodmenu', $cid, &$changes_requested, $this));

			return true;
		}
		$this->setError(JText::_('FWFM_NO_MENU_ID_PASSED_TO_PROCESS'));
	}
	function copy() {
		$app = JFactory::getApplication();
		$input = $app->input;
        if ($cid = (array)$input->getVar('cid')) {
			jimport('joomla.filesystem.file');
			$db = JFactory::getDBO();
            $menu = $this->getTable('menu');
            foreach ($cid as $id) {
                if ($menu->load($id)) {
					$menu->id = 0;
					$menu->ordering = 0;
					$menu->published = 0;
					$menu->name .= ' (copy)';
					if ($menu->check() and $menu->store()) {
						if ($menu->_prices) {
							$db = JFactory::getDBO();
							foreach ($menu->_prices as $i=>$price) {
								$db->setQuery('INSERT INTO `#__fwfoodmenu_menu_price` SET menu_id = '.(int)$menu->id.', ordering = '.(int)$price->ordering.', name = '.$db->quote($price->name).', size = '.$db->quote($price->size).', price = '.$db->quote($price->price).', special_price = '.$db->quote($price->special_price).', energy = '.$db->quote($price->energy));
								if ($db->execute()) {
									$menu->_prices[$i]->new_id = $db->insertid();
								}
							}
						}
						$app->triggerEvent('onCopyMenuExtraFields', array('com_fwfoodmenu', $menu, $id));
					} else $this->setError($menu->getError());
				}
            }
            $this->setError(JText::_('FWFM_MENU_COPIED'));
            return true;
        }
        $this->setError(JText::_('FWFM_NO_MENU_ID_PASSED_TO_COPY'));
    }
    function remove() {
		$input = JFactory::getApplication()->input;
        if ($cid = (array)$input->getVar('cid')) {
            $menu = $this->getTable('menu');
            foreach ($cid as $id) {
                $menu->delete($id);
            }
            $this->setError(JText::_('FWFM_MENU_REMOVED'));
            return true;
        }
        $this->setError(JText::_('FWFM_NO_MENU_ID_PASSED_TO_REMOVE'));
    }
    function saveOrder() {
		$input = JFactory::getApplication()->input;
        $cid = $input->getVar('cid');
        $order = $input->getVar('order');

        if (is_array($cid) and is_array($order) and count($cid) and count($cid) == count($order)) {
            $db = JFactory::getDBO();
            foreach ($cid as $num=>$id) {
				$odering = (int)JArrayHelper::getValue($order, $num);
				$db->setQuery('UPDATE #__fwfoodmenu_menu SET ordering = '.$odering.' WHERE id = '.(int)$id);
				$db->execute();
            }
            $menu = $this->getTable('menu');
			$menu->reorder();
            return true;
        }
    }
    function orderDown() {
		$input = JFactory::getApplication()->input;
        if ($cid = (array)$input->getVar('cid') and $id = JArrayHelper::getValue($cid, 0)) {
            $menu = $this->getTable('menu');
            $menu->load($id);
            $menu->move(1);
            return true;
        }
    }
    function orderup() {
		$input = JFactory::getApplication()->input;
        if ($cid = (array)$input->getVar('cid') and $id = JArrayHelper::getValue($cid, 0)) {
            $menu = $this->getTable('menu');
            $menu->load($id);
            $menu->move(-1);
            return true;
        }
    }
    function publish() {
		$input = JFactory::getApplication()->input;
        if ($cid = (array)$input->getVar('cid')) {
            $menu = $this->getTable('menu');
            $menu->publish($cid, 1);
            $this->setError(JText::_('FWFM_MENU_PUBLISHED'));
            return true;
        }
        $this->setError(JText::_('FWFM_NO_MENU_ID_PASSED_TO_PUBLISH'));
    }
    function unPublish() {
		$input = JFactory::getApplication()->input;
        if ($cid = (array)$input->getVar('cid')) {
            $menu = $this->getTable('menu');
            $menu->publish($cid, 0);
            $this->setError(JText::_('FWFM_MENU_UNPUBLISHED'));
            return true;
        }
        $this->setError(JText::_('FWFM_NO_MENU_ID_PASSED_TO_UNPUBLISH'));
    }
    function mealDay() {
		$input = JFactory::getApplication()->input;
        if ($cid = (array)$input->getVar('cid')) {
			JArrayHelper::toInteger($cid, 0);
			$db = JFactory::getDBO();
			$db->setQuery('UPDATE #__fwfoodmenu_menu SET is_meal_of_the_day = 1 WHERE id IN ('.implode(',', $cid).')');
			$db->execute();
            $this->setError(JText::_('FWFM_MENU_SET_AS_mealday'));
            return true;
        }
        $this->setError(JText::_('FWFM_NO_MENU_ID_PASSED_TO_SET_AS_mealday'));
    }
    function unMealDay() {
		$input = JFactory::getApplication()->input;
        if ($cid = (array)$input->getVar('cid')) {
			JArrayHelper::toInteger($cid, 0);
			$db = JFactory::getDBO();
			$db->setQuery('UPDATE #__fwfoodmenu_menu SET is_meal_of_the_day = 0 WHERE id IN ('.implode(',', $cid).')');
			$db->execute();
            return true;
        }
        $this->setError(JText::_('FWFM_NO_MENU_ID_PASSED_TO_UNSET_AS_mealday'));
    }
    function asNew() {
		$input = JFactory::getApplication()->input;
        if ($cid = (array)$input->getVar('cid')) {
			JArrayHelper::toInteger($cid, 0);
			$db = JFactory::getDBO();
			$db->setQuery('UPDATE #__fwfoodmenu_menu SET is_new = 1 WHERE id IN ('.implode(',', $cid).')');
			$db->execute();
            $this->setError(JText::_('FWFM_MENU_SET_AS_new'));
            return true;
        }
        $this->setError(JText::_('FWFM_NO_MENU_ID_PASSED_TO_SET_AS_NEW'));
    }
    function unNew() {
		$input = JFactory::getApplication()->input;
        if ($cid = (array)$input->getVar('cid')) {
			JArrayHelper::toInteger($cid, 0);
			$db = JFactory::getDBO();
			$db->setQuery('UPDATE #__fwfoodmenu_menu SET is_new = 0 WHERE id IN ('.implode(',', $cid).')');
			$db->execute();
            return true;
        }
        $this->setError(JText::_('FWFM_NO_MENU_ID_PASSED_TO_UNSET_AS_NEW'));
    }
    function asrecommended() {
		$input = JFactory::getApplication()->input;
        if ($cid = (array)$input->getVar('cid')) {
			JArrayHelper::toInteger($cid, 0);
			$db = JFactory::getDBO();
			$db->setQuery('UPDATE #__fwfoodmenu_menu SET is_recommended = 1 WHERE id IN ('.implode(',', $cid).')');
			$db->execute();
            $this->setError(JText::_('FWFM_MENU_SET_AS_RECOMMENDED'));
            return true;
        }
        $this->setError(JText::_('FWFM_NO_MENU_ID_PASSED_TO_SET_AS_RECOMMENDED'));
    }
    function unrecommended() {
		$input = JFactory::getApplication()->input;
        if ($cid = (array)$input->getVar('cid')) {
			JArrayHelper::toInteger($cid, 0);
			$db = JFactory::getDBO();
			$db->setQuery('UPDATE #__fwfoodmenu_menu SET is_recommended = 0 WHERE id IN ('.implode(',', $cid).')');
			$db->execute();
            $this->setError(JText::_('FWFM_MENU_UNSET_AS_RECOMMENDED'));
            return true;
        }
        $this->setError(JText::_('FWFM_NO_MENU_ID_PASSED_TO_UNSET_AS_RECOMMENDED'));
    }
	function quickMeals() {
		$input = JFactory::getApplication()->input;
		if ($text = $input->getString('text')) {
			$db = JFactory::getDBO();
			$data = explode("\n", str_replace("\r", '', $text));

			$cid = $input->getInt('category');
			if (!$cid) {
				$this->setError(JText::_('FWFM_SELECT_CATEGORY'));
				return;
			}

			$updated = $added = 0;

			foreach ($data as $row) {
				$buff = explode('=', $row, 3);
				$name = trim($buff[0]);
				if (empty($name)) {
					continue;
				}

				$price = empty($buff[1])?'':trim($buff[1]);
				$descr = empty($buff[2])?'':('<p>'.trim($buff[2]).'</p>');

				$db->setQuery('
SELECT
	(SELECT id FROM #__fwfoodmenu_menu WHERE name = '.$db->quote($name).' AND category_id = '.(int)$cid.') AS mid,
	(SELECT MAX(ordering) FROM #__fwfoodmenu_menu WHERE category_id = '.(int)$cid.') AS ordering');
				if ($obj = $db->loadObject()) {
					$mid = $obj->mid;
					$meal = $this->getTable('menu');
					$meal->id = 0;
					if ($mid) {
						$meal->load($mid);
					}
					$is_new = !$meal->id;
					$data = array('lang'=>$meal->lang?$meal->lang:fwFoodMenuHelper::getLanguage());
					if (!$meal->id) {
						$data['name'] = $name;
						$data['published'] = 1;
						$data['category_id'] = $cid;
						$data['ordering'] = $obj->ordering + 1;
					}
					if ($descr) {
						$data['description'] = $descr;
					}
					$prices = array();
					$list = explode('+', $price);
					foreach ($list as $price) {
						$price = explode('|', $price);
						$price[0] = trim($price[0]);
						if ($price[0] > 0) {
							$prices[] = array(
								'price' => $price[0],
								'name' => empty($price[1])?'':trim($price[1])
							);
						}
					}

					$input->set('prices', $prices);
					if ($meal->bind($data) and $meal->check() and $meal->store()) {
						if ($is_new) {
							$added++;
						} else {
							$updated++;
						}
					} else {
						$this->setError($meal->getError());
					}
				} else {
					$this->setError($db->getError());
				}
			}
			if ($added and $updated) {
				$this->setError(JText::sprintf('FWFM_MEAL_QUICK_IMPORT_RESULT_ADDED_EXISTED', $added, $updated));
			} elseif ($added) {
				$this->setError(JText::sprintf('FWFM_MEAL_QUICK_IMPORT_RESULT_ADDED', $added));
			} elseif ($updated) {
				$this->setError(JText::sprintf('FWFM_MEAL_QUICK_IMPORT_RESULT_EXISTED', $updated));
			} else {
				$this->setError(JText::_('FWFM_MEAL_QUICK_IMPORT_RESULT'));
			}
			return true;
		} else $this->setError(JText::_('FWFM_NOTHING_TO_PROCESS'));
	}
}
