<?php
$admin_page = $_GET['admin-page'];

function positionX($numItems,$thisNum,$radius){
  //echo "thisNum: $thisNum<br>";
  $alpha = 360/$numItems; // angle between the elements 
  //echo "angle: $alpha<br>";
  $angle = $alpha * $thisNum; // angle for N element
  //echo "angle: $angle<br>";
  $x = $radius * cos(deg2rad($angle)); // X coordinates
  return $x;
}

function positionY($numItems,$thisNum,$radius){
  $alpha = 360/$numItems; // angle between the elements
  $angle = $alpha * $thisNum; // angle for N element
  $y = $radius * sin(deg2rad($angle)); // Y coordinates
  return $y;
}

function getCoordinates($x_coord, $y_coord, $radius){
	//based on 1degree = approx 69 miles, 
	//1 mile = approx 0.0144927536231884 degrees in coordinate location (round to 0.0144928)
	$coordstring = "";
	if($radius=="none"){return $coordstring;}
	$radius = ($radius *2); //was being used as a diameter, not radius, so need to double
	$mile_length = 0.0144928;

	$x_mile_length = $mile_length*1.3; //adjust x coordinate to keep shape round

	$numItems = 20; //number of coordinates to return

	$z = 1;
	$coordstring = "";
	while ($z < $numItems+1){
		$x_point = round(positionX($numItems,$z,$radius),7);
		//echo $x_point."<br>";
		$y_point = round(positionY($numItems,$z,$radius),7);
		//echo $y_point;
		$x_offset = $x_mile_length*$x_point;
		$y_offset = $mile_length*$y_point;
		//echo "<br>coord adjustment: ".$x_offset.", ".$y_offset."<br>"; 
		//echo "new point coordinate: ".($x_coord+$x_offset).", ".($y_coord+$y_offset); 
		$coordstring.= round(($x_coord+$x_offset),7).",".round(($y_coord+$y_offset),7)." ";
		
		$z++;
	}
	return rtrim($coordstring);
}


//if new zone submitted:
if($_POST['submit_new']){
	echo "submitted";
	if(isset($_POST['zone_name'])){
		$new_num = getNextZoneNumber();
		$name = $_POST['zone_name'];
		$deliveryCost = $_POST['delivery_cost'];
		$minOrder = $_POST['min_order'];
		
		if(isset($_FILES['kml']) && $_FILES['kml'][0] == 0 && $_FILES['kml']['name']!=""){	
			//kml file map uploaded
			$coordinates = getCoordinatesFromUploadedKmlFile();
			$coordinates = str_replace(",0.0", "", $coordinates);
			$coordinates = trim($coordinates);
		}elseif(isset($_POST['x_cordinate']) && !empty($_POST['x_cordinate']) && isset($_POST['y_cordinate']) && !empty($_POST['y_cordinate']) && isset($_POST['radius']) && !empty($_POST['radius'])){
			//map not uploaded, set using radius
			$coordinates = getCoordinates($_POST['x_cordinate'], $_POST['y_cordinate'], $_POST['radius']);	
		}

		$update = "insert into delivery_zones (zone_number, name, coordinates, cost, min_order) values (";
		
		$update .="'$new_num'";
		$update .=",'".mysql_real_escape_string($name)."', '".mysql_real_escape_string($coordinates)."', '".mysql_real_escape_string($deliveryCost)."', '".mysql_real_escape_string($minOrder)."'";
		$update .=")";

		if(mysql_query($update)){
			echo "<center><b><font color='red'>Delivery zone added.</font></b></center><br><br>";
		}		
	}
}


//if existing zone updated:
if (isset($_POST['update_zone'])) {
	$recordkey = $_POST['recordkey'];
	$zoneNumber = $_POST['zone_number'];
	$name = $_POST['zone_name'];
	$deliveryCost = $_POST['delivery_cost'];
	$minOrder = $_POST['min_order'];
	$orig_coordinates = $_POST['zone_coordinates'];
	//print_r($_POST); //die();
	//print_r($_FILES); 
	//get new zone coordinates
	if(isset($_FILES['kml']) && $_FILES['kml'][0] == 0 && $_FILES['kml']['name']!=""){
		//$test = $_FILES['kml'];
		//die("kml added: $test");			//kml file map uploaded
		$coordinates = getCoordinatesFromUploadedKmlFile();
		$coordinates = str_replace(",0.0", "", $coordinates);
		$coordinates = trim($coordinates);
		//die($coordinates);
	}elseif(isset($_POST['x_cordinate']) && !empty($_POST['x_cordinate']) && isset($_POST['y_cordinate']) && !empty($_POST['y_cordinate']) && isset($_POST['radius']) && !empty($_POST['radius'])){
		//map not uploaded, set using radius
		$coordinates = getCoordinates($_POST['x_cordinate'], $_POST['y_cordinate'], $_POST['radius']);
		//die("radius coords: $coordinates");
	}
	
	if (is_null($coordinates) || trim($coordinates=="")) {
	 	$coordinates = $orig_coordinates;
	}
	//$coordinates = str_replace(",0.0", "", $coordinates);

	$sql = "UPDATE delivery_zones
			SET 
				zone_number = '".mysql_real_escape_string($zoneNumber)."',
				name = '".mysql_real_escape_string($name)."',
				coordinates = '".mysql_real_escape_string($coordinates)."',
				cost = '".mysql_real_escape_string($deliveryCost)."',
				min_order = '".mysql_real_escape_string($minOrder)."'
			WHERE recordkey = '".mysql_real_escape_string($recordkey)."'";
	mysql_query($sql) or die(mysql_error());

	echo "<center><b><font color='red'>Delivery zone updated.</font></b></center><br><br>";
}


	//if new zone selected, add fields here
	if($_GET['new']==1){
		$longitude = '';
		$latitude = '';
		$query = "SELECT * from storePrefs";
		$rt=mysql_query($query);
		while($nt=mysql_fetch_array($rt)){
			$longitude = $nt[longitude];
			$latitude = $nt[latitude];
		}
		echo "<form action='index.php?admin-page=$admin_page' method='POST' enctype='multipart/form-data'>";
		//echo "Zone #: <input type='text' name='zone_number' size='1'><br>";
		echo "<table>
				<tr>
					<td>Zone name:</td>
					<td><input type='text' name='zone_name' size='20'><font size='1'><i>*For your own reference only</i></font></td>
				</tr>
				<tr>
					<td>Coordinates:</td>
					<td><input type='text' name='x_cordinate' value='".$longitude."' size='20' placeholder='Enter Longitude'>
					<input type='text' name='y_cordinate' value='".$latitude."' size='20' placeholder='Enter Latitude'></td>
				</tr>";
				echo "<tr>
					<td>Pick a Radius:</td>
					<td><select name='radius'>";
					echo "<option value='none'>-- None selected --</option>";
					for ($i=1; $i<=25 ; $i++) {
						if($i>1){$miles = "miles";} else {$miles="mile";}
						echo "<option value=$i>$i $miles</option>";
					}
				echo "</select></td>
					</tr>";
				
				
				
				
				echo "<tr>
					<td>OR Upload  file</td>
					<td><input type='file' name='kml' /><a href='get_coordinates.php' target='blank'><font size='1' color='blue'><i>How do I get this?</i></font></a></td>
				</tr>";
/*				echo "<tr>
					<td>Pick a Radius:</td>
					<td><select name='radius'>";
					for ($i=1; $i<=25 ; $i++) { 
						echo "<option value=$i>$i miles</option>";
					}
				echo "</select></td>
	
					</tr>";
 */
			echo "<tr>
					<td>Extra delivery charge:</td>
					<td><input type='text' name='delivery_cost' size='6'><font size='1'><i>*This would be added to the standard delivery charge.</i></font></td>
				</tr>
				<tr>
					<td>Min Order $:</td>
					<td><input type='text' name='min_order' size='6'><font size='1'><i>*Orders below this dollar amount will not be accepted.</i></font></td>
				</tr>
				<tr>
					<td><input type='submit' name='submit_new' value='Save Zone'> <button><a href='index.php?admin-page=$admin_page'>Cancel</a></button></td>
				</tr>
			</table>
		";
		echo "</form>";


		// echo "Zone name: <input type='text' name='zone_name' size='20'> <font size='1'><i>*For your own reference only</i></font><br>";
		// echo "Coordinates: <input type='text' name='x_cordinate' />	<a href='get_coordinates.php' target='blank'><font size='1' color='blue'><i>How do I get this?</i></font></a><br>";
		// echo "Extra delivery charge: <input type='text' name='delivery_cost' size='6'> <font size='1'><i>*This would be added to the standard delivery charge.</i></font><br>";
		// echo "Min Order $: <input type='text' name='min_order' size='6'> <font size='1'><i>*Orders below this dollar amount will not be accepted.</i></font><br>";
		// echo "<input type='submit' name='submit_new' value='Save Zone'> <button><a href='index.php?admin-page=$admin_page'>Cancel</a></button><br>";
	} elseif ($_GET['edit']>0){
		//edit selected zone
		$qry = "select * from delivery_zones where recordkey='$_GET[edit]'";
		$rt=mysql_query($qry);
		while($nt=mysql_fetch_array($rt)){
			echo "<form action='index.php?admin-page=$admin_page' method='POST' enctype='multipart/form-data'>";
			echo '<input type="hidden" name="recordkey" value="'.$nt['recordkey'].'">';
			echo "<table>
					<tr>
						<td>Zone #:</td>
						<td ><input type='text' name='zone_number' size='1' value='$nt[zone_number]'></td>
					</tr>";
			echo "<tr>
						<td>Zone name: </td>
						<td ><input type='text' name='zone_name' size='20' value='$nt[name]'> <font size='1'><i>*For your own reference only</i></font></td>
					</tr>";
			$longitude = '';
			$latitude = '';
			$query = "SELECT * from storePrefs";
			$rt=mysql_query($query);
			while($nt2=mysql_fetch_array($rt)){
				$longitude = $nt2[longitude];
				$latitude = $nt2[latitude];
			}
			echo "<tr>
					<td>Coordinates:</td>
					<td><input type='text' name='x_cordinate' size='20' value='$longitude' placeholder='Enter Longitude'>
					<input type='text' name='y_cordinate' size='20' value='$latitude' placeholder='Enter Latitude'></td>
				</tr>";
			echo "<tr>
					<td>Pick a Radius:</td>
					<td><select name='radius'>";
					echo "<option value='none'>-- None selected --</option>";
					for ($i=1; $i<=25 ; $i++) {
						if($i>1){$miles = "miles";} else {$miles="mile";}
						echo "<option value=$i>$i $miles</option>";
					}
			echo "</select></td>
				</tr>";
			
			
			
			echo "<tr>
					<td>OR Upload  file</td>
					<td><input type='file' name='kml' /><a href='get_coordinates.php' target='blank'><font size='1' color='blue'><i>How do I get this?</i></font></a></td>
				</tr>
				<tr>
					<td colspan='2'><textarea name='zone_coordinates' rows='3' cols='50'>$nt[coordinates]</textarea></td>
				</tr>";
			/*echo "<tr>
					<td>Pick a Radius:</td>
					<td><select name='radius'>";
					for ($i=1; $i<=25 ; $i++) { 
						echo "<option value=$i>$i miles</option>";
					}
			echo "</select></td>
				</tr>";*/
			echo "<tr>
					<td>Extra delivery charge:</td>
					<td ><input type='text' name='delivery_cost' size='6' value='$nt[cost]'> <font size='1'><i>*This would be added to the standard delivery charge.</i></font></td>
				</tr>";
			echo "<tr>
					<td>Min Order $:</td>
					<td ><input type='text' name='min_order' size='6' value='$nt[min_order]'> <font size='1'><i>*Orders below this dollar amount will not be accepted.</i></font></td>
				</tr>";
			echo "<tr>
					<td><input type='submit' name='update_zone' value='Save Zone'></td>
					<td><button><a href='index.php?admin-page=$admin_page'>Cancel</a></button></td>
				</tr>";
			echo "</table></form>";
		}
		
	
		
	} else {
		
		if ($_GET['delete']>0) {	
			$update = "delete from delivery_zones where recordkey='$_GET[delete]'";
			if(mysql_query($update)){
				echo "<center><b><font color='red'>You have successfully deleted the delivery zone.</font></b></center>";
			}
		}
		//show overview of all zones
		$qry = "select * from delivery_zones order by zone_number";
		$rt=mysql_query($qry);
			if(mysql_num_rows($rt)==0){
				echo "<center><b><font color='red'>You currently have no delivery zones added.</font></b></center>";
			} else {

	echo '<div id="single-admin-button" style="margin-top:-34px;">
	<ul>
	<a href="index.php"><li>BACK TO HOME ADMIN</li></a>
	</ul>
	</div>';

				echo "<table cellspacing=4>";
				echo "<tr><td width='50'>Zone #<td width='50'>Name<td width='280'>Coordinates<td width='80'>Del. cost<td width='70'>Min. order<td><td>
				<tr><td colspan=9><hr /></td</tr>";
				while($nt=mysql_fetch_array($rt)){
					echo '<tr>';
					echo "<td valign='top'>$nt[zone_number]</td>";
					echo "<td valign='top'>$nt[name]</td>";
					echo "<td valign='top'>$nt[coordinates]</td>";
					echo "<td valign='top'>$nt[cost]</td>";
					echo "<td valign='top'>$nt[min_order]</td>";
					echo "<td valign='top'><a id='new-button' href='zone_preview.php?zone={$nt[recordkey]}' target='_blank'>View Zone</a></td>";
					echo "<td valign='top'><a id='new-button' href='index.php?admin-page=$admin_page&edit=$nt[recordkey]'>Edit Zone</a></td>";
					echo "<td valign='top'><a id='new-button'href='index.php?admin-page=$admin_page&delete=$nt[recordkey]'>Delete Zone</a>";
				}
				echo "</table>";
				
				
				
			}
			echo "<br><br><div style='float:right;'>
			<a id='save-button' href='http://restaurant-online.biz/custom/help/delivery-zone-directions.pdf' target='_blank'>Instructions</a> &nbsp; 
			<a id='save-button' href='https://mapsengine.google.com/map/' target='_blank'>Create a new zone</a> &nbsp; 
			<a id='save-button' href='index.php?admin-page=$admin_page&new=1'>Add new zone</a></div>";


	}




function getNextZoneNumber() {
	//get highest zone number
	$qry = "select max(zone_number) as zone_number from delivery_zones";
	//echo "$qry";
	$rt=mysql_query($qry);
	if(mysql_num_rows($rt)==0){
		$new_num = 1;	
	} else {
		while($nt=mysql_fetch_array($rt)){
			$new_num = $nt['zone_number'];
			$new_num++;
		}
	}

	return $new_num;
}

function getCoordinatesFromUploadedKmlFile() {
	$coordinates = null;

	if (isset($_FILES['kml']) && $_FILES['kml'][0] == 0) {
		$fileName = $_FILES['kml']['name'];
		//die("filename: $fileName");
		$info = pathinfo($fileName);
		//print_r($info);
		//die();
		if ($info['extension'] != 'kml') {
			return $coordinates;
		}

		$destination = 'temp/temp-kml-'.time().'.kml';
		
		move_uploaded_file($_FILES['kml']['tmp_name'], $destination);
		
		$contents = file_get_contents($destination); //read contents of kml map file
		$contents = str_ireplace("\n", "", $contents); //remove line breaks
		$contents = str_ireplace("\r", "", $contents);  //remove carriage returns
		$contents = preg_replace("/ {2,}/", " ", $contents); //replace any multiple spaces with a single space
		
		//$display = str_replace("<", "&lt;", $contents);
		//die("contents: $display");
		if (preg_match('/<coordinates>(.+?)<\/coordinates>/', $contents, $matches)) {
			$coordinates = $matches[1];
			//print_r($matches);
			//die();
		}
	}

	return $coordinates;
}


?>
<?php include("admin_globals.php"); ?>
<div style="text-align:center;"><?php echo $bottom_links; ?></div>