<?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 TableMenu extends JTable {
    var $id = null,
    	$category_id = null,
    	$ordering = null,
    	$name = null,
		$published = null,
		$image = null,
        $image_size = null,
		$description = null,
		$created = null,
		$price = null,
		$special_price = null,
		$special_descr = null,
		$weight = null,
		$energy = null,
		$is_meal_of_the_day = null,
		$is_new = null,
		$is_recommended = null,
        $lang = null,
		$has_vat = null,
		$is_online = null,
		$params = null;

	var $_category_name = null,
		$_category_ordering = null,
        $_prices_exists = null,
        $_prices = null,
		$_groups = null,
		$_groups_exists = null,
		$_images_qty = null,
		$_images = null;

    function __construct(&$db) {
		$this->params = new JRegistry();
        parent::__construct('#__fwfoodmenu_menu', 'id', $db);
    }

    function load($keys = NULL, $reset = true) {
		if ($keys and is_numeric($keys)) {
			$app = JFactory::getApplication();
			$extras = $app->triggerEvent('onGetMenuExtraFields', array('com_fwfoodmenu'));

			$db = JFactory::getDBO();
			$db->setQuery('
SELECT
	m.*,
	c.name AS _category_name,
	c.ordering AS _category_ordering,
	(SELECT COUNT(*) FROM #__fwfoodmenu_menu_price AS mp WHERE mp.menu_id = m.id) AS _prices_exists
    '.implode('', $extras).'
FROM
	#__fwfoodmenu_menu AS m
	LEFT JOIN #__fwfoodmenu_category AS c ON c.id = m.category_id
WHERE
	m.id = '.(int)$keys);
			if ($obj = $db->loadObject()) {
				foreach ($obj as $key => $val) $this->$key = $val;
				if ($this->_prices_exists) {
					$db = JFactory::getDBO();
					$db->setQuery('SELECT * FROM `#__fwfoodmenu_menu_price` WHERE menu_id = '.(int)$this->id.' ORDER BY `ordering`');
					$this->_prices = $db->loadObjectList();
					foreach ($this->_prices as $j=>$price) {
						$this->_prices[$j]->_price = fwFoodMenuHelper::formatPrice(($price->special_price>0)?$price->special_price:$price->price);
					}
				}
                $this->params = new JRegistry($this->params);
				$app->triggerEvent('onLoadMenu', array('com_fwfoodmenu', $this));
				return true;
			}
		}
    }

    function bind($data, $skip=array()) {
        if ($data) {
            $app = JFactory::getApplication();
            $app->triggerEvent('onBindMenu', array('com_fwfoodmenu', $data, &$skip, $this));

			$keys = array_keys($this->getProperties());
            foreach ($data as $key=>$val) {
                if (!in_array($key, $keys) or ($skip and in_array($key, $skip))) {
                    continue;
                }
                $this->$key = $val;
            }
		}
        return true;
    }
    function check() {
		$db = JFactory::getDBO();
		jimport('joomla.filesystem.file');

		if (!$this->id) {
			if (!$this->ordering) {
//					$db->setQuery('SELECT MAX(ordering) FROM `#__fwfoodmenu_menu` WHERE category_id = '.(int)$this->category_id);
				$db->setQuery('SELECT MAX(ordering) FROM `#__fwfoodmenu_menu`');
				$this->ordering = 1 + (int)$db->loadResult();
			}
		}
		$data = JFactory::getApplication()->triggerEvent('onCheckMenu', array('com_fwfoodmenu', $this));
		if ($data) {
			foreach ($data as $row) {
				if (!$row) {
					return;
				}
			}
		}
		$params = new JRegistry($this->params);
		$this->params = $params->toString();
		return true;
    }
    function store($updn=null) {
		$is_new = !$this->id;
	    if (parent::store($updn)) {
			$db = JFactory::getDBO();
			$app = JFactory::getApplication();
			$input = $app->input;
			if ($input->getCmd('task') != 'copy') {
				if (!in_array($input->getCmd('format'), array('json', 'raw')) or $input->getCmd('layout') == 'quick_meals') {
					$pids = array();
					if ($this->_prices) {
						foreach ($this->_prices as $price) {
							$pids[] = $price->id;
						}
					}
					if ($prices = $input->getVar('prices')) {
						$i = 0;

						foreach ($prices as $p=>$row) {
							if (empty($row['name']) and empty($row['price']) and empty($row['special_price'])) {
								continue;
							}

							$p_fields = array(
								'menu_id' => $this->id,
								'ordering' => $i,
								'name' => @$row['name'],
								'price' => (float)@$row['price'],
								'special_price' => (float)@$row['special_price']
							);

							$app->triggerEvent('onBindMealPrice', array('com_fwfoodmenu', &$p_fields, $this->lang));

							$query = '';
							foreach ($p_fields as $key=>$val) {
								$query .= ($query?',':'').'`'.$key.'`='.$db->quote($val);
							}

							if (empty($row['id'])) {
								$db->setQuery('
INSERT INTO
	`#__fwfoodmenu_menu_price`
SET
	'.$query);
							} else {
								$key = array_search($row['id'], $pids);
								if ($key !== false) {
									unset($pids[$key]);
								}
								$db->setQuery('
UPDATE
	`#__fwfoodmenu_menu_price`
SET
	'.$query.'
WHERE
    `id` = '.(int)$row['id']);
							}
							if ($db->execute()) {
								if (empty($row['id'])) {
									$prices[$p]['id'] = $db->insertid();
								}
							}
							$i++;
						}
						$input->set('prices', $prices);
					}
					if ($pids) {
						$db->setQuery('DELETE FROM `#__fwfoodmenu_menu_price` WHERE id IN ('.implode(',', $pids).')');
						$db->execute();
						$app->triggerEvent('onDeleteMenuPrices', array('com_fwfoodmenu', $this, $pids));
					}
				}
				$app->triggerEvent('onStoreMenu', array('com_fwfoodmenu', $this, $is_new));
			}
            return true;
        }
    }
    function delete($oid = null) {
    	if ((int)$oid and $this->load($oid) and parent::delete($oid)) {
			$db = JFactory::getDBO();
			if ($this->_prices_exists) {
				$db->setQuery('DELETE FROM `#__fwfoodmenu_menu_price` WHERE menu_id = '.(int)$this->id);
				$db->execute();
				$pids = array();
				if ($this->_prices) {
					foreach ($this->_prices as $price) {
						$pids[] = $price->id;
					}
				}
				JFactory::getApplication()->triggerEvent('onDeleteMenuPrices', array('com_fwfoodmenu', $this, $pids));
			}
			JFactory::getApplication()->triggerEvent('onDeleteMenu', array('com_fwfoodmenu', $this));
    		return true;
    	} else $this->setError(JText::_('FWFM_NO_MENU_ID_PASSED'));
    }
}
