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

echo "These are the links in the footer section of your website. Simply drag and drop them into the order you want them to appear on your website.<br><br>";

//require_once ('mysql_connect.php');
$action          = $_GET["a"];
$del_item			= $_GET["item"];
$builtin			= $_GET["builtin"];
$filename			= $_GET["filename"];
$pageid			= $_GET["pageid"];

if(($action=="addfile")&&(!empty($filename))){ //add pdf doc to nav menu
	$button_text = $filename;
	$button_text = str_ireplace('.pdf', '', $button_text);
	$button_text = str_replace('_', ' ', $button_text);
	$button_text = strtoupper($button_text);	
	$sql="Insert into footer_links (link_text, url, sequence) values ('$button_text','$filename','0')";
	//echo "sql=" . $sql . "<br>";
	if(mysql_query($sql)){
		echo "<center><font color='red'>Document link button added successfully to menu</font></center>";
	} else {
		echo "<center><font color='red'>There was a problem saving the item to the menu.</font></center>";
	}
}

if(($action=="addpage")&&($pageid !="")){
	$sql="SELECT * from footer_links where pageid='$pageid'";
	$rt=mysql_query($sql); 
	if(mysql_num_rows($rt)==0){
		//add pdf doc to nav menu
		$sql="INSERT INTO footer_links ( button_text, button_url, nav_order, pageid) SELECT pageTitle, permalink, pageOrder, pageID from content where pageID ='$pageid'";
		
	} else {
		$sql="UPDATE footer_links set active='1' where pageid='$pageid'"; 
	}
	//echo "sql=" . $sql . "<br>";
	if(mysql_query($sql)){
		echo "<center><font color='red'>Page added successfully to menu</font></center>";
	} else {
		echo "<center><font color='red'>There was a problem saving the item to the menu.</font></center>";
	}
	$sql="SELECT * from footer_links where pageid='$pageid'";
	$rt=mysql_query($sql); 
	while($nt=mysql_fetch_array($rt)){
		if(empty($nt[button_url])){
			$sql="update footer_links set button_url='core.php&pageid=$pageid' where pageid='$pageid'";
			mysql_query($sql);
		}
	}
}

if($_POST[add_new]){
	$button_text = mysql_real_escape_string(strtoupper($_POST[button_text]));
	$button_url = mysql_real_escape_string($_POST[button_url]);
	if((!empty($button_text))&&(!empty($button_url))){
		$sql="Insert into footer_links (link_text, url, sequence) values ('$button_text','$button_url','0')";
		if(mysql_query($sql)){
			echo "<center><font color='red'>Link added successfully to footer</font></center>";
		} else {
			echo "<center><font color='red'>There was a problem saving the link to the footer.</font></center>";
		}
	} else {
		echo "<center><font color='red'>There was a problem saving the link to the footer. Please make sure you fill in the Link text AND the URL.</font></center>";
	}
}

if(($action=="delete")&&(!empty($del_item))){
	if($builtin=='0'){
		$sql="delete from footer_links where recordkey='$del_item'";
	} else {
		$sql="update footer_links set active='0' where recordkey='$del_item'";
	}
		//echo "qry=". $sql;
	if(mysql_query($sql)){
		echo "<center><font color='red'>Link removed successfully from footer</font></center>";
	}
}

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

//display current menu order	
$docqry="Select * from footer_links order by sequence, recordkey";
$rt=mysql_query($docqry); 
echo '<div id="menusort" class="dd current">';
echo '<h2>Current Links Displayed</h2>';
if (mysql_num_rows($rt) == 0) {
	echo '<div class="dd-empty"></div>';
} else {
	echo"<ol class='dd-list'>";
	$x=0;
	while($nt=mysql_fetch_array($rt)){
		$id="page-".$nt[recordkey];
		if($nt[pageid] != NULL){
			$qry = "select * from content where pageID='".$nt[pageid]."'";
			//echo "qry=". $qry;
				$rt2=mysql_query($qry);  
				while($nt2=mysql_fetch_array($rt2)){
					//$permalink = $nt2[permalink];
					$alias = $nt2[alias];
					//echo "alias=". $alias;
					if(empty($alias)){
						$label = $nt2[pageTitle];
					} else {
						$label=$alias;
					}
					
				}
		} else {
			$label = $nt[link_text];
		}
		//$id=$nt[recordkey];
		//if($nt[button_url]=="orderredirect.php"){$builtin=1;} else {$builtin=0;}
		echo '<li class="dd-item" id="'.$id.'" name="'.$id.'" data-recordkey="'.$nt['recordkey'].'" data-pageid="'.$nt['pageid'].'" data-type="';
		if($nt['doc_link'] == 1) {
			echo 'doc';
		}elseif($nt['pageid'] != 0) {
			echo 'page';
		}elseif(empty($nt['pageid'])) {
			echo 'custom';
		}
		echo '">';
		echo '<span class="dd-handle">';
		echo $label;
		echo '</span>';
		echo ' <span class="remove-icon"><a class="remove-nav-item" href="#"><img src="../images/remove-icon.png" title="Remove from footer"></a></span>';
		/*
		$docqry2="Select * from footer_links order by sequence, recordkey ";
		$rt2=mysql_query($docqry2); 
		if(mysql_num_rows($rt2) > 0) {	
			echo'<ol class="dd-list" id="menusort'.$x.'">';
			while($nt2=mysql_fetch_array($rt2)){
				$id="subpage-".$nt2[recordkey];
				//if($nt2[button_url]=="orderredirect.php"){$builtin=1;} else {$builtin=0;}
				echo'<li id="'.$id.'" class="dd-item" name="'.$id.'" data-recordkey="'.$nt2['recordkey'].'" data-pageid="'.$nt2['pageid'].'" data-type="';
				if($nt2['custom'] == 1) {
					echo 'custom';
				}elseif($nt2['navdoc'] == 1) {
					echo 'doc';
				}elseif($nt2['pageid'] != 0) {
					echo 'page';
				}
				echo '">';
				echo '<span class="dd-handle">';
				echo $nt2[button_text];
				echo '</span>';
				echo '<span class="remove-icon"><a class="remove-nav-item" href=""><img src="../images/remove-icon.png" title="Remove from menu"></a></span>';
				echo '</li>';
				
			}
			echo'</ol>';
		}
		*/
		echo '</li>';
		$x++;
	}	
	echo"</ol>";
	
}
echo '</div>';

//show active pages that are not in the footer
echo '<div id="available-pages">';
echo '<h2>Available Pages</h2>';
echo '<div class="dd available pages">';

$items = '';
$pageqry="Select * from content where active='1' and pageID not in (select pageid as pageID from footer_links where pageid is not null)";
$rt=mysql_query($pageqry); 
while($nt=mysql_fetch_array($rt)){
	$pageqry2="Select * from footer_links where pageid = '" . $nt[pageID] ."'";
	$rt2=mysql_query($pageqry2); 
	if (mysql_num_rows($rt2) == 0) {  //if not listed, add now
		$items .= "<li class='dd-item' data-type='page' data-new='true' data-pageid='".$nt['pageID']."'>";
		$items .= '<span class="dd-handle">';
		$items .= $nt[pageTitle];
		// echo "<div class='add-to-menu'><a href='?a=addpage&pageid=".$nt[pageID]."'>Add to menu</a></div>";
		$items .= '</span>';
		$items .= "</li>";
	}	
}
//check if ordering button is active
/*
$docqry="Select * from footer_links where button_url='orderredirect.php'";
$rt=mysql_query($docqry); 
while($nt=mysql_fetch_array($rt)){
	if($nt[active]=='0'){
		$items .= "<li class='dd-item' data-type='doc' data-new='true'>";
		$items .= '<span class="dd-handle">';
		$items .= $nt[button_text];
		// echo "<div class='add-to-menu'><a href='?a=addpage&pageid=".$nt[pageid]."'>Add to menu</a></div>";
		$items .= '</span>';
		$items .= "</li>";
	}
}
*/
if (!empty($items)) {
	echo "<ol id='ol-available-pages' class='dd-list'>";
	echo $items;
	echo '</ol>';
} else {
	echo '<div class="dd-empty"></div>';
}
echo '</div>';

echo "<h2>Available PDF Documents</h2>";
echo '<div class="dd available docs">';
//show docs in the library that are not in the menu
$items = '';
if ($handle = opendir('../docs')) {
    /* This is the correct way to loop over the directory. */
    while (false !== ($file = readdir($handle))) {
		if ($file != "." && $file != "..") {				
			//check if file listed in footer_links
			$pageqry="Select * from footer_links where url = '" . $file ."'";
			$rt=mysql_query($pageqry); 
			if (mysql_num_rows($rt) == 0) {  //if not listed, add now
				$items .= "<li class='dd-item' data-new='true' data-type='doc' data-filename='".$file."'>";
				$items .= '<span class="dd-handle">';
				$items .= $file;
				// echo "<div class='add-to-menu'><a href='?a=addfile&filename=".$file."'> Add to menu</a></div>";
				$items .= '</span>';
				$items .= "</li>";
			} else {	//if listed, delete now
				//echo '<font color="green">Yes</font>';
			}	
			mysql_close;	
		}
    }
    closedir($handle);
}

if (!empty($items)) {
	echo '<ol id="ol-available-docs" class="dd-list">';
	echo $items;
	echo "</ol>";
} else {
	echo '<div class="dd-empty"></div>';
}

echo '</div> <!--end dd class -->';
echo '</div>';
?>

<script>
// $("#menusort").sortable({
//     axis: 'y',
//     stop: function (event, ui) {
//         var data = $(this).sortable("serialize").toString();
// 		var idsInOrder = $(this).sortable("toArray").toString();
// 		//alert(idsInOrder); //popup alert to show data for testing		
// 		//var elem = document.getElementById("results").value = idsInOrder;	//update results input field for testing
//         $.ajax({
//             data: data,
//             type: 'POST',
//             url: 'save_menu_order.php'
//         });
//     }
// });
function updateOrder() {
	// add X button if not there
	$('.dd.current li').each(function() {
		if($(this).children('span.remove-icon').length == 0) {
			$(this).append('<span class="remove-icon"><a class="remove-nav-item" href="#"><img src="../images/remove-icon.png" title="Remove from footer"></a></span>');
		}
	});

	// remove X button for available pages, docs
	$('.dd.available li').each(function() {
		if($(this).children('span.remove-icon').length != 0) {
			$(this).children('span.remove-icon').remove();
		}
	});

	order = window.JSON.stringify($('#menusort').nestable('serialize'));
	// console.log(order);

	$.ajax({
		url: 'save_footlink_order.php',
		type: 'post',
		data: {menuOrder: order}
	});

	// check list items of available pages and docs
	$('.dd.pages li').each(function() {
		var type = $(this).data('type');
		if(type == 'doc') {
			if($('.dd.docs .dd-list').length == 0) {
				$('.dd.docs .dd-empty').remove();
				$('.dd.docs').append('<ol class="dd-list"></ol>');
			}

			$('.dd.docs .dd-list').append($(this));			
		}
	});

	// check list items of available pages and docs
	$('.dd.docs li').each(function() {
		var type = $(this).data('type');
		if(type == 'page') {
			if($('.dd.pages .dd-list').length == 0) {
				$('.dd.pages .dd-empty').remove();
				$('.dd.pages').append('<ol class="dd-list"></ol>');
			}

			$('.dd.pages .dd-list').append($(this));
		}
	});


	if($('.dd.docs .dd-list li').length == 0 && $('.dd.docs .dd-list').length > 0) {
		$('.dd.docs .dd-list').remove();
		$('.dd.docs').append('<div class="dd-empty"></div>');
	}

	if($('.dd.pages .dd-list li').length == 0 && $('.dd.pages .dd-list').length > 0) {
		$('.dd.pages .dd-list').remove();
		$('.dd.pages').append('<div class="dd-empty"></div>');
	}
}
$(document).ready(function() {
	$('#menusort').nestable({
		maxDepth: 1,
		group: 1
	}).on('change', function() {
		updateOrder();
	});

	$('.dd.available').nestable({
		maxDepth: 1,
		group: 1
	}).on('change', function() {
		updateOrder();
	});

	$(document).on('click', 'a.remove-nav-item', function(e) {
		liObj = $(this).closest('li');

		type = liObj.data('type');

		liObj.children('span.remove-icon').remove();

		if(type == 'doc') {
			$('#ol-available-docs').append(liObj);
		} else if(type == 'page') {
			$('#ol-available-pages').append(liObj);
		} else {
			liObj.remove();
		}

		// check if empty
		if ($('#menusort li').length == 0) {
			$('#menusort ol').remove();
			$('#menusort').append('<div class="dd-empty"></div>');
		}

		updateOrder();

		e.preventDefault();
	});
});


</script>
<?php /*
	$j=0;
	while ($j<=$x){
?>
		<script>$("#menusort<?php echo $j;?>").sortable({
    axis: 'y',
    stop: function (event, ui) {
        var data = $(this).sortable("serialize").toString();
		var idsInOrder = $(this).sortable("toArray").toString();
		//alert(idsInOrder); //popup alert to show data for testing		
		//var elem = document.getElementById("results").value = idsInOrder;	//update results input field for testing
        $.ajax({
            data: data,
            type: 'POST',
            url: 'save_submenu_order.php'
        });
    }
});
</script>
<?php
$j++;
	} */
?>
<div id="add-custom-link">
<form action="" method="POST">
<h2>Add Custom Navigation Link</h2>
<p>Link navigation to external web links</p>
Link text: <input type="text" name="button_text" size="30"><br />
<p>The text you want to display as a navigation link</p>
URL: <input type="text" name="button_url" size="36">
<br /><p>Paste link to page you want button to link to here</p>
<input id="save-button" type="submit" name="add_new" value="Save to Footer Menu">

</form>
</div>
<!--<p><input type="text" name="results" id="results" value=""></p>-->