<?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 'update_order_by':
		updateOrderBy();
		break;
	case 'update_sort_order':
		updateSortOrder();
		break;
}

returnResponse();

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

function updateOrderBy() {
	global $response;
	if (!isset($_POST['order']) || (empty($_POST['order']) && $_POST['order'] != '0')) {
		$response['message'] = 'Invalid order.';
		returnResponse();
	}

	$order = trim($_POST['order']);

	$sql = "UPDATE storePrefs 
			SET specials_sort_by = '".mysql_real_escape_string($order)."'";
	mysql_query($sql) or die(mysql_error());

	$response['result'] = 1;
	returnResponse();
}

function updateSortOrder() {
	global $response;
	if (!isset($_POST['sort_order']) || empty($_POST['sort_order']) || !is_array($_POST['sort_order'])) {
		$response['message'] = 'Invalid sort order.';
		returnResponse();
	}

	foreach ($_POST['sort_order'] as $order => $key) {
		$sql = "UPDATE specials
				SET sort_order = '".mysql_real_escape_string($order)."'
				WHERE recordKey = '".mysql_real_escape_string($key)."'";
		mysql_query($sql) or die(mysql_error());
	}

	$response['result'] = 1;
	returnResponse();
}