<?php
#*******************************************************************************
# program:    main.php
# written by:    John Phillips on 2003.03.05
#
# description:    This is the main program for a classroom/lab reservation system.
#
# revisions:    
# 2003.03.09    Latest version.
#*******************************************************************************

require( "common.php" );

# ***** SECTION I - VALIDATE SESSION

# If no sessionString is passed in then we assume a student user
# and will just display a read-only room schedule.

$sessionString $_REQUEST['sessionString'];

if( empty(
$sessionString) ) {
  
$session 0;
}
else { 
  
$session 1
}

# Establish a connection to the database that will be used througout the program.
SqlStart();

# This function only returns if there is a valid sessionString
if( $session ) {
 
$userId ValidateSession$sessionString$YSP );
}


# ***** SECTION II - PROCESS LOGOUT

# Check to see if user is logging out. If so, delete the session and then
# make a new entry in the log file. Redisplay the read-only room schedule.

if( $session ) {
  if( ! empty( 
$_POST['logout'] ) ) {
    
$q "DELETE FROM ${YSP}session WHERE sessionString = '$sessionString'";
    
MYSQL_QUERY$q ) || die( "could not delete sessions: $q" );

    
$q "INSERT INTO ${YSP}log ( logId, userId, timeStamp, inOut ) ";
    
$q.= "values ( NULL, $userId, NULL, 'o' )";
    
MYSQL_QUERY$q ) || die( "could not insert exit event into user log: $q" );

    
header("Location:http://$HTTP_HOST/$DOC_ROOT/$WORKING_DIR/main.php" );
  }
}


# ***** SECTION III - GET GLOBAL SESSION VARIABLES

# If user is logged in, then find out their name.

if( $session ) {

  
$q "SELECT first, last FROM ${YSP}user WHERE userId = $userId";
  
$qResult MYSQL_QUERY$q ) or die( "Invalid query: $q" );
  
$qRow MYSQL_FETCH_OBJECT$qResult );

  
$firstName $qRow->first;
  
$lastName  $qRow->last;
}


# ***** SECTION IV - INSERT POSTED RESERVATION INTO DB

# If user is logged in, check to see if they are posting a new reservation.

if( $session ) { 
  if( 
"reserve" == $_POST['post2'] ) {
    
$tStartHour $_POST['startHour'];
    
$mStartMin $_POST['startMin'];
    
$tEndHour $_POST['endHour'];
    
$mEndMin $_POST['endMin'];
    
$mDate $_POST['date'];
    
$mNote $_POST['note'];

    
$mStartHour militaryHour$tStartHour );
    
$mEndHour militaryHour$tEndHour );

    
$roomId 1# add code for multiple rooms later

    
$q "INSERT INTO ${YSP}reservation ";
    
$q.= "(reservationId, roomId, userId, date, startTime, endTime, note, status) ";
    
$q.= "VALUES (NULL, $roomId, $userId, '$mDate', '$mStartHour:$mStartMin', '$mEndHour:$mEndMin', '$mNote', 'a')";

    
MYSQL_QUERY$q ) or die( "Invalid query: $q" );
  }
}


# ***** SECTION V - DELETE RESERVATION FROM DB

# If user is logged in, check to see if they are deleting a reservation.
# Instead of actual deletion, leave an audit trail by changing the
# reservation status from 'a' to 'd'.

if( $session ) { 
  if( 
"Delete" == $_POST['delete'] ) {
    
$reservationId $_POST['reservationId'];

    
$q "UPDATE ${YSP}reservation ";
    
$q.= "SET status = 'd' ";
    
$q.= "WHERE reservationId=$reservationId";

    
MYSQL_QUERY$q ) or die( "Invalid query: $q" );
  }
}


# ***** SECTION VI - DISPLAY CONTROL PANEL AT TOP OF SCREEN

# Start the HTML page and display the top control panel. The user can
# login/logout or choose a date and room.

HTMLStart();

?>
<table cellspacing='0' id='controlpanel'>
  <tr>
  <td id='logForm'>
  <?php

  
# If user is already logged in, then let them logout else let them login.

  
if( $session ) {
    print 
"<form method='post' id='formlogout'>";
    print 
"<input type='hidden' name='sessionString' value='$sessionString'>";
    print 
"<input type='submit' name='logout' value='Logout $firstName $lastName'>";
    print 
"</form>\n";
  }
  else {
    print 
"<form method='post' action='login.php' id='formlogin'>";
    print 
"<span class='login'>";
    print 
"USER <input type='text' name='user' size=8>&nbsp;&nbsp;";
    print 
"PASSWORD <input type='password' name='pw' size=8>&nbsp;&nbsp;</span>";
    print 
"<input type='submit' name='login' value='Login'>\n";
    print 
"</form>\n"
  }
  print 
"</td>\n";

  print 
"<td id='gForm'>";
  print 
"<form method='post' name='goForm' id='formgo'>\n";
    
  
# Get the current date parts for today.

  
$today date("d");
  
$todayYear date("Y");
  
$todayMonth date("m");

  
# Check if a date was passed in from the control panel.

  
if( ! ($month $_REQUEST['month']) ) { $month $todayMonth; }
  if( ! (
$year $_REQUEST['year']) ) { $year $todayYear; }

  
# Set arrays for control panel drop down menus.

  
$monthArray = array( 123456789101112 );
  
$yearArray = array($todayYear-1$todayYear$todayYear+1);
  
$rooms = array( 'Elliott 207' );

  
# Display the month drop down menu on the control panel.

  
print '<select name="month">' "\n";
  
array2select$monthArray$month );
  print 
'</select>&nbsp;&nbsp;' "\n";

  
# Display the year drop down menu on the control panel.

  
print '<select name="year">' "\n";
  
array2select$yearArray$year );
  print 
'</select>&nbsp;&nbsp;' "\n";

  
# Display the room drop down menu on the control panel.

  
print '<select name="room">' "\n";
  
array2select$rooms'Elliott 207' );
  print 
'</select>&nbsp;&nbsp;' "\n";

  print 
"<input type='hidden' name='sessionNum' value='$sessionNum'>\n";
  
?>
  <input type="submit" name="update" value="Update">
  </form></td>
  </tr>
</table>
<?php


# ***** SECTION VII - DISPLAY CALENDAR DATA IN MIDDLE OF SCREEN

# This section contains the main code for this application. It is a large
# one month calendar that displays the schedule for a room.

# Figure out dates for last month and next month. Watch year boundaries.

if($month == ) { 
  
$lastMonth 12$lastMonthYear$year 1;

else {
  
$lastMonth $month 1$lastMonthYear $year;
}

if(
$month == 12 ) {
  
$nextMonth 1$nextMonthYear $year 1;

else {
  
$nextMonth $month 1$nextMonthYear $year;
}

# Find the last day number of this month and next month.
# Brute force method. Try dates from the end of the month until one works.

for ($lastday 31$lastday 27$lastday--) {
  
$valid checkdate($month,$lastday,$year);
  if (
$valid) { break; }
}

for (
$lastDayLastMonth 31$lastDayLastMonth 27$lastDayLastMonth--) {
  
$valid checkdate($lastMonth,$lastDayLastMonth,$lastMonthYear);
  if (
$valid) { break; }
}

# Get the UNIX style date in seconds for last, present, and next month.

$base_date mktime(0,0,0,$month,1,$year);
$lastMonthDate mktime(0,0,0,$lastMonth,1,$lastMonthYear);
$nextMonthDate mktime(0,0,0,$nextMonth,1,$nextMonthYear);

# Determine some more key date elements.

$firstDayOfMonth date("w",$base_date); # 0=Sun, 6=Sat
$stopMe $firstDayOfMonth;
$startDay $lastDayLastMonth $firstDayOfMonth 1;

$monthName date"F"$base_date );
$lastMonthName date"F"$lastMonthDate );
$nextMonthName date"F"$nextMonthDate );

# Start the main calendar table and display a title bar with last month 
# and next month hyperlink buttons.

print '<table cellspacing="0" id="calendar">';
  print 
'<tr id="title">';
  print 
"<th id='lastmonth'>";
  print 
"<a href='main.php?month=$lastMonth&year=$lastMonthYear&sessionString=$sessionString'>&laquo;</a></th>";
  print 
"<th colspan='5' id='thismonth'>";
  print 
"Elliott 207 $monthName $year Schedule</th>";
  print 
"<th id='nextmonth'>";
  print 
"<a href='main.php?month=$nextMonth&year=$nextMonthYear&sessionString=$sessionString'>&raquo;</a></th>";
  print 
'</tr>';

  
# Display a row with the days of the week listed as column headings.
  
?> 
  <tr id="days">
  <th class="sun">Sun</th>
  <th class="mon">Mon</th>
  <th class="tue">Tue</th>
  <th class="wed">Wed</th>
  <th class="thu">Thu</th> 
  <th class="fri">Fri</th>
  <th class="sat">Sat</th>
  </tr>

  <?php
  
print "<tr id='firstweek'>";
  
$wd = array( "sun""mon""tue""wed""thu""fri""sat" );

  
# Start displaying the days from last month. List any reservations in each cell.

  
for( $z 0$z 7$z++, $startDay++ ) {
    if( 
$z $firstDayOfMonth ) {
      print 
"<td class='$lastMonthName $wd[$z]' id='$lastMonthName$startDay'><div class='date'>$startDay</div>";

      
$current "$lastMonthYear-$lastMonth-$startDay";

      
$q "SELECT r.reservationId, r.startTime, r.endTime, r.note, r.status, u.userId, u.initials ";
      
$q.= "FROM ${YSP}reservation r, ${YSP}user u ";
      
$q.= "WHERE u.userId = r.userId AND date = '$current' AND r.status = 'a' ";
      
$q.= "ORDER BY r.startTime";

      
$qResult MYSQL_QUERY$q ) or die( "could not select: $q" );

      
calData$q );
    }
    else { break; }
  }

  
# Finish off first week row with days from the current month.

  
$day $z;
  for (
$z 1$z <= $stopMe $z++,$day++) {
    
$day=$day%7;
    if( 
$z==$today && $month==$todayMonth && $year == $todayYear ) {
      print 
"<td class='$monthName $wd[$day]' id='$monthName$z'><div class='date'><div class='today'>$z</div></div>";
    }
    else {
      print 
"<td class='$monthName $wd[$day]' id='$monthName$z'><div class='date'><div class='thismonth'>$z</div></div>";
    }

    
$current "$year-$month-$z";

    
$q "SELECT r.reservationId, r.startTime, r.endTime, r.note, r.status, u.userId, u.initials ";
    
$q.= "FROM ${YSP}reservation r, ${YSP}user u ";
    
$q.= "WHERE u.userId = r.userId AND date = '$current' AND r.status = 'a' ";
    
$q.= "ORDER BY r.startTime";

    
# If user is logged in then let them add and delete reservations.
    
if( $session ) {
      
calForm($current);
    }

    
calData$q );

    print 
"</td>";
  }

  
# Print 2nd week through last week days of current month with reservations.

  
$hold $z-1;
  for( ; 
$z <= $lastday$z++, $day++ ) {
    
$day $day 7;
    if( 
$day==) { print "</tr>\n<tr>"; }
    if( 
$z==$today && $month==$todayMonth && $year == $todayYear ) {
      print 
"<td class='$monthName $wd[$day]' id='$monthName$z'><div class='date'><div class='today'>$z</div></div>";
    }
    else {
      print 
"<td class='$monthName $wd[$day]' id='$monthName$z'><div class='date'><div class='thismonth'>$z</div></div>";
    }

    
$current "$year-$month-$z";

    
$q "SELECT r.reservationId, r.startTime, r.endTime, r.note, r.status, u.userId, u.initials ";
    
$q.= "FROM ${YSP}reservation r, ${YSP}user u ";
    
$q.= "WHERE u.userId = r.userId AND date = '$current' AND r.status = 'a' ";
    
$q.= "ORDER BY r.startTime";

    
# If user is logged in then let them add and delete reservations.
    
if( $session ) {
      
calForm($current);
    }

    
calData$q );

    print 
"</td>";
  }

  
# Finish out the week with a few days from next month.

  
if( $day <= ) {
    for( 
$z=1$z <= 7$day<7$z++, $day++ ) {
      
$day=$day%7;
      print 
"<td class='$nextMonthName $wd[$day]' id='$nextMonthName$z'><div class='date'>$z</div>";

      
$current "$nextMonthYear-$nextMonth-$z";

      
$q "SELECT r.reservationId, r.startTime, r.endTime, r.note, r.status, u.userId, u.initials ";
      
$q.= "FROM ${YSP}reservation r, ${YSP}user u ";
      
$q.= "WHERE u.userId = r.userId AND date = '$current' AND r.status = 'a' ";
      
$q.= "ORDER BY r.startTime";

      
$qResult MYSQL_QUERY$q ) or die( "could not select: $q" );

      
calData($q);
      print 
"</td>";
    }
    print 
"</tr>\n";
  }

print 
"</table>";

# ***** SECTION IX - DISPLAY FOOTER AT BOTTOM OF SCREEN

PageFooter();
HTMLEnd();
?>