<?php
include("functions.php");
include("rules.php");

header( "Cache-Control: no-cache, must-revalidate" );
header( "Pragma: no-cache" );



//header("Cache-Control: no-cache, must-revalidate");

//error_reporting('0');
//ini_set('display_errors', '0');

$dbhost = 'db.washingtonyachtclub.org';
$dbuser = 'wyc';
$dbpass = 'WYC#Sail!Pass';
$database = 'production';

$conn = mysql_connect($dbhost, $dbuser, $dbpass);
@mysql_select_db($database) or die( "Unable to select database");

if(isset($_COOKIE['ID_wycnumber']))
{
	$wycnumber = parseInput($_COOKIE['ID_wycnumber']);
	$password = parseInput($_COOKIE['Key_site']);
	$query = "SELECT StudentID FROM WYCDatabase WHERE wycnumber = '$wycnumber' and password = PASSWORD('$password')";
	$check = mysql_query($query)or die(mysql_error());

	$check2 = mysql_num_rows($check);
	if ($check2 == 0)
		header("Location: login.php");
	else
	{
		$studentid=mysql_result($check,0,"StudentID");
		$check4 = getAllowReservations($_SERVER['REMOTE_ADDR']);
		
		//don't allow members without a KB rating to check out a boat
		$ratingQuery= "SELECT * FROM wyc_ratings JOIN ratings ON rating = ratings._index WHERE member = '$wycnumber' and is_kb";
		$ratingMySQL = mysql_query($ratingQuery)or die(mysql_error());
		$hasRating = mysql_num_rows($ratingMySQL);
		if (($check4 == 0 | $is_guest) | $hasRating == 0)
			$allowReservation=0;
		else
			$allowReservation=1;


		$ruleviolation=0;
		$conflicting=0;

		if($allowReservation==1)
		{
			// Gather variables from query strings and break them down for usage in our script
			if(!isset($_REQUEST['date']))
			{
				$date = mktime(0,0,0,date('m'), date('d'), date('Y'));
			}
			else
			{
				$date = $_REQUEST['date'];
			}
			$fromdate = $date;
			$untildate = $date;

			if (!$_REQUEST['boatname'])
				die("You didn't choose a boat to reserve.");
			if(!$_REQUEST['from'])
				die("You didn't enter a departure date.");
			if(!$_REQUEST['rFrom'])
				die("You didn't enter a departure time.");
			if(!$_REQUEST['until'])
				die("You didn't enter a return date.");
			if(!$_REQUEST['rUntil'])
				die("You didn't enter a return time.");
			if(!$_REQUEST['destination'])
				die("You didn't enter a destination.");
			if(!$_REQUEST['phone'])
				die("You didn't enter a phone number.");

			$boatname = parseInput($_REQUEST['boatname']);
			$wycnum = parseInput($_COOKIE['ID_wycnumber']);

			$temp = parseInput($_REQUEST['from']);
			$fromdate = stringToDate($temp, 0, "From field not formatted correctly");
			if($fromdate==0)
				die();
			if($temp == "")
				$fromdate = $date;


			$rFrom = parseInput($_REQUEST['rFrom']);

			$temp = parseInput($_REQUEST['until']);
			$untildate = stringToDate($temp, 0, "Until field not formatted correctly");
			if($untildate==0)
				die();
			if($temp == "")
				$untildate = $date;
			$rUntil = parseInput($_REQUEST['rUntil']);


			$destination = parseInput($_REQUEST['destination']);
			if(!parseInput($_REQUEST['numcrew']))
				$numcrew = 0;
			else
				$numcrew = parseInput($_REQUEST['numcrew']);
			$phone = parseInput($_REQUEST['phone']);
			$comments = parseInput($_REQUEST['comments']);
			$existscomment=true;
			if(!parseInput($_REQUEST['comments']))
				$existscomment=false;

			if($rFrom=="morning")
				$from = date("Y-m-d", $fromdate) . " 03:00:00";
			else
				$from = date("Y-m-d", $fromdate) . " 15:00:00";

			if($rUntil=="morning")
				$until = date("Y-m-d", $untildate) . " 03:00:00";
			else
				$until = date("Y-m-d", $untildate) . " 15:00:00";

			if(datetime($until)<datetime($from))
				die("You specified a reservation that ends before it starts!");
			if(mktime(0,0,0,date('m'), date('d'), date('Y')) > datetime($from))
				die("You are trying to make a reservation which starts in the past!");
			if(mktime(0,0,0,date('m'), date('d'), date('Y')) > datetime($until) )
				die("You are trying to make a reservation which ends in the past!");
			if(mktime(0,0,0,date('m'), date('d'), date('Y')+1) < $fromdate || mktime(0,0,0,date('m'), date('d'), date('Y')+1) < $untildate)
				die("You cannot make a reservation that spans more than one year into the future.");


			$error_message="";

			?>
<html>
<head>
	<title>Washington Yacht Club Reservations - Unable to reserve!</title>
    <link rel="stylesheet" type="text/css" href="css/wyc.css">
</head>
<body>
	<table style="width:100%">
		<tr>
		<td style="vertical-align:top; text-align:left; width:150px">
			<a href="http://www.washingtonyachtclub.com"><img src="images/burgee_purple.gif" alt="burgee_purple" /></a>
		</td>
		<td style="vertical-align:top">
			<span style="font-size:30">Washington Yacht Club</span><br />
			<span style="font-size:18">Keelboat availability</span>
		</td>
		<td style="vertical-align:top; text-align:right; width:250px">
			<b>Remember to <a href="logout.php">Logout</a></b>
		</td>
		</tr>
	</table>
	<br /><br />
	<?php

			//see if this user is an admin
			$queryadmin = "SELECT wycnum FROM calendaradmin WHERE wycnum = '$wycnumber'";
			$checkadmin = mysql_query($queryadmin)or die(mysql_error());
			$isadmin = mysql_num_rows($checkadmin);


			//check for rule reservation rule violations
			if(checkCompliance($wycnumber, datetime($from), datetime($until))==0 && $isadmin==0)
			{
				$ruleviolation=1;
			}
			else
			{
				$rulviolation=0;

				//check for conflicting reservations
				$queryOldReservations = "select * from calendartable t, calendarboats b where t.cboatid=b.cboatid and t.reserveFrom <= '".$until."' and t.reserveTo >= '".$from."' and b.name = '" . $boatname . "'";
				$resultOldReserves=mysql_query($queryOldReservations);

				$checkPriorReserveCount = mysql_num_rows($resultOldReserves);
				if ($checkPriorReserveCount > 0)
				{
					//cannot reserve - conflicting dates
					$conflicting = 1;
					mysql_close();
				}
				else
				{
					$conflicting=0;

					//calculate # of (half)weekdays/ends
					$fromdt =  datetime($from);
					$untildt = datetime($until);


					$idate = mktime(0,0,0,date('m', $fromdt),date('d', $fromdt)+1,date('Y', $fromdt));
					$edate = mktime(0,0,0,date('m', $untildt),date('d', $untildt),date('Y', $untildt));
					$numhalfweekdays=0;
					$numhalfweekends=0;
					$numfullweekdays=0;
					$numfullweekends=0;
					$holidays="";

					//echo strftime("%A", $rFrom) . "<br/>";
					if(strftime("%A",$fromdt)=="Saturday" || strftime("%A",$fromdt)=="Sunday" || isHoliday($fromdt))
					{
						if(isHoliday($fromdt))
						{
							$holidays=$holidays . " " . date("m-d-Y",$fromdt);
						}
						if(date('H', $fromdt)==3 && (date('H', $untildt)==15 || (date('m', $untildt)-date('m', $fromdt))!=0 || (date('d', $untildt)-date('d', $fromdt))!=0 || (date('Y', $untildt)-date('Y', $fromdt))!=0))
							$numfullweekends=$numfullweekends+1;
						else
							$numhalfweekends=$numhalfweekends+1;
					}
					else
					{
						if(date('H', $fromdt)==3 && (date('H', $untildt)==15 || (date('m', $untildt)-date('m', $fromdt))!=0 || (date('d', $untildt)-date('d', $fromdt))!=0 || (date('Y', $untildt)-date('Y', $fromdt))!=0))
							$numfullweekdays=$numfullweekdays+1;
						else
							$numhalfweekdays=$numhalfweekdays+1;
					}

					while($idate<$edate)
					{
						//echo strftime("%A", $idate) . "<br/>";
						if(strftime("%A",$idate)=="Saturday" || strftime("%A",$idate)=="Sunday" || isHoliday($idate))
						{
							if(isHoliday($idate))
							{
								$holidays=$holidays . " " . date("m-d-Y",$idate);
							}
							$numfullweekends=$numfullweekends+1;
						}
						else
						{
							$numfullweekdays=$numfullweekdays+1;
						}
						$idate = mktime(0,0,0,date('m', $idate),date('d', $idate)+1,date('Y', $idate));
					}
					if((date('m', $untildt)-date('m', $fromdt))!=0 || (date('d', $untildt)-date('d', $fromdt))!=0 || (date('Y', $untildt)-date('Y', $fromdt))!=0)
					{
						//echo strftime("%A", $rTo) . "<br/>";
						if(strftime("%A",$untildt)=="Saturday" || strftime("%A",$untildt)=="Sunday" || isHoliday($untildt))
						{
							if(isHoliday($untildt))
							{
								$holidays=$holidays . " " . date("m-d-Y",$untildt);
							}
							if(date('H', $untildt)==15)
								$numfullweekends=$numfullweekends+1;
							else
								$numhalfweekends=$numhalfweekends+1;
						}
						else
						{
							if(date('H', $untildt)==15)
								$numfullweekdays=$numfullweekdays+1;
							else
								$numhalfweekdays=$numhalfweekdays+1;
						}
					}
					//now that we've calculated (half)weekdays/ends, insert into the db and print a price on the screen as well.
					$studentprice=0;
					$nonstudentprice=0;
					//calcculate student pricing
					if($numhalfweekdays>0)
					{
						$querypricea = "select price from keelboat_pricing where student=1 and fullday=0 and weekday=1";
						//echo $queryprice;
						$hpra=mysql_query($querypricea);
						$hpricea = mysql_result($hpra,0,"price");
						$price=$price+$numhalfweekdays*$hpricea;
					}
					if($numhalfweekends>0)
					{
						$querypriceb = "select price from keelboat_pricing where student=1 and fullday=0 and weekday=0";
						//echo $queryprice;
						$hprb=mysql_query($querypriceb);
						$hpriceb = mysql_result($hprb,0,"price");
						$price=$price+$numhalfweekends*$hpriceb;
					}
					if($numfullweekdays>0)
					{
						$querypricec = "select price from keelboat_pricing where student=1 and fullday=1 and weekday=1";
						//echo $queryprice;
						$hprc=mysql_query($querypricec);
						$hpricec = mysql_result($hprc,0,"price");
						$price=$price+$numfullweekdays*$hpricec;
					}
					if($numfullweekends>0)
					{
						$querypriced = "select price from keelboat_pricing where student=1 and fullday=1 and weekday=0";
						//echo $queryprice;
						$hprd=mysql_query($querypriced);
						$hpriced = mysql_result($hprd,0,"price");
						$price=$price+$numfullweekends*$hpriced;
					}

					//calculate non-student pricing
					$nonstudentprice=0;
					if($numhalfweekdays>0)
					{
						$querypricea = "select price from keelboat_pricing where student=0 and fullday=0 and weekday=1";
						//echo $queryprice;
						$hpra=mysql_query($querypricea);
						$hpricea = mysql_result($hpra,0,"price");
						$nonstudentprice=$nonstudentprice+$numhalfweekdays*$hpricea;
					}
					if($numhalfweekends>0)
					{
						$querypriceb = "select price from keelboat_pricing where student=0 and fullday=0 and weekday=0";
						//echo $queryprice;
						$hprb=mysql_query($querypriceb);
						$hpriceb = mysql_result($hprb,0,"price");
						$nonstudentprice=$nonstudentprice+$numhalfweekends*$hpriceb;
					}
					if($numfullweekdays>0)
					{
						$querypricec = "select price from keelboat_pricing where student=0 and fullday=1 and weekday=1";
						//echo $queryprice;
						$hprc=mysql_query($querypricec);
						$hpricec = mysql_result($hprc,0,"price");
						$nonstudentprice=$nonstudentprice+$numfullweekdays*$hpricec;
					}
					if($numfullweekends>0)
					{
						$querypriced = "select price from keelboat_pricing where student=0 and fullday=1 and weekday=0";
						//echo $queryprice;
						$hprd=mysql_query($querypriced);
						$hpriced = mysql_result($hprd,0,"price");
						$nonstudentprice=$nonstudentprice+$numfullweekends*$hpriced;
					}

					$query = "insert into calendartable (cboatid, memberwycnumber, reservefrom, reserveto, destination, numberofcrew, phone, numFullWD, numHalfWD, numFullWE, numHalfWE) values ((select cboatid from calendarboats where name = '" . $boatname . "'), " . $wycnum . ", '" . $from . "', '" . $until . "', '" . $destination . "', " . $numcrew . ", '" . $phone . "', ".$numfullweekdays.", ".$numhalfweekdays.", ".$numfullweekends.", ".$numhalfweekends.");";
					$result=mysql_query($query) or die("There was a problem with the way you entered your data!<br/><br/>Check that Number of Crew is a number and that the Reserve from/until fields are formatted as (M)M-(D)D-YYYY");

					$queryGetResid = "select id from calendartable t, calendarboats b where t.cboatid=b.cboatid and b.name = '".$boatname."' and memberwycnumber = " . $wycnum . " and reservefrom = '" . $from . "' and reserveto = '" . $until . "' and destination = '" . $destination . "' and numberofcrew = " . $numcrew . " and phone = '" . $phone . "'";
					$resIdresult=mysql_query($queryGetResid);
					$resid = mysql_result($resIdresult,0,"id");

					if($comments=="")
					{
						$insertcomments="insert into calendarcomment (id, userwyc, date, comment) values (".$resid.", ".$wycnumber.", '".date("Y-m-d G:i:s")."', 'Reservation Placed')";
						mysql_query($insertcomments) or die(mysql_error());
					}
					else
					{
						$insertcomments="insert into calendarcomment (id, userwyc, date, comment) values (".$resid.", ".$wycnumber.", '".date("Y-m-d G:i:s")."', '(Comment made on reservation) ".$comments."')";
						mysql_query($insertcomments) or die(mysql_error());
					}

					mysql_close();
				}
			}
		}
		else
		{
			die ('You are only allowed to reserve from the sail locker!');
		}

	if(!$ruleviolation)
	{
		if(!$conflicting)
		{
			echo "Reservation successful! <a href=\"reservationinfo.php?resid=".$resid."\">View reservation details.</a><br/><br/><br/>";
			echo "From: ".date("(l) Y-m-d", $fromdt)." $rFrom  <a style =\"font-size:9pt\" href=\"reservationrates.php\" target=\"_blank\">(more info)</a><br/>";
			echo "Through: ".date("(l) Y-m-d", $untildt)." $rUntil  <a style =\"font-size:9pt\" href=\"reservationrates.php\" target=\"_blank\">(more info)</a><br/><br/>";
			echo "Your reservation covers:<br/>";
			echo "Full Weekdays: $numfullweekdays<br/>Half Weekdays: $numhalfweekdays<br/>Full Weekends/Holidays: $numfullweekends<br/>Half Weekends/Holidays: $numhalfweekends<br/> With holidays on the following days: $holidays <br/>";
			echo "<br/>Your reservation number is: $resid &nbsp;&nbsp;&nbsp;&nbsp;<span style=\"font-size:9pt\">This is the only thing you have to write on your payment envelope.</span>";
			echo "<br/><br/>If you are a student, the total owed amount for this reservation is: $$price";
			echo "<br/>If you are not a student, the total owed amount for this reservation is: $$nonstudentprice";
			echo "<br/><a style =\"font-size:9pt\" href=\"reservationrates.php\" target=\"_blank\">(check if this price is correct, since rates can be variable)</a>&nbsp;&nbsp;&nbsp;&nbsp;";
			echo "<span style=\"font-size:9pt\">Put a check for this amount, or cash totalling this amount in the payment envelope.</span>";
			echo "<br /><br />Thank you for your reservation! Have fun sailing and remember to leave the boat in a clean condition for the next hearty sailor.";
		}
		else
		{
			echo "You cannot reserve that time because of the following conflicting reservations that have already been made:<br />(";
			echo "Note: if you leave this page then you might not be able to get back here, so open the following links in a new window/tab)<br /><br />";
			for($i=0;$i<$checkPriorReserveCount;$i++)
			{
				$oldres = mysql_result($resultOldReserves,$i,"id");
				echo ($i+1).": <a target=\"_blank\" href=\"reservationinfo.php?resid=".$oldres."\">View conflicting reservation</a><br />";
			}
		}
	}
	else
	{
	}
	echo "<br /><br /><a href=\"cal.php?monthyear=".$fromdate."\">Go back to calendar</a><br />";

	?>

</body>
<head>

<?php

	}
}
else
	header("Location: login.php");
?>
