<?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;
	case 'update_date_options':
		updateDateOptions();
		break;
		
}

returnResponse();

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

function updateDateOptions() {
	global $response;
	
	$show_weekdays = $_POST['show_weekdays'];
	$show_dates = $_POST['show_dates'];
	
/*if($_POST['show_weekdays'] =="on"){
	$show_weekdays = 1;
} else {
	$show_weekdays = 0;
}
$show_dates = $_POST['show_dates'];

 
 if(!empty($_POST['show_dates']) =="on"){
	$show_dates = 1;
} else {
	$show_dates = 0;
}*/
	
	$id = trim($_POST['id']);

	$sql = "UPDATE content 
			SET list_show_days = '".$show_weekdays."',
			list_show_dates = '".$show_dates."'
			WHERE pageID = '".mysql_real_escape_string($id)."'";
			
			$testsql = "insert into test_log (field1) values ('".mysql_real_escape_string($sql)."')";
			mysql_query($testsql);// or die(mysql_error());
		
	mysql_query($sql) or die(mysql_error());

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

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

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

	$sql = "UPDATE content 
			SET list_order_by = '".mysql_real_escape_string($order)."'
			WHERE pageID = '".mysql_real_escape_string($id)."'";
	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();
	}
	if (!isset($_POST['id']) || empty($_POST['id'])) {
		$response['message'] = 'Invalid id.';
		returnResponse();
	}
	
	$id = trim($_POST['id']);

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

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