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

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_item':
		getItem();
		break;
	case 'get_items_in_category':
		getItemsInCategory();
		break;
	case 'get_all_items':
		getAllItems();
		break;
	case 'get_items':
		getItems();
		break;
	default:
		$response['message'] = 'Invalid action.';
}

echo json_encode($response);

function getItemsInCategory() {
	global $response;

	if (!isset($_POST['category']) || empty($_POST['category'])) {
		$response['category'] = 'No category id.';
		returnResponse();
	}

	$items = array();

	$sql = "SELECT *
			FROM menuItem
			WHERE categoryKey = '".mysql_real_escape_string($_POST['category'])."'
			ORDER BY itemName";
	$result = mysql_query($sql) or die(mysql_error());

	while ($row = mysql_fetch_assoc($result)) {
		$items[] = $row;
	}

	$response['result'] = 1;
	$response['items'] = $items;

	returnResponse();
}

function getAllItems() {
	global $response;

	$items = array();

	$sql = "SELECT *
			FROM menuItem
			ORDER BY itemName";
	$result = mysql_query($sql) or die(mysql_error());

	while ($row = mysql_fetch_assoc($result)) {
		$items[] = $row;
	}

	$response['result'] = 1;
	$response['items'] = $items;

	returnResponse();
}

function getItem() {
	global $response;

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

	$sql = "SELECT *
			FROM menuItem
			WHERE itemKey = '".mysql_real_escape_string($_POST['id'])."'
			ORDER BY itemName";
	$result = mysql_query($sql) or die(mysql_error());

	if (mysql_num_rows($result) < 1) {
		$response['message'] = 'Menu item not found.';
		returnResponse();
	}

	$response['result'] = 1;
	$response['item'] = mysql_fetch_assoc($result);

	returnResponse();
}


function returnResponse() {
	global $response;

	echo json_encode($response);
	die();
}

function getItems() {
	global $response;

	if (empty($_POST['ids'])) {
		$ids = '';
	} else {
		$ids = $_POST['ids'];
	}

	$ids = explode(',', $_POST['ids']);

	if (empty($_POST['ids'])) {
		$response['message'] = 'No ids.';
		returnResponse();
	}

	$items = array();

	$sql = "SELECT *
			FROM menuItem
			WHERE itemKey IN (".implode(',', $ids).")
			ORDER BY itemName";
	$result = mysql_query($sql) or die(mysql_error());

	while ($row = mysql_fetch_assoc($result)) {
		$items[] = $row;
	}

	$response['result'] = 1;
	$response['items'] = $items;

	returnResponse();
}

?>