<?php

session_start();
if (!isset($_SESSION['FirstName'])) {
	exit;
}

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

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

if (!isset($_POST['action']) || empty($_POST['action'])) {
	$response['message'] = 'No action';
	returnResponse();
}

switch ($_POST['action']) {
	case 'get_menu_items':
		getMenuItems();
		break;
	case 'save':
		saveExcludedMenuItems();
		break;
}

returnResponse();

function returnResponse() {
	global $response;
	echo json_encode($response);
	die();
}

function getMenuItems() {
	
	global $response;
	
	$categoryId = isset($_POST['category_id']) ? $_POST['category_id'] : 0;
	$menuId = isset($_POST['menu_id']) ? $_POST['menu_id'] : 0;
	

	$excludedMenuItems = getExcludedItemsForMenu($menuId);

	$sql = "SELECT *
			FROM menuItem
			WHERE categoryKey = '".mysql_real_escape_string($categoryId)."'";
	$result = mysql_query($sql) or die(mysql_error());

	$menuItems = '';

	$menuItems .= '<input type="hidden" name="category_id" id="category_id" value="'.$categoryId.'">';
	while ($row = mysql_fetch_assoc($result)) {
		$menuItems .= '<div id="menu-item-'.$row['itemKey'].'">';
		$menuItems .= '<label>';
		$menuItems .= '<input class="menu-item-exclusions" type="checkbox" value="'.$row['itemKey'].'" '.(in_array($row['itemKey'], $excludedMenuItems) ? 'checked' : '').'> ';
		$menuItems .= $row['itemName'];
		$menuItems .= '</label>';
		$menuItems .= '</div>';
	}

	if ($menuItems == '') {
		$menuItems = 'No menu items found.';
	}
    
    $response['result'] = 1;
	$response['menuItems'] = $menuItems;
	returnResponse();
}

function getExcludedItemsForMenu($menuId) {
	$menuExclusions = array();

	$sql = "SELECT *
			FROM menu_exclusions
			WHERE menukey = '".mysql_real_escape_string($menuId)."'";
	$result = mysql_query($sql) or die(mysql_error());

	while ($row = mysql_fetch_assoc($result)) {
		$menuExclusions[] = $row['itemkey'];
	}

	return $menuExclusions;
}

function getExcludedItemsForCategory($menuId,$categoryId,$exclusion) {
	
	//$menuExclusions = array();

	$sql = "SELECT *
			FROM menu_exclusions
			WHERE (menukey = '".mysql_real_escape_string($menuId)."') && 
			      (categoryKey = '".mysql_real_escape_string($categoryId)."') &&
			      (itemKey = '".mysql_real_escape_string($exclusion)."')";
	$result = mysql_query($sql) or die(mysql_error());

	while ($row = mysql_fetch_assoc($result)) {
		$existing = $row['recordKey'];
	}

	return $existing;
}

function getCategory($itemKey)
{
	$sql = "SELECT categoryKey
			FROM menuItem
			WHERE itemKey = '".mysql_real_escape_string($itemKey)."'";	
	$result = mysql_query($sql) or die(mysql_error());

	while ($row = mysql_fetch_assoc($result)) {
		$categoryId = $row['categoryKey'];
	}
	return $categoryId;
}
function saveExcludedMenuItems() {
	
	global $response;
	
	$menuId = isset($_POST['menu_id']) ? $_POST['menu_id'] : 0;
	$categoryId = isset($_POST['category_id']) ? $_POST['category_id'] : 0;
	
	if (empty($menuId)) {
		$response['message'] = 'No menu id';
		returnResponse();
	}
    
    $sql = "DELETE FROM menu_exclusions WHERE  categoryKey= '".mysql_real_escape_string($categoryId)."'";
    mysql_query($sql) or die(mysql_error());

	$exclusions = isset($_POST['exclusions']) && is_array($_POST['exclusions']) ? $_POST['exclusions'] : array();
	// $existingExclusions = getExcludedItemsForMenu($menuId);
	
	$savedExclusions = array();
	
	foreach ($exclusions as $exclusion) {

	$categoryId=getCategory($exclusion);
	$existing = getExcludedItemsForCategory($menuId,$categoryId,$exclusion);
	
		if ($existing==0) {
			
			$sql = "INSERT INTO menu_exclusions (
						menukey,
						itemkey,
						categoryKey
					) VALUES (
						'".mysql_real_escape_string($menuId)."',
						'".mysql_real_escape_string($exclusion)."',
						'".mysql_real_escape_string($categoryId)."'
					)";
			mysql_query($sql) or die(mysql_error());
		}
	
		$savedExclusions[] = $exclusion;
	}

	
	//Delete not saved
	// $sql = "DELETE FROM menu_exclusions
	// 		WHERE menukey = '".mysql_real_escape_string($menuId)."'";
	// if (!empty($savedExclusions)) {
	// 	$sql .= " AND itemkey NOT IN (".implode(',', $savedExclusions).")";
	// }
	// mysql_query($sql) or die(mysql_error());

	$response['result'] = 1;
}