<?php

	/*
		Shopping list created by Jens Schröder
		See https://server47.de for more information.
	*/

	require_once("shoppingListConfig.php");

	$justCreatedProductId;

	$iconDelete = "❌";
	$iconSave = "💾";



/*
		 ▄▄▄▄▄▄▄ ▄▄▄     ▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ 
		█       █   █   █      █       █       █       █       █
		█       █   █   █  ▄   █  ▄▄▄▄▄█  ▄▄▄▄▄█    ▄▄▄█  ▄▄▄▄▄█
		█     ▄▄█   █   █ █▄█  █ █▄▄▄▄▄█ █▄▄▄▄▄█   █▄▄▄█ █▄▄▄▄▄ 
		█    █  █   █▄▄▄█      █▄▄▄▄▄  █▄▄▄▄▄  █    ▄▄▄█▄▄▄▄▄  █
		█    █▄▄█       █  ▄   █▄▄▄▄▄█ █▄▄▄▄▄█ █   █▄▄▄ ▄▄▄▄▄█ █
		█▄▄▄▄▄▄▄█▄▄▄▄▄▄▄█▄█ █▄▄█▄▄▄▄▄▄▄█▄▄▄▄▄▄▄█▄▄▄▄▄▄▄█▄▄▄▄▄▄▄█

		 ▄▄▄▄▄▄  ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄    ▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄    ▄ ▄▄▄▄▄▄▄ 
		█      ██       █       █   █  █  █ █   █       █   █       █  █  █ █       █
		█  ▄    █    ▄▄▄█    ▄▄▄█   █   █▄█ █   █▄     ▄█   █   ▄   █   █▄█ █  ▄▄▄▄▄█
		█ █ █   █   █▄▄▄█   █▄▄▄█   █       █   █ █   █ █   █  █ █  █       █ █▄▄▄▄▄ 
		█ █▄█   █    ▄▄▄█    ▄▄▄█   █  ▄    █   █ █   █ █   █  █▄█  █  ▄    █▄▄▄▄▄  █
		█       █   █▄▄▄█   █   █   █ █ █   █   █ █   █ █   █       █ █ █   █▄▄▄▄▄█ █
		█▄▄▄▄▄▄██▄▄▄▄▄▄▄█▄▄▄█   █▄▄▄█▄█  █▄▄█▄▄▄█ █▄▄▄█ █▄▄▄█▄▄▄▄▄▄▄█▄█  █▄▄█▄▄▄▄▄▄▄█

*/

	class DBLink
	{
		static $sqlLink = null;

		public static function getDbLink()
		{
			if(DBLink::$sqlLink == null)
			{
				DBLink::$sqlLink = new mysqli(Configuration::$mysqlserver, Configuration::$mysqluser, Configuration::$mysqlpw, Configuration::$mysqldb, Configuration::$mysqlPort);

				// Verbindung überprüfen
				if (mysqli_connect_errno())
				{
				  printf("Database connection error:%s\n", mysqli_connect_error());
				  exit();
				}
			}
			
			return DBLink::$sqlLink;
		}
	}

	if(isset($_GET['command']))
	{
		if($_GET['command'] == "printProductList" || $_GET['command'] == "printRhasspyProductList")
		{
			displayProductList();
			exit(0);
		}
		else if($_GET['command'] == "printUnitList")
		{
			displayUnitList();
			exit(0);
		}
	}
	
	class Unit
	{
		private $id;
		private $name;
		private $abbreviation;
		private $isDefault;
		private $isDummy;
		private $isPiece;

		public function setID($id)
		{
			$this->id = $id;
		}
		public function getID()
		{
			return $this->id;
		}

		public function setName($name)
		{
			$this->name = $name;
		}
		public function getName()
		{
			return $this->name;
		}
		
		public function setAbbreviation($abbreviation)
		{
			$this->abbreviation = $abbreviation;
		}
		public function getAbbreviation()
		{
			return $this->abbreviation;
		}
		
		public function setDefault($isDefault)
		{
			$this->isDefault = $isDefault;
		}
		public function isDefault()
		{
			return $this->isDefault;
		}
		
		public function setDummy($isDummy)
		{
			$this->isDummy = $isDummy;
		}
		public function isDummy()
		{
			return $this->isDummy;
		}
		
		public function setPiece($isPiece)
		{
			$this->isPiece = $isPiece;
		}
		public function isPiece()
		{
			return $this->isPiece;
		}

		public function getMainName()
		{
			$unitNamesArray = explode(";", $name);
			return $unitNamesArray[0];
		}

		private function ensurePlausibility()
		{
			$SQL_commands = "";

			if($this->isDefault())
				$SQL_commands .= "UPDATE units SET isDefault=0 WHERE NOT id=".$this->getID().";";
			
			if($this->isDummy())
				$SQL_commands .= "UPDATE units SET isDummy=0 WHERE NOT id=".$this->getID().";";

			if(strlen($SQL_commands) > 0)
			{
				$mysqli_result = DBLink::getDbLink()->query($SQL_commands);

				if ($mysqli_result)
					return true;

				return false;
			}
			else
				return true;
		}

		public static function getById($unitId)
		{
			$allUnits = Unit::getAllUnits();

			foreach($allUnits as $unit)
			{
				if($unit->getID() === $unitId)
				{
					return $unit;
				}
			}

			return null;
		}

		public function create()
		{
			$SQL_command = "INSERT INTO units (name, abbreviation, isDefault, isDummy, isPiece) VALUES (\"".$this->getName()."\", \"".$this->getAbbreviation()."\", ";
			
			if($this->isDefault())
				$SQL_command .= "1, ";
			else
				$SQL_command .= "0, ";
			
			if($this->isDummy())
				$SQL_command .= "1, ";
			else
				$SQL_command .= "0, ";
			
			if($this->isPiece())
				$SQL_command .= "1)";
			else
				$SQL_command .= "0)";

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($mysqli_result)
			{
				$this->ensurePlausibility();
				return true;
			}

			return false;
		}

		public function change()
		{
			$SQL_command = "UPDATE units SET name=\"".$this->getName()."\", abbreviation=\"".$this->getAbbreviation()."\", ";
			
			if($this->isDefault())
				$SQL_command .= "isDefault=1, ";
			else
				$SQL_command .= "isDefault=0, ";
			
			if($this->isDummy())
				$SQL_command .= "isDummy=1, ";
			else
				$SQL_command .= "isDummy=0, ";
			
			if($this->isPiece())
				$SQL_command .= "isPiece=1";
			else
				$SQL_command .= "isPiece=0";
			
			$SQL_command .= " WHERE id=".$this->getID();

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($mysqli_result)
			{
				$this->ensurePlausibility();
				return true;
			}

			return false;
		}

		public function delete()
		{
			$SQL_command = "DELETE FROM units WHERE id=".$this->getID();

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($mysqli_result)
				return true;

			return false;
		}

		public function getUsage()
		{
			$SQL_command = "SELECT COUNT(listId) as entryAmount FROM listEntries WHERE unit=".$this->getID();

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($row = mysqli_fetch_object($mysqli_result))
				return $row->entryAmount;
			
			return 0;
		}

		public static function getAllUnits()
		{
			$SQL_command = "SELECT * FROM units ORDER BY units.name ASC";
			
			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			$returnList = array();

			while ($row = mysqli_fetch_object($mysqli_result))
			{
				$newUnit = new Unit();

				$newUnit->setID($row->id);
				$newUnit->setName($row->name);
				$newUnit->setAbbreviation($row->abbreviation);
				$newUnit->setDefault($row->isDefault == 1);
				$newUnit->setDummy($row->isDummy == 1);
				$newUnit->setPiece($row->isPiece == 1);

				$returnList[] = $newUnit;
			}

			return $returnList;
		}
	}

	class StoreType
	{
		private $id;
		private $name;

		private static $storeTypesCache = null;

		public function setID($id)
		{
			$this->id = $id;
		}
		public function getID()
		{
			return $this->id;
		}

		public function setName($name)
		{
			$this->name = $name;
		}
		public function getName()
		{
			return $this->name;
		}

		public static function getById($storeTypeId)
		{
			$allStoreTypes = StoreType::getAllStoreTypes();

			foreach($allStoreTypes as $storeType)
			{
				if($storeType->getID() === $storeTypeId)
				{
					return $storeType;
				}
			}

			return null;
		}

		public function create()
		{
			$SQL_command = "INSERT INTO storeTypes (name) VALUES (\"".$this->getName()."\")";

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($mysqli_result)
				return true;

			return false;
		}

		public function change()
		{
			$SQL_command = "UPDATE storeTypes SET name=\"".$this->getName()."\" WHERE id=".$this->getID();

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($mysqli_result)
				return true;

			return false;
		}

		public function delete()
		{
			$SQL_command = "DELETE FROM storeTypes WHERE id=".$this->getID();

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($mysqli_result)
				return true;

			return false;
		}

		public function getUsage()
		{
			$SQL_command = "SELECT COUNT(name) as entryAmount FROM products WHERE storeTypeId=".$this->getID();

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($row = mysqli_fetch_object($mysqli_result))
				return $row->entryAmount;
			
			return 0;
		}

		public static function getAllStoreTypes()
		{
			if(StoreType::$storeTypesCache == null)
			{
				$SQL_command = "SELECT * FROM storeTypes ORDER BY storeTypes.name ASC";
				
				$mysqli_result = DBLink::getDbLink()->query($SQL_command);

				StoreType::$storeTypesCache = array();

				while ($row = mysqli_fetch_object($mysqli_result))
				{
					$newStoreType = new StoreType();

					$newStoreType->setID($row->id);
					$newStoreType->setName($row->name);

					StoreType::$storeTypesCache[] = $newStoreType;
				}
			}

			return StoreType::$storeTypesCache;
		}
	}

	class Product
	{
		private $id;
		private $name;
		private $synonyms;
		private $storeType;

		private static $productsCache = null;

		public function setID($id)
		{
			$this->id = $id;
		}
		public function getID()
		{
			return $this->id;
		}

		public function setName($name)
		{
			$this->name = $name;
		}
		public function getName()
		{
			return $this->name;
		}
		
		public function setSynonyms($synonyms)
		{
			$this->synonyms = $synonyms;
		}
		public function getSynonyms()
		{
			return $this->synonyms;
		}
		
		public function setStoreType(StoreType $storeType)
		{
			$this->storeType = $storeType;
		}
		public function getStoreType()
		{
			return $this->storeType;
		}

		public static function getById($productId)
		{
			$allProducts = Product::getAllProducts();

			foreach($allProducts as $product)
			{
				if($product->getID() === $productId)
				{
					return $product;
				}
			}

			return null;
		}

		public function create()
		{
			$syns = "NULL";
			if($this->getSynonyms() != null || strlen($this->getSynonyms()) > 0)
				$syns = "\"".$this->getSynonyms()."\"";

			$SQL_command = "INSERT INTO products (name, synonyms, storeTypeId) VALUES (\"".$this->getName()."\", ".$syns.", ".$this->getStoreType()->getID().")";
			
			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($mysqli_result)
			{
				return true;
			}

			return false;
		}

		public function change()
		{
			$syns = "NULL";
			if($this->getSynonyms() != null || strlen($this->getSynonyms()) > 0)
				$syns = "\"".$this->getSynonyms()."\"";

			$SQL_command = "UPDATE products SET name=\"".$this->getName()."\", synonyms=".$syns.", storeTypeId=".$this->getStoreType()->getID()." WHERE id=".$this->getID();

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($mysqli_result)
			{
				return true;
			}

			return false;
		}

		public function delete()
		{
			$SQL_command = "DELETE FROM products WHERE id=".$this->getID();

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($mysqli_result)
				return true;

			return false;
		}

		public function getUsage()
		{
			$SQL_command = "SELECT COUNT(listId) as entryAmount FROM listEntries WHERE productId=".$this->getID();

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($row = mysqli_fetch_object($mysqli_result))
				return $row->entryAmount;
			
			return 0;
		}

		public static function getAllProducts()
		{
			if(Product::$productsCache == null)
			{
/*				$productsAmount = 500;
				$SQL_command = "SELECT COUNT(name) as productsAmount FROM products";
				$mysqli_result = DBLink::getDbLink()->query($SQL_command);
				if($row = mysqli_fetch_object($mysqli_result))
					$amount = $row->productsAmount;
*/
				$SQL_command = "SELECT * FROM products ORDER BY products.name ASC";

				$mysqli_result = DBLink::getDbLink()->query($SQL_command);

//				Product::$productsCache = new SplFixedArray($productsAmount);
				Product::$productsCache = array();

//				$index = 0;
				while ($row = mysqli_fetch_object($mysqli_result))
				{
					$newProduct = new Product();

					$newProduct->setID($row->id);
					$newProduct->setName($row->name);
					$newProduct->setSynonyms($row->synonyms);
					$newProduct->setStoreType(StoreType::getById($row->storeTypeId));

					Product::$productsCache[] = $newProduct;
//					Product::$productsCache[$index] = $newProduct;
//					$index++;
				}
			}

			return Product::$productsCache;
		}
	}

	class ShoppingListEntry
	{
		private $parentList;
		private $product;
		private $amount;
		private $unit;

		public function setParentList($parentList)
		{
			$this->parentList = $parentList;
		}
		public function getParentList()
		{
			return $this->parentList;
		}

		public function setProduct(Product $product)
		{
			$this->product = $product;
		}
		public function getProduct()
		{
			return $this->product;
		}
		
		public function setAmount($amount)
		{
			$this->amount = $amount;
		}
		public function getAmount()
		{
			return $this->amount;
		}
		
		public function setUnit(Unit $unit)
		{
			$this->unit = $unit;
		}
		public function getUnit()
		{
			return $this->unit;
		}

		public function create()
		{
			$syns = "NULL";
			if($this->getSynonyms() != null || strlen($this->getSynonyms()) > 0)
				$syns = "\"".$this->getSynonyms()."\"";

			$SQL_command = "INSERT INTO products (name, synonyms, storeTypeId) VALUES (\"".$this->getName()."\", ".$syns.", ".$this->getStoreType()->getID().")";
			
			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($mysqli_result)
			{
				return true;
			}

			return false;
		}

		public function change()
		{
			$syns = "NULL";
			if($this->getSynonyms() != null || strlen($this->getSynonyms()) > 0)
				$syns = "\"".$this->getSynonyms()."\"";

			$SQL_command = "UPDATE products SET name=\"".$this->getName()."\", synonyms=".$syns.", storeTypeId=".$this->getStoreType()->getID()." WHERE id=".$this->getID();

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($mysqli_result)
			{
				return true;
			}

			return false;
		}

		public function delete()
		{
			$SQL_command = "DELETE FROM products WHERE id=".$this->getID();

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($mysqli_result)
				return true;

			return false;
		}

		public function getUsage()
		{
			$SQL_command = "SELECT COUNT(listId) as entryAmount FROM listEntries WHERE productId=".$this->getID();

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($row = mysqli_fetch_object($mysqli_result))
				return $row->entryAmount;
			
			return 0;
		}

		public static function getAllProducts()
		{
			if(Product::$productsCache == null)
			{
/*				$productsAmount = 500;
				$SQL_command = "SELECT COUNT(name) as productsAmount FROM products";
				$mysqli_result = DBLink::getDbLink()->query($SQL_command);
				if($row = mysqli_fetch_object($mysqli_result))
					$amount = $row->productsAmount;
*/
				$SQL_command = "SELECT * FROM products ORDER BY products.name ASC";

				$mysqli_result = DBLink::getDbLink()->query($SQL_command);

//				Product::$productsCache = new SplFixedArray($productsAmount);
				Product::$productsCache = array();

//				$index = 0;
				while ($row = mysqli_fetch_object($mysqli_result))
				{
					$newProduct = new Product();

					$newProduct->setID($row->id);
					$newProduct->setName($row->name);
					$newProduct->setSynonyms($row->synonyms);
					$newProduct->setStoreType(StoreType::getById($row->storeTypeId));

					Product::$productsCache[] = $newProduct;
//					Product::$productsCache[$index] = $newProduct;
//					$index++;
				}
			}

			return Product::$productsCache;
		}

		public static function entryCombinationExists($productId, $unitId)
		{
			$SQL_command = "SELECT COUNT(listId) as entryAmount FROM listEntries WHERE listId=(SELECT id FROM `lists` ORDER BY creationTime DESC LIMIT 1) AND productId=".$productId." AND unit=".$unitId;

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);
			if ($row = mysqli_fetch_object($mysqli_result))
			{
				if($row->entryAmount > 0)
					return true;
			}

			return false;
		}
	}

	class ShoppingList
	{
		private $id;
		private $creationTime;
		private $comment;
		private $entries = array();

		private static $listsCache = null;

		public function setID($id)
		{
			$this->id = $id;
		}
		public function getID()
		{
			return $this->id;
		}

		public function setCreationTime($cTime)
		{
			$this->creationTime = $cTime;
		}
		public function getCreationTime()
		{
			return $this->creationTime;
		}
		
		public function setComment($comment)
		{
			$this->comment = $comment;
		}
		public function getComment()
		{
			return $this->comment;
		}
		
		public function setEntries($entries)
		{
			$this->entries = $entries;
		}
		public function getEntries()
		{
			return $this->entries;
		}

		public function create()
		{
			if($this->getCreationTime() == null || $this->getCreationTime() == 0 || strlen($this->getCreationTime()) == 0)
				$this->setCreationTime(round(microtime(true) * 1000));

			$comment = "NULL";
			if($this->getComment() != null || strlen($this->getComment()) > 0)
				$comment = "\"".$this->getComment()."\"";

			$SQL_command = "INSERT INTO lists (creationTime, comment) VALUES (".$this->getCreationTime().", ".$comment.")";
			
			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($mysqli_result)
			{
				return true;
			}

			return false;
		}

		public function change()
		{
			$comment = "NULL";
			if($this->getComment() != null || strlen($this->getComment()) > 0)
				$comment = "\"".$this->getComment()."\"";

			$SQL_command = "UPDATE lists SET creationTime=\"".$this->getCreationTime()."\", comment=".$comment." WHERE id=".$this->getID();

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($mysqli_result)
			{
				return true;
			}

			return false;
		}

		public function delete()
		{
			$SQL_command = "DELETE FROM lists WHERE id=".$this->getID();

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			if ($mysqli_result)
				return true;

			return false;
		}

		public static function getAllLists()
		{
			if(ShoppingList::$listsCache == null)
			{
				$SQL_command = "SELECT * FROM lists ORDER BY lists.creationTime DESC";

				$mysqli_result = DBLink::getDbLink()->query($SQL_command);

				ShoppingList::$listsCache = array();

				while ($row = mysqli_fetch_object($mysqli_result))
				{
					$newList = new ShoppingList();

					$newList->setID($row->id);
					$newList->setCreationTime($row->creationTime);
					$newList->setComment($row->comment);

						$SQL_command_inner = "SELECT * FROM listEntries WHERE listId=".$newList->getID();
						$mysqli_result_inner = DBLink::getDbLink()->query($SQL_command_inner);
						while ($row_inner = mysqli_fetch_object($mysqli_result_inner))
						{
							$newListEntry = new ShoppingListEntry();
							$newListEntry->setParentList($newList);
							$newListEntry->setProduct(Product::getById($row_inner->productId));
							$newListEntry->setAmount($row_inner->amount);
							$newListEntry->setUnit(Unit::getById($row_inner->unit));
							$newList->getEntries()[] = $newListEntry;
						}

					ShoppingList::$listsCache[] = $newList;
				}
			}

			return ShoppingList::$listsCache;
		}

		public static function oneListExists()
		{
			$SQL_command = "SELECT COUNT(id) as listAmount FROM lists";
			$mysqli_result = DBLink::getDbLink()->query($SQL_command);
			if ($row = mysqli_fetch_object($mysqli_result))
			{
				if($row->listAmount > 0)
					return true;
			}

			return false;
		}

		public static function twoListsExist()
		{
			$SQL_command = "SELECT COUNT(id) as listAmount FROM lists";
			$mysqli_result = DBLink::getDbLink()->query($SQL_command);
			if ($row = mysqli_fetch_object($mysqli_result))
			{
				if($row->listAmount > 1)
					return true;
			}

			return false;
		}
	}

?>

<!--
			 ▄▄   ▄▄ ▄▄▄▄▄▄ ▄▄▄ ▄▄    ▄ 
			█  █▄█  █      █   █  █  █ █
			█       █  ▄   █   █   █▄█ █
			█       █ █▄█  █   █       █
			█       █      █   █  ▄    █
			█ ██▄██ █  ▄   █   █ █ █   █
			█▄█   █▄█▄█ █▄▄█▄▄▄█▄█  █▄▄█

			 ▄▄▄▄▄▄▄ ▄▄▄▄▄▄   ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄   ▄▄▄▄▄▄ ▄▄   ▄▄ 
			█       █   ▄  █ █       █       █   ▄  █ █      █  █▄█  █
			█    ▄  █  █ █ █ █   ▄   █   ▄▄▄▄█  █ █ █ █  ▄   █       █
			█   █▄█ █   █▄▄█▄█  █ █  █  █  ▄▄█   █▄▄█▄█ █▄█  █       █
			█    ▄▄▄█    ▄▄  █  █▄█  █  █ █  █    ▄▄  █      █       █
			█   █   █   █  █ █       █  █▄▄█ █   █  █ █  ▄   █ ██▄██ █
			█▄▄▄█   █▄▄▄█  █▄█▄▄▄▄▄▄▄█▄▄▄▄▄▄▄█▄▄▄█  █▄█▄█ █▄▄█▄█   █▄█

			 ▄▄▄▄▄▄▄ ▄▄▄     ▄▄▄▄▄▄▄ ▄     ▄ 
			█       █   █   █       █ █ ▄ █ █
			█    ▄▄▄█   █   █   ▄   █ ██ ██ █
			█   █▄▄▄█   █   █  █ █  █       █
			█    ▄▄▄█   █▄▄▄█  █▄█  █       █
			█   █   █       █       █   ▄   █
			█▄▄▄█   █▄▄▄▄▄▄▄█▄▄▄▄▄▄▄█▄▄█ █▄▄█

-->

	<html>
		<head>
			<title>Shopping list</title>
			<style type="text/css">
				body
				{
					font-family: Arial, Geneva, Helvetica, sans-serif;
				}

				details
				{
					padding-top: 15px;
					padding-left: 15px;
				}

				table
				{
				  border-collapse:separate;
				  border-spacing:10px 10px;
				}​​​​​​​​​​​​​

				.smallButton
				{
					font-size:10px;;
					height:5000em;
					width:5000em;
				}
			</style>

			<script language="javascript" type="text/javascript">

				var detailsElements = [];

				function checkCreateProduct()
				{
					var storeTypeId = document.forms["createProductForm"]["productStoreTypeId"].value;
					if (storeTypeId == "" || storeTypeId == "0")
					{
						alert("Store type must be selected");
						return false;
					}

					return true;
				}

				function checkAddProductToList()
				{
					var storeTypeId = document.forms["addProductToListForm"]["productId"].value;
					if (storeTypeId == "" || storeTypeId == "0")
					{
						alert("Product must be selected");
						return false;
					}

					return true;
				}

				function addHidden(theForm, key, value)
				{
					// Create a hidden input element, and append it to the form:
					var input = document.createElement('input');
					input.type = 'hidden';
					input.id = key; // 'the key/name of the attribute/field that is sent to the server
					input.name = key; // 'the key/name of the attribute/field that is sent to the server
					input.value = value;
					theForm.appendChild(input);
				}

				function addToggleStates(formId)
				{
					addHidden(formId, "openDetailsElements", detailsElements.join(";"));
				}

				function rememberToggleState(detailsElement)
				{
					if(detailsElement.open)
					{
						if(!detailsElements.includes(detailsElement.id))
						{
							detailsElements.push(detailsElement.id);
						}
					}
					else
					{
						for (var i = detailsElements.length - 1; i >= 0; i--)
						{
							if (detailsElements[i] === detailsElement.id)
							{
								detailsElements.splice(i, 1);
							}
						}
					}
				}

			</script>

		</head>

		<body>

<?php

	$command = $_POST['command'];
	$listId;

	if(isset($command))
	{
		switch($command)
		{
			case "addToList":
				$productId = $_POST['productId'];
				$amount = $_POST['amountToAdd'];
				$unitId = $_POST['unitToAdd'];
				addToList($productId, $amount, $unitId);
				break;

			case "removeFromList":
				$productId = $_POST['productToRemove'];
				$listId = $_POST['listId'];
				$amount = $_POST['productAmountToRemove'];
				$unit = $_POST['productUnitToRemove'];
				removeFromList($productId, $listId, $amount, $unit);
				break;

			case "displayShoppingList":
				displayShoppingList();
				break;

			case "createNewShoppingList":
				$newList = new ShoppingList();
				if($newList->create())
					echo "New shopping list has been created.";
				else
					echo "New shopping list could not be created: ".mysqli_error(DBLink::getDbLink());
				break;

			case "manageList":
				$listId = $_POST['oldListId'];
				$subCommand = $_POST['bSubmit'];
				GLOBAL $iconDelete;
				if($subCommand == $iconDelete)
				{
					removeShoppingList($listId);
					$listId = null;
				}
				break;

			case "createProduct":
				$p = new Product();
				$p->setID($_POST['oldProductId']);
				
				if(strpos($_POST['productName'], ";") !== false)
				{
					$terms = explode(";", $_POST['productName']);
					$p->setName = $terms[0];

					$syns = "";
					for($i=1; $i<count($terms); $i++)
					{
						$currentWord = trim($terms[$i]);

						if(strlen($currentWord) > 0)
							$syns .= ";".$currentWord;
					}
					
					$syns = ltrim($syns, ';');
					$p->setSynonyms($syns);
				}
				else
					$p->setName($_POST['productName']);

				if(isset($_POST['productStoreTypeId']) && (int)$_POST['productStoreTypeId'] > 0)
				{
					$p->setStoreType(StoreType::getById($_POST['productStoreTypeId']));

					if($p->create())
						echo "Product has been created.";
					else
						echo "Product could not be created: ".mysqli_error(DBLink::getDbLink());
				}
				else
					echo "Store type was not set.";

				break;				
			case "manageProduct":
				$p = new Product();
				$p->setID($_POST['oldProductId']);
				$p->setName($_POST['productName']);
				$p->setSynonyms($_POST['productSynonyms']);
				$p->setStoreType(StoreType::getById($_POST['productStoreTypeId']));

				GLOBAL $iconDelete;
				GLOBAL $iconSave;

				$subCommand = $_POST['bSubmit'];
				if($subCommand == $iconDelete)
				{
					if($p->delete())
						echo "Product has been deleted.";
					else
						echo "Product could not be deleted: ".mysqli_error(DBLink::getDbLink());
				}
				else if($subCommand == $iconSave)
				{
					if($p->change())
						echo "Product has been changed.";
					else
						echo "Product could not be changed: ".mysqli_error(DBLink::getDbLink());
				}
				else
					echo "Invalid command.";
				break;


			case "createStoreType":
				$st = new StoreType();
				$st->setName($_POST['storeTypeName']);

				if($st->create())
					echo "Store type has been created.";
				else
					echo "Store type could not be created: ".mysqli_error(DBLink::getDbLink());

				break;
			case "manageStoreType":
				$st = new StoreType();
				$st->setID($_POST['oldStoreTypeId']);
				$st->setName($_POST['storeTypeName']);

				GLOBAL $iconDelete;
				GLOBAL $iconSave;

				$subCommand = $_POST['bSubmit'];
				if($subCommand == $iconDelete)
				{
					if($st->delete())
						echo "Store type has been deleted.";
					else
						echo "Store type could not be deleted: ".mysqli_error(DBLink::getDbLink());
				}
				else if($subCommand == $iconSave)
				{
					if($st->change())
						echo "Store type has been changed.";
					else
						echo "Store type could not be changed: ".mysqli_error(DBLink::getDbLink());
				}
				else
					echo "Invalid command.";
				break;
				

			case "createUnit":

				$u = new Unit();
				$u->setName($_POST['unitName']);
				$u->setAbbreviation($_POST['unitAbbreviation']);
				$u->setDefault(isset($_POST['unitIsDefault']));
				$u->setDummy(isset($_POST['unitIsDummy']));
				$u->setPiece(isset($_POST['unitIsPiece']));

				if($u->create())
					echo "Unit has been created.";
				else
					echo "Unit could not be created.";

				break;
			case "manageUnit":

				$u = new Unit();
				$u->setID($_POST['oldUnitId']);
				$u->setName($_POST['unitName']);
				$u->setAbbreviation($_POST['unitAbbreviation']);
				$u->setDefault(isset($_POST['unitIsDefault']));
				$u->setDummy(isset($_POST['unitIsDummy']));
				$u->setPiece(isset($_POST['unitIsPiece']));

				GLOBAL $iconDelete;
				GLOBAL $iconSave;

				$subCommand = $_POST['bSubmit'];
				if($subCommand == $iconDelete)
				{
					if($u->delete())
						echo "Unit has been deleted.";
					else
						echo "Unit could not be deleted.";
				}
				else if($subCommand == $iconSave)
				{
					if($u->change())
						echo "Unit has been changed.";
					else
						echo "Unit could not be changed.";
				}
				else
					echo "Invalid command.";
				break;
			case "trainRhasspy":
				echo "Triggering training in Rhasspy has not been implemented, yet.";
				break;
		}
	}
	
	displayShoppingList($listId, $justCreatedProductId);

	showDataMaintenance();

	echo "</body></html>";

	mysqli_close(DBLink::getDbLink());


	function addToList($productId, $amount, $unitId)
	{
		if($productId > 0 && $amount != 0 && isset($unitId) && strlen($unitId) > 0)
		{
			if(!ShoppingList::oneListExists())
				createList();

			if(!ShoppingListEntry::entryCombinationExists($productId, $unitId))
			{
				$SQL_command = "INSERT IGNORE INTO listEntries (listId, productId, amount, unit) VALUES ((SELECT id FROM `lists` ORDER BY creationTime DESC LIMIT 1), ".$productId.", ".$amount.", ".$unitId.")";

				if (DBLink::getDbLink()->query($SQL_command))
					echo "Product added to list.<br>";
				else
					echo "Product could not be added to list.<br>";
			}
			else
			{
				/*
					update command that adds the amount to the already existing amount
					if amount is negative -> subtract from existing amount. if resulting amount <= 0 -> 
				*/

				$SQL_command = "SELECT amount FROM listEntries WHERE listId=(SELECT id FROM `lists` ORDER BY creationTime DESC LIMIT 1) AND productId=".$productId." AND unit=".$unitId;

				$mysqli_result = DBLink::getDbLink()->query($SQL_command);
				if ($row = mysqli_fetch_object($mysqli_result))
				{
					if($row->amount + $amount > 0)
					{
						$SQL_command = "UPDATE listEntries set amount=".($row->amount + $amount)." WHERE listId=(SELECT id FROM `lists` ORDER BY creationTime DESC LIMIT 1) AND productId=".$productId." AND unit=".$unitId;
						
						if (DBLink::getDbLink()->query($SQL_command))
							echo "Product added to existing entry on list.<br>";
						else
							echo "Product could not be added to existing entry on list.<br>";
					}
					else
					{
						$SQL_command = "DELETE FROM listEntries WHERE listId=(SELECT id FROM `lists` ORDER BY creationTime DESC LIMIT 1) AND productId=".$productId." AND unit=".$unitId;
						if (DBLink::getDbLink()->query($SQL_command))
							echo "Product removed from list as too many pieces of this item have been removed.<br>";
						else
							echo "Product could not be removed from list (too many pieces of this item have been removed).<br>";
					}
				}
			}
		}
		else
			echo "Specifiy product, amount and unit.";
	}


	function removeFromList($productId, $listId, $amount, $unitId)
	{
		if($productId > 0 && $amount != null && $unitId > 0)
		{
			if(ShoppingList::oneListExists())
			{
				$SQL_command = "DELETE FROM listEntries WHERE listId=".$listId." AND productId=".$productId." AND amount=".$amount." AND unit=".$unitId;

				if (DBLink::getDbLink()->query($SQL_command))
					echo "Product removed from list.<br>";
				else
					echo "Product could not be removed from list.<br>";
			}
		}
		else
			echo "Select a product.";
	}

	function displayShoppingList($listId, $justCreatedProductId)
	{
		echo "	<h2>Shopping list</h2>
		
				<form id=\"addProductToListForm\" action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\" onSubmit=\"addToggleStates(this); return checkAddProductToList();\">
					<input type=\"hidden\" id=\"command\" name=\"command\" value=\"addToList\" />
					<select name=\"productId\" id=\"productId\">
						<option value=\"0\">Select product to add</option>
					";
/*
					$SQL_command = "SELECT id, name FROM `products` ORDER BY name ASC";
					$mysqli_result = DBLink::getDbLink()->query($SQL_command);
					while ($row = mysqli_fetch_object($mysqli_result))
					{
						$currentId = (int)$row->id;

						if(isset($justCreatedProductId) && $justCreatedProductId === $currentId)
							echo "<option value=\"".$row->id."\" selected="selected">".$row->name."</option>";
						else
							echo "<option value=\"".$row->id."\">".$row->name."</option>";
					}
*/
					foreach(Product::getAllProducts() as $product)
					{
						$currentId = (int)$product->getID();

						if(isset($justCreatedProductId) && $justCreatedProductId === $currentId)
							echo "<option value=\"".$product->getID()."\" name=\"".$product->getName()."\" selected=\"selected\">".$product->getName()."</option>";
						else
							echo "<option value=\"".$product->getID()."\" name=\"".$product->getName()."\">".$product->getName()."</option>";
					}


		echo "		</select>

					<input type=\"number\" step=\"any\" id=\"amountToAdd\" name=\"amountToAdd\" value=\"1.0\" required />

					<select name=\"unitToAdd\" id=\"unitToAdd\">
						<option value=\"0\">Select unit to add</option>
					";

					$SQL_command = "SELECT * FROM `units` ORDER BY name ASC";
					$mysqli_result = DBLink::getDbLink()->query($SQL_command);
					while ($row = mysqli_fetch_object($mysqli_result))
					{
						$currentId = (int)$row->id;
						$unitArray = explode(";", $row->name);

						if($row->isDefault == 1 || (isset($justCreatedUnitId) && $justCreatedUnitId === $currentId))
							echo "<option value=\"".$row->id."\" selected=\"selected\">".$unitArray[0]."</option>";
						else
							echo "<option value=\"".$row->id."\">".$unitArray[0]."</option>";
					}

		echo "		</select>
					<input type=\"submit\" value=\"add\" />
				</form>";

		if(ShoppingList::oneListExists())
		{
			$list_SQL_command;

			if(isset($listId))
			{
				$list_SQL_command = "SELECT * FROM lists WHERE id=".$listId;
			}
			else
			{
				$list_SQL_command = "SELECT * FROM lists ORDER BY creationTime DESC LIMIT 0,1";

				$SQL_command_listId = "SELECT id FROM lists ORDER BY creationTime DESC LIMIT 0,1";

				$mysqli_result = DBLink::getDbLink()->query($SQL_command_listId);
				if ($row = mysqli_fetch_object($mysqli_result))
					$listId = $row->id;
			}
				
			$mysqli_result = DBLink::getDbLink()->query($list_SQL_command);

			if ($row = mysqli_fetch_object($mysqli_result))
			{
				echo "This list was created on ".date("l, d.m.Y", ($row->creationTime)/1000)." at ".date("G:i:s", ($row->creationTime)/1000)."<br />";

				if(isset($row->comment) && strlen($row->comment) > 0)
					echo "<i>".$row->comment."</i><br />";

				echo "<br />";
			}

			$SQL_command = "SELECT * FROM listEntries
							INNER JOIN products ON listEntries.productId=products.id
							INNER JOIN storeTypes ON products.storeTypeId = storeTypes.id
							INNER JOIN units ON units.id = listEntries.unit
							WHERE listEntries.listId=".$listId." ORDER BY storeTypes.name, products.name ASC";

			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			$lastShop="";

			$found = false;
			while ($row = mysqli_fetch_array($mysqli_result))
			{
				if(!$found)
					$found = true;

				if(isset($lastShop) && $lastShop != "" && $row[9] != $lastShop)
					echo "</table>";

				if(!isset($lastShop) || $row[9] != $lastShop)
				{
					$lastShop = $row[9];
					echo "<h3>".$lastShop."</h3>";
					echo "<table border=\"0\">";
				}

				echo "<tr>";

				if($row[14] == 1)
					echo "<td style=\"vertical-align:top;\" colspan=\"3\">".$row[5]."</td>";
				else
					echo "
						<td style=\"vertical-align:top;\">".$row[2]."</td>
						<td style=\"vertical-align:top;\">".$row[12]."</td>
						<td style=\"vertical-align:top;\">".$row[5]."</td>";

				GLOBAL $iconDelete;

				echo "
						<td style=\"vertical-align:top;\">
							<form id=\"removeItemFromListForm\" action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\" onSubmit=\"addToggleStates(this)\">
								<input type=\"hidden\" id=\"command\" name=\"command\" value=\"removeFromList\" />
								<input type=\"hidden\" id=\"listId\" name=\"listId\" value=\"".$listId."\" />
								<input type=\"hidden\" id=\"productToRemove\" name=\"productToRemove\" value=\"".$row[1]."\" />
								<input type=\"hidden\" id=\"productAmountToRemove\" name=\"productAmountToRemove\" value=\"".$row[2]."\" />
								<input type=\"hidden\" id=\"productUnitToRemove\" name=\"productUnitToRemove\" value=\"".$row[10]."\" />
								<input class=\"smallButton\" type=\"submit\" value=\"".$iconDelete."\" />
							</form>
						</td>
					</tr>";
			}

			if($found)
				echo "</table>";
			else
				echo "<i>No entries in this list, yet.</i>";
		}
		else
			echo "<i>No list exists, yet.</i>";
	}

	function showDataMaintenance()
	{
		echo "<hr />";

		$detailsName = "detailsMaintenance";
		$openString = "";		
		if(in_array($detailsName, explode(";", $_POST['openDetailsElements'])))
			$openString = " open=\"\"";

		echo "<details id=\"".$detailsName."\"".$openString." ontoggle=\"rememberToggleState(this)\">
					<summary>
						<strong>Data maintenance</strong>
					</summary>";

		echo "	<h2>Data maintenance</h2>";


				$detailsName = "detailsLists";
				$openString = "";		
				if(in_array($detailsName, explode(";", $_POST['openDetailsElements'])))
					$openString = " open=\"\"";

		echo "	<details id=\"".$detailsName."\"".$openString." ontoggle=\"rememberToggleState(this)\">
					<summary>
						<strong>Manage shopping lists</strong>
					</summary>

				<h3>Create new list</h3>

				<form id=\"createNewListForm\" action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\" onSubmit=\"if(!confirm('Are you sure you want to create a new list?')){return false;} else { addToggleStates(this) }\">
					<input type=\"hidden\" id=\"command\" name=\"command\" value=\"createNewShoppingList\" />
					<input type=\"submit\" value=\"🗎\" style=\"font-size : 25px;\" />
				</form>";

		if(ShoppingList::twoListsExist())
		{
			$SQL_command = "SELECT * FROM lists ORDER BY creationTime DESC";
				
			$mysqli_result = DBLink::getDbLink()->query($SQL_command);

			echo "<h3>Show specific list</h3>";

			echo "<form id=\"manageListForm\" action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\" onSubmit=\"addToggleStates(this)\">
					<input type=\"hidden\" id=\"command\" name=\"command\" value=\"manageList\" />
					<select name=\"oldListId\" id=\"oldListId\">";

			$selected = " selected=\"selected\"";
			foreach(ShoppingList::getAllLists() as $list)
			{
				echo "<option value=\"".$list->getID()."\" name=\"".$list->getID()."\"".$selected.">List created on ".date("l, d.m.Y", ($list->getCreationTime())/1000)." at ".date("G:i:s", ($list->getCreationTime())/1000);

				if(strlen($selected) > 0)
					$selected = "";

				if($list->getComment() != null && strlen($list->getComment()) > 0)
					echo "<i>(".$list->getComment().")</i>";

				echo "</option>";
			}

			GLOBAL $iconDelete;
			echo "		
					</select>
					<input type=\"submit\" name=\"bSubmit\" value=\"".$iconDelete."\" onClick=\"if(!confirm('Are you sure you want to delete this list?')){return false;}\"/>
					<input type=\"submit\" name=\"bSubmit\" value=\"show\" />

				</form>";
			}

			echo "</details>";

			$detailsName = "detailsRhasspy";
			$openString = "";		
			if(in_array($detailsName, explode(";", $_POST['openDetailsElements'])))
				$openString = " open=\"\"";

		echo "	<details id=\"".$detailsName."\"".$openString." ontoggle=\"rememberToggleState(this)\">
					<summary>
						<strong>Manage Rhasspy</strong>
					</summary>

					<h3>Train Rhasspy</h3>

					<form id=\"trainRhasspyForm\" action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\" onSubmit=\"addToggleStates(this)\">
						<input type=\"hidden\" id=\"command\" name=\"command\" value=\"trainRhasspy\" />
					<input type=\"submit\" value=\"🚂\" style=\"font-size : 25px;\" />
					</form>
				</details>";

			$detailsName = "detailsManageProducts";
			$openString = "";		
			if(in_array($detailsName, explode(";", $_POST['openDetailsElements'])))
				$openString = " open=\"\"";

			GLOBAL $iconSave;

			echo "
					<details id=\"".$detailsName."\"".$openString." ontoggle=\"rememberToggleState(this)\">
						<summary>
							<strong>Manage products</strong>
						</summary>

					<h4>Create new product</h4>
					
					<form id=\"createProductForm\" action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\" onSubmit=\"addToggleStates(this); return checkCreateProduct()\">
						<input type=\"hidden\" id=\"command\" name=\"command\" value=\"createProduct\" />
						<input type=\"text\" id=\"productName\" name=\"productName\" required />

						<select name=\"productStoreTypeId\" id=\"productStoreTypeId\">
							<option value=\"0\">Select store type</option>
						";

						$SQL_command = "SELECT id, name FROM storeTypes ORDER BY name ASC";
						$mysqli_result = DBLink::getDbLink()->query($SQL_command);
						while ($row = mysqli_fetch_object($mysqli_result))
						{
							echo "<option value=\"".$row->id."\">".$row->name."</option>";
						}

			echo "		</select>

						<input type=\"submit\" value=\"".$iconSave."\" />
					</form>
					<font size=\"2\">You can enter synonyms. Separate all terms with semikolons.</font>
				";

			$allProducts = Product::getAllProducts();
			
			if(count($allProducts) > 0)
				echo "	<h4>Manage existing products</h4>
						<table border=\"0\">
						<tr>
							<th>Product name</th>
							<th>Synonyms</th>
							<th>Store type</th>
						</tr>";

			GLOBAL $iconDelete;
			GLOBAL $iconSave;

			foreach($allProducts as $p)
			{
				echo "<tr>
						<form id=\"manageProductForm\" action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\" onSubmit=\"addToggleStates(this)\">
							<input type=\"hidden\" id=\"command\" name=\"command\" value=\"manageProduct\" />
						<td><input type=\"text\" size=\"20\" id=\"productName\" name=\"productName\" value=\"".$p->getName()."\" required /></td>
						<td><input type=\"text\" size=\"20\" id=\"productSynonyms\" name=\"productSynonyms\" value=\"".$p->getSynonyms()."\" /></td>
						<td>
						<select name=\"productStoreTypeId\" id=\"productStoreTypeId\">
						";

						foreach(StoreType::getAllStoreTypes() as $storeType)
						{
							if($storeType->getID() === $p->getStoreType()->getID())
								echo "<option value=\"".$storeType->getID()."\" name=\"".$storeType->getName()."\" selected=\"selected\">".$storeType->getName()."</option>";
							else
								echo "<option value=\"".$storeType->getID()."\" name=\"".$storeType->getName()."\" >".$storeType->getName()."</option>";
						}

			echo "		</select></td>
							<input type=\"hidden\" id=\"oldProductId\" name=\"oldProductId\" value=\"".$p->getID()."\" />
						";

				$usageAmount = $p->getUsage();
				$deletionWarning = "Are you sure you want to delete this product?";
				if($usageAmount > 0)
					$deletionWarning = "Are you sure you want to delete this product? It is still in use by ".$usageAmount." list entries. If you delete the product it will be removed from all shopping lists as well.";

			echo "
					<td><input type=\"submit\" name=\"bSubmit\" value=\"".$iconDelete."\" onClick=\"if(!confirm('".$deletionWarning."')){return false;}\" /></td>
					<td><input type=\"submit\" name=\"bSubmit\" value=\"".$iconSave."\" /></td>
					</form>
				</tr>";
		}

		if(count($allProducts) > 0)
			echo "</table>";

		echo "
				</details>";

		$detailsName = "detailsManageUnits";
		$openString = "";		
		if(in_array($detailsName, explode(";", $_POST['openDetailsElements'])))
			$openString = " open=\"\"";

		echo "
				<details id=\"".$detailsName."\"".$openString." ontoggle=\"rememberToggleState(this)\">
					<summary>
						<strong>Manage units</strong>
					</summary>

					<h4>Create new unit</h4>

					<form id=\"createUnitForm\" action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\" onSubmit=\"addToggleStates(this)\">
						<table border=\"0\">
							<tr><td>Unit name</td><td><input type=\"text\" id=\"unitName\" name=\"unitName\" required /></td></tr>
							<tr><td>Unit abbreviation</td><td><input type=\"text\" id=\"unitAbbreviation\" name=\"unitAbbreviation\" /></td></tr>
							<tr><td>Is default?</td><td><input type=\"checkbox\" id=\"unitIsDefault\" name=\"unitIsDefault\" /></td></tr>
							<tr><td>Is dummy?</td><td><input type=\"checkbox\" id=\"unitIsDummy\" name=\"unitIsDummy\" /></td></tr>
							<tr><td>Is piece?</td><td><input type=\"checkbox\" id=\"unitIsPiece\" name=\"unitIsPiece\" /></td></tr>
						</table>
						<input type=\"hidden\" id=\"command\" name=\"command\" value=\"createUnit\" />
						<input type=\"submit\" value=\"Create unit\" />
					</form>";

		$allUnits = Unit::getAllUnits();
		
		if(count($allUnits) > 0)
			echo "	<h4>Manage existing units</h4>
					<table border=\"0\">
					<tr>
						<th>Unit name</th>
						<th>Abbreviation</th>
						<th>is default?</th>
						<th>is dummy?</th>
						<th>is piece?</th>
					</tr>";

		GLOBAL $iconDelete;
		GLOBAL $iconSave;

		foreach($allUnits as $u)
		{
			echo "<tr>
					<form id=\"manageUnitForm\" action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\" onSubmit=\"addToggleStates(this)\">
						<input type=\"hidden\" id=\"command\" name=\"command\" value=\"manageUnit\" />
					<td><input type=\"text\" size=\"20\" id=\"unitName\" name=\"unitName\" value=\"".$u->getName()."\" required /></td>
					<td><input type=\"text\" size=\"5\" id=\"unitAbbreviation\" name=\"unitAbbreviation\" value=\"".$u->getAbbreviation()."\" /></td>
					<td><input type=\"checkbox\" id=\"unitIsDefault\" name=\"unitIsDefault\", value=\"unitIsDefault\""; if ($u->isDefault()) echo " checked"; echo " /></td>
					<td><input type=\"checkbox\" id=\"unitIsDummy\" name=\"unitIsDummy\", value=\"unitIsDummy\""; if ($u->isDummy()) echo " checked"; echo " /></td>
					<td><input type=\"checkbox\" id=\"unitIsPiece\" name=\"unitIsPiece\", value=\"unitIsPiece\""; if ($u->isPiece()) echo " checked"; echo " /></td>
						<input type=\"hidden\" id=\"oldUnitId\" name=\"oldUnitId\" value=\"".$u->getID()."\" />
					";

			$usageAmount = $u->getUsage();
			$deletionWarning = "Are you sure you want to delete this unit?";
			if($usageAmount > 0)
				$deletionWarning = "Are you sure you want to delete this unit? It is still in use by ".$usageAmount." list entries. If you delete the unit those entries will all be removed as well.";

			echo "
					<td><input type=\"submit\" name=\"bSubmit\" value=\"".$iconDelete."\" onClick=\"if(!confirm('".$deletionWarning."')){return false;}\" /></td>
					<td><input type=\"submit\" name=\"bSubmit\" value=\"".$iconSave."\" /></td>
					</form>
				</tr>";
		}

		if(count($allUnits) > 0)
			echo "</table>";

		echo "
				</details>";
		

		$detailsName = "detailsManageStoreTypes";
		$openString = "";		
		if(in_array($detailsName, explode(";", $_POST['openDetailsElements'])))
			$openString = " open=\"\"";

		GLOBAL $iconSave;

		echo "
				<details id=\"".$detailsName."\"".$openString." ontoggle=\"rememberToggleState(this)\">
					<summary>
						<strong>Manage store types</strong>
					</summary>

					<h4>Create new store type</h4>

					<form id=\createStoreTypeForm\" action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\" onSubmit=\"addToggleStates(this)\">
						<table border=\"0\">
							<tr><td>Store type name</td><td><input type=\"text\" id=\"storeTypeName\" name=\"storeTypeName\" required /></td><td><input type=\"submit\" value=\"".$iconSave."\" /></td></tr>
						</table>
						<input type=\"hidden\" id=\"command\" name=\"command\" value=\"createStoreType\" />						
					</form>";

		$allStoreTypes = StoreType::getAllStoreTypes();
		
		if(count($allStoreTypes) > 0)
		{
			echo "	<h4>Manage existing store types</h4>
					<table border=\"0\">
					<tr>
						<th>Store type name</th>
					</tr>";
		}

		GLOBAL $iconDelete;
		GLOBAL $iconSave;

		foreach($allStoreTypes as $st)
		{
			echo "<tr>
					<form id=\"manageStoreTypeForm\" action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\" onSubmit=\"addToggleStates(this)\">
						<input type=\"hidden\" id=\"command\" name=\"command\" value=\"manageStoreType\" />
					<td><input type=\"text\" size=\"20\" id=\"unitStoreType\" name=\"storeTypeName\" value=\"".$st->getName()."\" required /></td>
						<input type=\"hidden\" id=\"oldStoreTypeId\" name=\"oldStoreTypeId\" value=\"".$st->getID()."\" />
					";

			$usageAmount = $st->getUsage();
			$deletionFunction = "if(!confirm('Are you sure you want to delete this store type?')){return false;}";
			if($usageAmount > 0)
				$deletionFunction = "alert('You cannot currently delete this store type. This is still your place to buy ".$usageAmount." products.'); return false;";

			echo "
					<td><input type=\"submit\" name=\"bSubmit\" value=\"".$iconDelete."\" onClick=\"".$deletionFunction."\" /></td>
					<td><input type=\"submit\" name=\"bSubmit\" value=\"".$iconSave."\" /></td>
					</form>
				</tr>";
		}

		if(count($allStoreTypes) > 0)
			echo "</table>";

		echo "
				</details>";



		echo "
				</details>";
	}


	function displayProductList()
	{
/*		$SQL_command = "SELECT name, synonyms FROM products ORDER BY products.name ASC";
		
		$mysqli_result = DBLink::getDbLink()->query($SQL_command);

		$lastShop="";

		while ($row = mysqli_fetch_array($mysqli_result))
		{
			if(is_null($row[1]))
				echo $row[0]."\n";
			else
				echo "(".str_replace(";", "|", $row[1])."|".$row[0]."):".$row[0]."\n";
		}*/

		foreach(Product::getAllProducts() as $product)
		{
			if($product->getSynonyms() == null && strlen($product->getSynonyms()) == 0)
				echo $product->getName()."\n";
			else
//				echo "(".str_replace(";", "|", $product->getSynonyms())."):".$product->getName()."\n";
				echo "(".str_replace(";", "|", $product->getSynonyms())."|".$product->getName()."):".$product->getName()."\n";
		}
	}


	function displayUnitList()
	{
		/*$SQL_command = "SELECT name FROM units ORDER BY name ASC";
		
		$mysqli_result = DBLink::getDbLink()->query($SQL_command);

		while ($row = mysqli_fetch_object($mysqli_result))
		{
			$unitArray = explode(";", $row->name);
			if(count($unitArray) == 1)
				echo $unitArray[0]."\n";
			else
			{
				$tbp = "";
				for($i=1; $i<count($unitArray); $i++)
					$tbp .= $unitArray[$i]."|";

				$tbp = trim($tbp, "|");

				echo "(".$tbp."):".$unitArray[0]."\n";
			}
		}*/

		foreach(Unit::getAllUnits() as $unit)
		{
			$unitArray = explode(";", $unit->getName());
			if(count($unitArray) == 1)
				echo $unitArray[0]."\n";
			else
			{
				$tbp = "";
				for($i=1; $i<count($unitArray); $i++)
					$tbp .= $unitArray[$i]."|";

				$tbp = trim($tbp, "|");

				echo "(".$tbp."):".$unitArray[0]."\n";
			}
		}
	}

	function removeShoppingList($listId)
	{
		$date = new DateTime();

		$SQL_command = "DELETE FROM lists WHERE id=".$listId;

		if (DBLink::getDbLink()->query($SQL_command))
			echo "List has been deleted.<br>";
		else
			echo "Error deleting list.<br>";
	}

?>