<?php
session_start();
if (!isset($_SESSION['FirstName'])) {
	exit;
}
include ('includes/db1config.php');
include ('../includes/mysql_connect.php');

if (!isset($_POST['pageid']) || empty($_POST['pageid'])) {
	die('Page id not set.');
}

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

$widgetAreas = array('sidebar', 'top', 'bottom', 'mobile');


					
foreach ($widgetAreas as $area) {
	if (!isset($_POST[$area]) || empty($_POST[$area])) {
		die('POST value not set.');
	}
	//write to log for testing
	$logqry = "insert into test_log (field1) values ('widget area value: ".$_POST[$area]."')";
	mysql_query($logqry) or die(mysql_error());
}

// get all saved widgets
$sql = "SELECT * FROM pageWidgets WHERE pageid = '".mysql_real_escape_string($pageid)."'";
$result = mysql_query($sql) or die(mysql_error());

$savedWidgets = array(
	'sidebar' => array(),
	'top' => array(),
	'bottom' => array(),
	'mobile' => array()
);
while ($row = mysql_fetch_assoc($result)) {
	foreach ($widgetAreas as $area) {
		if ($row[$area] == 1) {
			$savedWidgets[$area][$row['widgetid']] = $row['recordkey'];
		}
	}
}

$newWidgets = array();

foreach ($widgetAreas as $area) {
	$sequence = 0;
	$widgets = str_replace('\"', '"', $_POST[$area]);
	$widgets = json_decode($widgets);
	
	foreach ($widgets as $widget) {
		if (array_key_exists($widget->recordkey, $savedWidgets[$area])) {
			// exists
			$sql = "UPDATE pageWidgets
					SET sequence = ".$sequence."
					WHERE recordkey = ".$savedWidgets[$area][$widget->recordkey];

			mysql_query($sql) or die(mysql_error());
			$newWidgets[] = $savedWidgets[$area][$widget->recordkey];
		} else {
			// insert new row
			$sql = "INSERT INTO pageWidgets (
						pageid, 
						widgetid, 
						$area,
						sequence
					) VALUES (
						'".mysql_real_escape_string($pageid)."',
						'".mysql_real_escape_string($widget->recordkey)."',
						1,
						".$sequence."
					)";
					
					//write to log for testing
					$logqry = "insert into test_log (field1) values ('".mysql_real_escape_string($sql)."')";
					mysql_query($logqry) or die(mysql_error());
					
					
			mysql_query($sql) or die(mysql_error());
			$newWidgets[] = mysql_insert_id();
		}
		$sequence++;
	}
}

// remove widgets
$sql = "DELETE
		FROM pageWidgets
		WHERE pageid = '$pageid'";
if (!empty($newWidgets)) {
	$sql .= " AND recordkey NOT IN (".implode(", ", $newWidgets).")";
}
mysql_query($sql) or die(mysql_error());

echo '1';
?>