<?php
session_start();
if (!isset($_SESSION['FirstName'])) {
	die('0');
}

include ('includes/db1config.php');
include ('../includes/mysql_connect.php');

$response = [
	'result' => 0
];

if (isset($_POST['boards']) && !empty($_POST['boards'])) {
	$allCategoryIds = getAllCategoryIds();
	$allWidgetIds = getAllWidgetIds();
	$menuBoardItems = getExistingMenuBoardItems();

	$newMenuBoardCategories = array();

	for ($menuBoardNum = 1; $menuBoardNum <= $_SESSION['menu_boards']; $menuBoardNum++) {
		if (array_key_exists($menuBoardNum, $_POST['boards']) && is_array($_POST['boards'][$menuBoardNum])) {
			$newItems = array();
			foreach ($_POST['boards'][$menuBoardNum] as $item) {
				if (!isValidItem($item, $allCategoryIds, $allWidgetIds)) {
					continue;
				}
				$newItems[] = $item;
			}
			$newRecordKeys = saveNewItemsForMenuBoard($menuBoardNum, $newItems, $menuBoardItems);
			removeOldItemsFromMenuBoard($menuBoardNum, $newRecordKeys);
		}
	}

	$response['result'] = 1;
}

echo json_encode($response);
die();

function parseMenuBoardCategoryIds($ids) {
	foreach ($ids as $boardId => $categoryIds) {
		if (!is_array($categoryIds)) {

		}
	}
}

function getAllCategoryIds() {
	$ids = array();

	$sql = "SELECT RecordKey
			FROM menuCategory
			WHERE Active = 1";
	$result = mysql_query($sql) or die(mysql_error());

	while ($row = mysql_fetch_assoc($result)) {
		$ids[] = $row['RecordKey'];
	}

	return $ids;
}

function getAllWidgetIds() {
	$ids = array();

	$sql = "SELECT recordkey
			FROM widgets
			WHERE active = 1";
	$result = mysql_query($sql) or die(mysql_error());

	while ($row = mysql_fetch_assoc($result)) {
		$ids[] = $row['recordkey'];
	}

	return $ids;
}

function getExistingMenuBoardItems() {
	$menuBoardItems = array();

	$sql = "SELECT recordkey, board_number, menu_category, widget_id
			FROM menu_boards";
	$result = mysql_query($sql) or die(mysql_error());

	while ($row = mysql_fetch_assoc($result)) {
		if (!array_key_exists($row['board_number'], $menuBoardItems)) {
			$menuBoardItems[$row['board_number']] = array();
		}

		if ($row['menu_category'] > 0) {
			$type = 'category';
			$id = $row['menu_category'];
		}
		if ($row['widget_id'] > 0) {
			$type = 'widget';
			$id = $row['widget_id'];
		}

		$item = array(
			'recordkey' => $row['recordkey'],
			'type' => $type,
			'id' => $id
		);

		$menuBoardItems[$row['board_number']][] = $item;
	}

	return $menuBoardItems;
}

function menuBoardHasItem($menuBoardId, $item, $menuBoardItems) {
	if (!array_key_exists($menuBoardId, $menuBoardItems)) {
		return false;
	}

	foreach ($menuBoardItems[$menuBoardId] as $menuBoardItem) {
		if ($menuBoardItem['type'] == $item['type'] && $menuBoardItem['id'] == $item['id']) {
			return true;
		}
	}

	return false;
}

function isValidItem($item, $allCategoryIds, $allWidgetIds) {
	if ($item['type'] == 'category' && in_array($item['id'], $allCategoryIds)) {
		return true;
	}
	if ($item['type'] == 'widget' && in_array($item['id'], $allWidgetIds)) {
		return true;
	}

	return false;
}

function addItemToMenuBoard($boardId, $item, $position) {
	switch ($item['type']) {
		case 'category':
			$column = 'menu_category';
			break;
		case 'widget':
			$column = 'widget_id';
			break;
	}
	$sql = "INSERT INTO menu_boards (
				board_number, {$column}, position
			) VALUES (
				'".mysql_real_escape_string($boardId)."', '".mysql_real_escape_string($item['id'])."', ".$position."
			)";
	mysql_query($sql) or die(mysql_error());

	return mysql_insert_id();
}

function updateMenuBoardItemPosition($boardId, $item, $position, $menuBoardItems) {
	switch ($item['type']) {
		case 'category':
			$column = 'menu_category';
			break;
		case 'widget':
			$column = 'widget_id';
			break;
	}

	$sql = "UPDATE menu_boards
				SET position = " . $position . " 
				WHERE board_number = '".mysql_real_escape_string($boardId)."' AND {$column} = '".mysql_real_escape_string($item['id'])."'";
	mysql_query($sql) or die(mysql_error());
}

function getMenuBoardItemRecordKey($boardNum, $item, $menuBoardItems) {
	if (!array_key_exists($boardNum, $menuBoardItems)) {
		return null;
	}

	foreach ($menuBoardItems[$boardNum] as $menuBoardItem) {
		if ($menuBoardItem['type'] == $item['type'] && $menuBoardItem['id'] == $item['id']) {
			return $menuBoardItem['recordkey'];
		}
	}

	return null;
}

function saveNewItemsForMenuBoard($boardId, $newItems, $menuBoardItems) {
	$newItemRecordKeys = [];
	$position = 1;
	foreach ($newItems as $item) {
		if (menuBoardHasItem($boardId, $item, $menuBoardItems)) {
			updateMenuBoardItemPosition($boardId, $item, $position, $menuBoardItems);
			$recordKey = getMenuBoardItemRecordKey($boardId, $item, $menuBoardItems);
		} else {
			$recordKey = addItemToMenuBoard($boardId, $item, $position);
		}
		$newItemRecordKeys[] = $recordKey;
		$position++;
	}

	return $newItemRecordKeys;
}

function removeOldItemsFromMenuBoard($boardId, $newRecordKeys) {
	$sql = "DELETE FROM menu_boards
			WHERE 
				board_number = '".mysql_real_escape_string($boardId)."'";
	if (!empty($newRecordKeys)) {
		$sql .= " AND recordkey NOT IN ('".implode("', '", $newRecordKeys)."')";
	}

	mysql_query($sql) or die(mysql_error());
}

?>