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

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

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

if (!isset($_POST['board']) || empty($_POST['board']) || $_POST['board'] < 1 ) {
	$response['message'] = 'Invalid board number.';
	die(json_encode($response));
}

if (!isset($_POST['num_columns']) || empty($_POST['num_columns'])) {
	$response['message'] = 'Invalid number of columns.';
	die(json_encode($response));
}

$board = trim($_POST['board']);
$numColumns = trim($_POST['num_columns']);

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

	for ($columnNum = 1; $columnNum <= $numColumns; $columnNum++) {
		$newItems = array();
		$newRecordKeys = array();
		if (array_key_exists($columnNum, $_POST['columns']) && is_array($_POST['columns'][$columnNum])) {
			foreach ($_POST['columns'][$columnNum] as $item) {
				if (!isValidItem($item, $allCategoryIds, $allWidgetIds)) {
					continue;
				}
				$newItems[] = $item;
			}
			$newRecordKeys = array_merge($newRecordKeys, saveNewItemsForMenuBoard($board, $columnNum, $newItems, $menuBoardItems, $numColumns));
		}
		removeOldItemsFromMenuBoard($board, $columnNum, $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() . "\n" . $sql);

	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() . "\n" . $sql);

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

	return $ids;
}

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

	$sql = "SELECT recordkey, board_number, menu_category, widget_id, display_column
			FROM menu_board_items";
	$result = mysql_query($sql) or die(mysql_error() . "\n" . $sql);

	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,
			'display_column' => $row['display_column']
		);

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

	return $menuBoardItems;
}

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

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

	return false;
}

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

	return false;
}

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

	$itemId = mysql_insert_id();

	if ($item['id'] == 9999) {
		saveCustomCategoryItems($itemId, $item);
	}

	return $itemId;
}

function saveCustomCategoryItems($id, $item) {
	if (isset($item['custom_category_items']) && !empty($item['custom_category_items'])) {
		$customCategoryItems = explode(',', $item['custom_category_items']);

		// pull existing
		$existingItems = array();
		$sql = "SELECT *
				FROM mb_custom_cat
				WHERE cust_cat_key = '".mysql_real_escape_string($id)."'";
		$result = mysql_query($sql) or die(mysql_error() . "\n" . $sql);
		while ($row = mysql_fetch_assoc($result)) {
			$existingItems[$row['recordkey']] = $row['item_key'];
		}

		$newIds = array();
		foreach ($customCategoryItems as $customCategoryItemId) {
			if (!in_array($customCategoryItemId, $existingItems)) {
				$sql = "INSERT INTO mb_custom_cat (
							cust_cat_key,
							item_key
						) VALUES (
							".$id.", '".mysql_real_escape_string($customCategoryItemId)."'
						)";
				mysql_query($sql) or die(mysql_error() . "\n" . $sql);
				$newIds[] = mysql_insert_id();
			} else {
				$newIds[] = array_search($customCategoryItemId, $existingItems);
			}
		}

		// Remove old
		$sql = "DELETE FROM mb_custom_cat
				WHERE cust_cat_key = '".$id."'";
		if (!empty($newIds)) {
			$sql .= " AND recordkey NOT IN (".implode(',', $newIds).")";
		}
		mysql_query($sql) or die(mysql_error() . "\n" . $sql);
	}
}

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

	$sql = "UPDATE menu_board_items
				SET 
					position = " . $position . ",
					custom_name = '" . mysql_real_escape_string($item['custom_name'])."',
					price_grid_format = '".mysql_real_escape_string($item['price_grid_format'])."'
				WHERE 
					board_number = '".mysql_real_escape_string($boardId)."' AND 
					{$column} = '".mysql_real_escape_string($item['id'])."' AND 
					display_column = ".$columnNum;
	mysql_query($sql) or die(mysql_error() . "\n" . $sql);
}

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

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

	return null;
}

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

	return $newItemRecordKeys;
}

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

	mysql_query($sql) or die(mysql_error() . "\n" . $sql);

	cleanMbCustomCatTable();
}

function cleanMbCustomCatTable() {
	$sql = "SELECT recordkey 
			FROM menu_board_items";
	$result = mysql_query($sql) or die(mysql_error() . "\n" . $sql);

	$ids = array();

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

	$sql = "DELETE FROM mb_custom_cat";
	if (!empty($ids)) {
		$sql .= " WHERE cust_cat_key NOT IN (".implode(',', $ids).")";
	}

	mysql_query($sql) or die(mysql_error() . "\n" . $sql);
}

?>