<?php
if ($_SESSION['FirstName'] == "") {
	echo 'You are not authorized to view this page. <br><br>You may <a href="index.php">log in here.</a>';
	exit;
	}

//print_r($_POST);
//require_once ('mysql_connect.php');
$action          = $_GET["a"];

	//echo 'Action = ' . $action; (for testing)


if ($action == "add") {
			
			$query = "Insert into specials (title) Values ('" . mysql_real_escape_string($_POST['title']) . "' )";

			if (!mysql_query($query)){
					echo $query;
  					die('Error: ' . mysql_error());
 			 } else {
				echo "<div align=center><font color=red>Special added successfully.</font></div>";
				
			}
		}

if ($action == "update") {
$checkbox = $_POST['chkdelete'];
$active = $_POST['chkactive'];
if(!empty($_POST['specials_group'])){$group=mysql_real_escape_string($_POST['specials_group']);}
if(!empty($_POST['new_specials_group'])){$group=mysql_real_escape_string($_POST['new_specials_group']);}

	if (empty($checkbox)) {
		//delete not checked, save other updated info

	
		
		$query = "UPDATE specials SET title = '" . mysql_real_escape_string($_POST['title']) . "',  description = '" . mysql_real_escape_string($_POST['description']) . "', Active ='";
		if (empty($active)){
			$query = $query . "0'";
		} else {
			$query = $query . "1'";
		}

		$query = $query . ", dayofweek = '" . $_POST['dayselect'] . "'";
		if(!empty($group)){
			$query = $query . ", specials_group = '$group'";			
		} else {
			$query = $query . ", specials_group = ''";				
		}
		
		
		$query = $query . " WHERE recordKey = '" . $_GET['key'] ."'" ;
		//echo $query;
		mysql_query($query) or die(mysql_error());   //execute query

		//confirmation message that delete worked...
		echo "<div id='submission-success-message-wrapper'><font color=red>****** Special updated successfully ******</font></div>";

		

	} else { 
		
		
	$query = "DELETE FROM specials WHERE recordKey = '" . $_GET["key"] ."'" ;
	
	

	mysql_query($query) or die(mysql_error());   //execute query

	//confirmation message that delete worked...
	echo "<font color=red>Special deleted successfully.</font>";

		}
		
			
	//assign day number to specials that have a day selected, doing it here will be backward compatible and auto-fix records from older sites
	$updateqry = "update specials set day_number='1' where dayofweek='Sunday'";
	mysql_query($updateqry);
	$updateqry = "update specials set day_number='2' where dayofweek='Monday'";
	mysql_query($updateqry);
	$updateqry = "update specials set day_number='3' where dayofweek='Tuesday'";
	mysql_query($updateqry);
	$updateqry = "update specials set day_number='4' where dayofweek='Wednesday'";
	mysql_query($updateqry);
	$updateqry = "update specials set day_number='5' where dayofweek='Thursday'";
	mysql_query($updateqry);
	$updateqry = "update specials set day_number='6' where dayofweek='Friday'";
	mysql_query($updateqry);
	$updateqry = "update specials set day_number='7' where dayofweek='Saturday'";
	mysql_query($updateqry);
	}	//end of update query







echo '<div align="center"><table border=0 cellpadding=0 cellspacing=8 width="100%"><tr><td>';

echo "<div align=center><font color='#368ff2'>Note:</font> this page is used to manage the specials shown on your specials page.<br>
	If you want to change the other content on the specials page, <a href='editpages.php?a=select&pagename=SPECIALS'><font color='#368ff2'>click here</font></a>.<br /><br /></div>";
echo'<center><form action="' . $_SERVER['PHP_SELF'] . '?a=add" method="post">Add new special: (title) <br><input type="text" name="title" size=50>

		<input id="save-button" type="submit" name="save" value="Save">
		</form></center>
    <br>';

// Get specials order by
$sql = "SELECT specials_sort_by
		FROM storePrefs
		LIMIT 1";
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) == 1) {
	$row = mysql_fetch_assoc($result);
	$orderby = $row['specials_sort_by'];
} else {
	$orderby = 0;
}
echo "<div>Order specials by: ";
echo '<select id="specials-order-by">';
echo "<option value='0'";
if($orderby=='0'){echo " selected='selected'";}
echo ">Day of Week</option>";
echo "<option value='1'";
if($orderby=='1'){echo " selected='selected'";}
echo ">Drag-n-drop</option>";
echo "<option value='2'";
if($orderby=='2'){echo " selected='selected'";}
echo ">Alphabetical</option>";
echo "<option value='3'";
if($orderby=='3'){echo " selected='selected'";}
echo ">Order of entry</option>";
echo "</select></div>";

//begin expandable accordion section
echo '<div id="specials" class="arrowlistmenu">';
$query = "SELECT * from specials";
switch ($orderby) {
	case '0':
		$query .= " ORDER BY day_number";
		break;
	case '1':
		$query .= " ORDER BY sort_order";
		break;
	case '2':
		$query .= " ORDER BY title";
		break;
	case '3':
		$query .= " ORDER BY recordkey";
		break;
}

$rt=mysql_query($query);
while($nt=mysql_fetch_array($rt)){
	echo '<div class="specials-row">';
	echo '<input type="hidden" name="sort_order[]" value="'.$nt['recordKey'].'">';
	echo "<h3 class='menuheader expandable'>$nt[title]</h3>";	
	echo'<ul class="categoryitems">';
	echo '<div class="specials-admin-wrapper"><table><tr><td><div align=left>Record Key:<td><div align=left><input type="text" name="description" size="30" value="' . $nt[recordKey] . '" disabled="disabled">';
	echo '<tr><td><form action="' . $_SERVER['PHP_SELF'] . '?a=update&key=' . $nt[recordKey] . '" method="post"><tr><td><div align=left>Title:<td valign="top"><div align=left><input type="text" name="title" size="78" value="' . $nt[title] . '">';  

	
	
	echo '<tr><td valign=top><div align=left>Description:<td valign=top><div align=left><textarea cols=80, rows=3 name="description">' . $nt[description] . '</textarea>';  
	echo '<tr><td valign=middle><div align=left>Day of week:<td valign=top><div align=left>
	
	<select name="dayselect" value="options">
	<option value="select"'; if($nt[dayofweek]=="select"){echo ' selected="selected"';} echo '>Select days for special</option>
	<option value="Weekly"'; if($nt[dayofweek]=="Weekly"){echo ' selected="selected"';} echo '>Weekly (all week)</option>
	<option value="Monday"'; if($nt[dayofweek]=="Monday"){echo ' selected="selected"';} echo '>Monday</option>
	<option value="Tuesday"'; if($nt[dayofweek]=="Tuesday"){echo ' selected="selected"';} echo '>Tuesday</option>
	<option value="Wednesday"'; if($nt[dayofweek]=="Wednesday"){echo ' selected="selected"';} echo '>Wednesday</option>
	<option value="Thursday"'; if($nt[dayofweek]=="Thursday"){echo ' selected="selected"';} echo '>Thursday</option>
	<option value="Friday"'; if($nt[dayofweek]=="Friday"){echo ' selected="selected"';} echo '>Friday</option>
	<option value="Saturday"'; if($nt[dayofweek]=="Saturday"){echo ' selected="selected"';} echo '>Saturday</option>
	<option value="Sunday"'; if($nt[dayofweek]=="Sunday"){echo ' selected="selected"';} echo '>Sunday</option>
	</SELECT><br>
	<font color="red"><i>This determines which days the special will be displayed in the "Specials" box. </font></i>
	';
	
	echo '<tr><td><div align=left>Active:<td valign=top><div align=left><input type="checkbox" name="chkactive"';
		if(!empty($nt[active])){
			echo 'checked=true';
		} 
	echo '>';
	echo'<tr><td><div align=left>Group:<td valign="top"><div align=left>';
	$qry = "select distinct specials_group from specials where specials_group >'' order by specials_group";
	$rtq=mysql_query($qry);
	if(mysql_num_rows($rtq)>'0'){
		echo'<select name="specials_group"><option value="">none</option>';	
		while($ntq=mysql_fetch_array($rtq)){
			echo "<option value='$ntq[specials_group]'";
			if($ntq[specials_group]==$nt[specials_group]){echo"selected='selected'";}
			echo">$ntq[specials_group]</option>";
		}
		echo'</select> ';
		}
	echo'Add new group: <input type="text" name="new_specials_group" size="20">';
	echo '<tr><td valign=top><div align=left>Delete:<td valign=top><div align=left><input type="checkbox" name="chkdelete" value="true">';  

	echo '<tr><td><td valign=top><input id="save-button" type="submit" name="save" value="Save"></form></td></tr></table></div>';
	echo "</ul>";
	echo '</div><!-- /.specials-row -->';
}


echo"</div><!-- /#specials -->";	


	echo '<br>
		
		</div></table></div>';
	

	

?>

<script type="text/javascript" src="includes/tinyaccordion/script.js"></script>

<script type="text/javascript">

var parentAccordion=new TINY.accordion.slider("parentAccordion");
parentAccordion.init("acc","h3",1,-1);

var nestedAccordion=new TINY.accordion.slider("nestedAccordion");
nestedAccordion.init("nested","h3",1,-1,"acc-selected");

var nestedAccordion2=new TINY.accordion.slider("nestedAccordion2");
nestedAccordion2.init("nested2","h3",1,-1,"acc-selected");


//var parentAccordion=new TINY.accordion.slider("parentAccordion");
//parentAccordion.init("acc","h3",0);

//var nestedAccordion=new TINY.accordion.slider("nestedAccordion");
//nestedAccordion.init("nested","h3",1,-1,"acc-selected");
//nestedAccordion.init("nested","h3",1,-1,"acc-selected");
</script>
<script type="text/javascript">
	function updateSpecialsOrderBy() {
		var order = $('#specials-order-by').val();

		$.ajax({
			url: 'specials_ajax.php',
			type: 'post',
			data: {action: 'update_order_by', order: order},
			dataType: 'json'
		}).done(function(response) {
			if (response.hasOwnProperty('result') && response.result == 1) {
				location.reload();
			} else {
				alert('Error updating order by.');
				console.log(response);
			}
		});
	}

	function updateSortOrder() {
		var sortOrder = {};
		var i = 1;
		$('input[name="sort_order[]"').each(function() {
			sortOrder[i] = $(this).val();
			i++;
		});
		console.log(sortOrder);

		$.ajax({
			url: 'specials_ajax.php',
			type: 'post',
			data: {action: 'update_sort_order', sort_order: sortOrder},
			dataType: 'json'
		}).done(function(response) {
			if (response.hasOwnProperty('result') && response.result == 1) {
				
			} else {
				alert('Error updating sort order.');
				console.log(response);
			}
		});
	}

	$(function() {
		$('#specials-order-by').change(function() {
			updateSpecialsOrderBy();
		});

		<?php if ($orderby == '1') : ?>
			$('#specials').sortable({
				axis: 'y',
				update: function() {
					updateSortOrder();
				}
			});
		<?php endif; ?>
	});
</script>