<?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);

$action          = $_GET["a"];
$pageID = $_GET["listid"];

if(!isset($_SESSION['listid'])){
	if(isset($pageID)){
		$_SESSION['listid']=$pageID;
	}
} else {	//listid exists in session
	if(!isset($pageID)){
		$pageID = $_SESSION['listid'];
	}
}
if(!isset($pageID)){
	echo "You have arrived here in error. No listing page selected.";
	//exit;
	echo '<script type="text/javascript">
           window.location = "index.php"
      </script>';
} else {
	//echo "pageid: $pageID"; //for troubleshooting
}
if ($action == "add") {
			
			$query = "Insert into list_content (title, listID) Values ('" . mysql_real_escape_string($_POST['title']) . "','$pageID' )";

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

if ($action == "update") {
$checkbox = $_POST['chkdelete'];
$active = $_POST['chkactive'];
$display_weekdays = $_POST['chk_display_weekdays'];
$display_dates = $_POST['chk_display_dates'];

if(!empty($_POST['list_group'])){$group=mysql_real_escape_string($_POST['list_group']);}
if(!empty($_POST['new_list_group'])){$group=mysql_real_escape_string($_POST['new_list_group']);}

	if (empty($checkbox)) {
		//delete not checked, save other updated info
		//print_r($_POST);
		
		//description is a variable named field
		foreach($_POST as $key => $value){
	        if(strpos($key, 'description') !== 0){
	        	//not a description field	
	        } else {	
	            $posted_description = mysql_real_escape_string($value);
			}    
	    }

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

		//echo "<br>$query<br>";
		

		// Check for uploaded image
		if (imageUploaded()) {
			removeUploadedImage($_GET['key']);
			$imageName = saveUploadedImage();
		} elseif (isset($_POST['remove_image']) && $_POST['remove_image'] == 'true') {
			removeUploadedImage($_GET['key']);
			$imageName = '';
		}
		if (isset($imageName)) {
			$query .= ", image_name = '".mysql_real_escape_string($imageName)."'";
		}

		//echo "date: $_POST[postdate]";
		$postdate = new DateTime(mysql_real_escape_string($_POST['postdate']));
		$postdate = date_format($postdate, 'Y-m-d');
		$query .=", date = '$postdate'";


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

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

		

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

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

	//confirmation message that delete worked...
	echo "<font color=red>Item 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 list_content set day_number='1' where dayofweek='Sunday'";
	mysql_query($updateqry);
	$updateqry = "update list_content set day_number='2' where dayofweek='Monday'";
	mysql_query($updateqry);
	$updateqry = "update list_content set day_number='3' where dayofweek='Tuesday'";
	mysql_query($updateqry);
	$updateqry = "update list_content set day_number='4' where dayofweek='Wednesday'";
	mysql_query($updateqry);
	$updateqry = "update list_content set day_number='5' where dayofweek='Thursday'";
	mysql_query($updateqry);
	$updateqry = "update list_content set day_number='6' where dayofweek='Friday'";
	mysql_query($updateqry);
	$updateqry = "update list_content set day_number='7' where dayofweek='Saturday'";
	mysql_query($updateqry);
	}	//end of update query
	
		//get page name
		$query = "SELECT pageTitle, recordKey, list_order_by, list_show_dates, list_show_days from content where pageID = '$pageID'";
		$rt=mysql_query($query);   
		while($nt=mysql_fetch_array($rt)){
			echo "Managing list items for: <b>$nt[pageTitle]</b> <span style='float:right;'><a id='save-button' href='editpages.php?page=$nt[recordKey]'>Return to Page Editor</a></span>";
			$orderby = $nt[list_order_by];
			$show_dates = $nt[list_show_dates];
			$show_days = $nt[list_show_days];
		}
		
		switch ($orderby) {
			case 0:
			echo "weekday";
			$order_clause = " order by day_number";
			break;
			
			case 1:
			$order_clause = " order by date";
			break;
			
			case 2:
			$order_clause = " order by title";
			break;
			
			case 3:
			$order_clause = " order by recordKey";
			break;
			
			case 4:
			$order_clause = " order by sort_order";
			break;
			
			default:
			$order_clause = " order by title";
			break;
		}

		$query = "SELECT * from list_content where listID = '$pageID' $order_clause";
		
		$rt=mysql_query($query);          
		echo mysql_error();               





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

echo'<center><form action="' . $_SERVER['PHP_SELF'] . '?a=add" method="post">Add new item: (title) <br><input type="text" name="title" size=50>

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

echo "<div>Order items by: ";
echo '<select id="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 ">Date</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 ">Recordkey</option>";
echo "<option value='4'";
if($orderby=='4'){echo " selected='selected'";}
echo ">Drag-n-drop</option>";
echo "</select>";

	echo 'Display weekday: <input type="checkbox" id="chk_display_weekday" name="chk_display_weekday"';
	if($show_days==1){echo ' checked=checked';}
	echo'>';

	echo 'Display dates: <input type="checkbox" id="chk_display_dates" name="chk_display_dates"';
	if($show_dates==1){echo ' checked=checked';}
	echo'>';
echo "</div>";
echo '<div id="list-items" class="arrowlistmenu">';
$x=1;
while($nt=mysql_fetch_array($rt)){
	
	echo '<div>';
	echo '<input type="hidden" name="sort_order[]" value="'.$nt['recordKey'].'">';
	echo '<h3 class="menuheader expandable">'.$nt[title].'</h3>';
	echo '<div class="categoryitems specials-admin-wrapper">';
	$textarea_name = "description$x";
	echo '<table><tr><td><div align=left>Record Key:<td><div align=left><input type="text" name="recordkey" size="30" value="' . $nt[recordKey] . '" disabled="disabled">';
	echo '<tr><td><form action="' . $_SERVER['PHP_SELF'] . '?a=update&key=' . $nt[recordKey] . '" method="post" enctype="multipart/form-data"><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="'.$textarea_name.'" id="'.$textarea_name.'">' . $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 item</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> ';

	echo '<br>';
	
	echo '<tr><td>Date: <td><input type="text" id="datepicker" name="postdate" value="'.$nt[date].'"> ';
	echo "Display time: <input type='text' name='display_time' value='".$nt[time_displayed]."'>";
	
	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 list_group from list_content where list_group >'' order by list_group";
	$rtq=mysql_query($qry);
	if(mysql_num_rows($rtq)>'0'){
	echo'<select name="list_group"><option value="">none</option>';	
	while($ntq=mysql_fetch_array($rtq)){
		echo "<option value='$ntq[list_group]'";
		if($ntq[list_group]==$nt[list_group]){echo"selected='selected'";}
		echo">$ntq[list_group]</option>";
	}
	echo'</select> ';
	}
	echo'Add new group: <input type="text" name="new_list_group" size="20">';
	
	echo '<tr>';
	echo '<td valign=top><div align=left>Image:</div></td>';
	echo '<td>';
	if (!empty($nt['image_name'])) {
		echo '<img src="/custom/images/'.$nt['image_name'].'" width="100">';
		echo '<br>';
	}
	echo '<input type="file" name="image">';
	echo '</td>';
	echo '</tr>';

	if (!empty($nt['image_name'])) {
		echo '<tr>';
		echo '<td valign=top><div align=left>Remove Image:</div></td>';
		echo '<td valign=top><div align=left><input type="checkbox" name="remove_image" value="true"></div></td>';
		echo '</tr>';
	}

	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>';
	echo '</table>';
	echo '</div><!-- /.categoryitems -->';
	echo '</div>';
	$x++;
}
echo '</div>';

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


	
		

	echo '    <!--<form action="' . $_SERVER['PHP_SELF'] . '?a=add" method="post">Add new item: (title) <br><input type="text" name="title" size=50>

		<input id="save-button" type="submit" name="save" value="Save">
		</form>-->
    <br>
		
		</div></table></div>';
	
	//duplicate ckeditor replace script, since multiple instances per page...need to dynamically create the textarea names	
	$y=1;
	while($y<$x){
		$editor_name = "description$y";	
?>
<script type="text/javascript" >
CKEDITOR.replace( '<?php echo $editor_name;?>',
{	
	filebrowserBrowseUrl : 'ckfinder/ckfinder.html',
	filebrowserImageBrowseUrl : 'ckfinder/ckfinder.html?type=Images',
	filebrowserFlashBrowseUrl : 'ckfinder/ckfinder.html?type=Flash',
	filebrowserUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
	filebrowserImageUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
	filebrowserFlashUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash',
	
	toolbarGroups: [
		/*{ name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },*/
		/*{ name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },*/
		{ name: 'links'},		
		/*{ name: 'others' },*/
		/*'/',*/
		{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
		/*{ name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align'] },*/
		/*{ name: 'styles', 	   }*/
		/*{ name: 'styles', 	   items: [ 'Styles', 'Format', 'Font', 'FontSize'] }*/

	],
    uiColor: '#499ED7'
});

</script>
<?php
	$y++; 
}
?>
<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 updateOrderBy() {
		var order = $('#order-by').val();

		$.ajax({
			url: 'list_items_ajax.php',
			type: 'post',
			data: {action: 'update_order_by', id: '<?php echo $pageID; ?>', 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 updateDateOptions() {
	//Check display week 
		if ($('#chk_display_weekday').is(":checked"))
		{
		var show_weekdays = 1;
		}else{
		var show_weekdays = 0;
		}
	//Check display dates 
		if ($('#chk_display_dates').is(":checked"))
		{
		var show_dates = 1;
		}else{
		var show_dates = 0;
		}

		$.ajax({
			url: 'list_items_ajax.php',
			type: 'post',
			data: {action: 'update_date_options', id: '<?php echo $pageID; ?>', show_dates: show_dates, show_weekdays: show_weekdays},
			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: 'list_items_ajax.php',
			type: 'post',
			data: {action: 'update_sort_order', id: '<?php echo $pageID; ?>', 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() {
		$('#order-by').change(function() {
			updateOrderBy();
		});
		$('#chk_display_weekday').change(function() {
			updateDateOptions();
		});
		$('#chk_display_dates').change(function() {
			updateDateOptions();
		});

		<?php if ($orderby == '4') : ?>
			$('#list-items').sortable({
				axis: 'y',
				update: function() {
					updateSortOrder();
				}
			});
		<?php endif; ?>
	});
</script>
<script>
  $(document).ready(function() {
    $("#datepicker").datepicker();
  });
  </script>
<?php
function imageUploaded() {
	if (isset($_FILES) && isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
		// Check to make sure it's an image
	    $check = getimagesize($_FILES["image"]["tmp_name"]);
	    if($check !== false) {
	        return true;
	    }
	}

	return false;
}
function saveUploadedImage() {
	$imageName = '';

	$dir = realpath('../custom/images/');
	$filenameParts = pathinfo($_FILES['image']['name']);
	$filename = strtolower(preg_replace("/[^a-zA-Z0-9]+/", "", $filenameParts['filename']));
	$ext = strtolower($filenameParts['extension']);

	$newFilename = $filename.'.'.$ext;
	$i = 2;
	while (file_exists($dir.'/'.$newFilename)) {
		$newFilename = $filename.'-'.$i.'.'.$ext;
	}

	$dest = $dir.'/'.$newFilename;
	if (move_uploaded_file($_FILES['image']['tmp_name'], $dest)) {
		// resize image
		require_once('includes/smart_resize_image.php');

		list($width, $height) = getimagesize($dest);
		if ($width > 250 || $height > 250) {
			if ($width >= $height) {
				smart_resize_image($dest, 250, 0, true, $dest);
			} else{
				smart_resize_image($dest, 0, 250, true, $dest);
			}
		}

		$imageName = $newFilename;
	}

	return $imageName;
}
function removeUploadedImage($id) {
	$sql = "SELECT image_name
			FROM list_content
			WHERE recordKey = '".mysql_real_escape_string($id)."'";
	$result = mysql_query($sql) or die(mysql_error());

	if (mysql_num_rows($result) < 1) {
		return false;
	}

	$row = mysql_fetch_assoc($result);
	$imageName = $row['image_name'];

	if (empty($imageName)) {
		return false;
	}

	$dir = realpath('../custom/images/');
	$path = $dir . '/' . $imageName;
	if (file_exists($path)) {
		unlink($path);
	}
}
?>