#!/usr/bin/perl
# Web Module for PC Reservation
# Copyright(c)2002-2009, Envisionware, Inc. - All Rights Reserved
# No part of this script may be modified or distributed without the express permission of the copyright holder

# Replace current-directory in include-directory path.
$script_path = $ENV{'SCRIPT_FILENAME'} || $ENV{'PATH_TRANSLATED'} || $0;
$script_path =~ s|[^/\\]+$||;
@INC = grep { $_ ne '.' } @INC;
push( @INC, $script_path );

require "ewDateUtils.pl";
require "ewNetUtils.pl";
require "pcrWebCommon.pl";
require "ewCgiUtils.pl";

# See what the request type is
$request = $ENV{"REQUEST_METHOD"};
$url = $ENV{"SCRIPT_NAME"};
if ($ENV{"QUERY_STRING"} eq "debug")
    { $debug = 1; }
else
    { $query = $ENV{"QUERY_STRING"}; }

&PrintHtmlHeader();
&Initialize();
&PrintHeader("Yakima Valley Libraries", $image_path, $cgi_dir, $font, $home_page);
$timestamp = &Format_Date(time, '<year><0m><0d><0h><0n><0s>');

#### Process the request ####
if ($request eq "GET")
{
    unless ($query)
    {
        print "<font face='$font' size=5>\n";
        print "<center>Make a PC Reservation</center><br></font>\n";

        print "<font face='$font' size=3><center>Select the $branch_label where you would like to use a PC, then press <b>Reserve a PC</b>.<br>\n";
print "<br />To use the WestlawNext dedicated terminal, please select the Yakima Central Library.";
        print "<p>$instructions\n" if (length($instructions) > 0);
        print "</center></font><br>\n";

        if ($debug == 1)
            { print "<form action='$url?debug' method='POST'>\n"; }
        else
            { print "<form action='$url' method='POST'>\n"; }
        
        &PrintBranchSelectionList($branch_label, $locations_file);

        print "<p><center><hr width=50%></center><p>\n";
        print "<center><table width=25%>\n";
        print "<tr align=center><td><input type=submit value='Reserve a PC'></td></tr>\n";
        print "</table></center>\n";
        print "<input type=hidden name='action' value=1>\n";
        print "</form>\n";
    }
    else
    { &ShowEnvironment if ($query eq "showenv"); }
}
elsif ($request eq "POST")
{
        print "POST Request<br>\n" if ($debug == 1);

        %values = &GetPostData($ENV{"CONTENT_LENGTH"});
        $branch = $values{'branch'};
        chomp($branch);
        ($branch_name, $branch_ip, $branch_port) = split(/:/, $branch);
        print "Selected $branch_label = $branch_name ($branch_ip $branch_port)<br>\n" if ($debug == 1);

        if ($values{'action'} == 1)     # Get the details for the request
        {
            if (&ConnectToManagementConsole($branch_ip, $branch_port) == 1)
            {
                if (&Check_Socket(COMM_SOCKET, $msg_timeout))
                {
                    @message_fields = split(/\|/, &Receive());
                    if ($message_fields[0] == $osiREQ_ID)
                    {
                        # Send osiMSG_WEBID with req. for Area List
                        &Send("$osiMSG_WEBID|$timestamp|$ENV{'SERVER_NAME'}|$osiREQ_POOLLIST\0");

                        # Wait for Area List
                        if (&Check_Socket(COMM_SOCKET, $msg_timeout))
                        {
                            @message_fields = split(/\|/, &Receive());
                            if ($message_fields[0] == $osiMSG_POOLLIST)
                            {
                                shift(@message_fields);                 # drop the message ID field
                                shift(@message_fields);                 # drop the timestamp field
                                $num_areas = shift(@message_fields);    # drop the area count field, but save in $num_areas
                                if ($num_areas > 0)
                                {
                                    @pc_areas = map { &strip_invalid_chars($_); } @message_fields;

                                    ($error, $user_id_prompt, $pin_prompt, $num_days, $num_digits, $user_id_prefix, $pin_required, $use_description, $adjust_for_closed, @closed_days) = &RequestWebConfig($language);
                                    if ($error == 0)
                                    {
                                        &PrintStandardInputPageHeader("Please enter the following information to request a reservation:", $url);
    
                                        # Hidden fields
                                        print "<input type=hidden name='branch' value='$branch'>\n";
                                        print "<input type=hidden name='action' value=2>\n";
                                        print "<input type=hidden name='pin_required' value='$pin_required'>\n";
                                        print "<input type=hidden name='num_digits' value='$num_digits'>\n";
                                        print "<input type=hidden name='prefix' value='$user_id_prefix'>\n";
                                        print "<input type=hidden name='user_id_prompt' value='$user_id_prompt'>\n";
                                        print "<input type=hidden name='pin_prompt' value='$pin_prompt'>\n";
                                        print "<input type=hidden name='use_description' value='$use_description'>\n";
    
                                        &PrintUserIdAndPinRequestBlock($user_id_prompt, $pin_prompt, $pin_required);
                                    
                                        # Area List
                                           print "<tr><td>Select Area:</td>\n";
                                        print "<td><select name='area'>\n";
                                        for ($i = 0; $i < $num_areas; $i++)
                                               { print "<option>$pc_areas[$i]\n"; }
                                        print "</select></td></tr>\n";
                                            
                                        # Date
                                        $now = time;
                                        print "<tr><td>Select Date:</td>\n";
                                        print "<td><select name='day'>\n";
                                
                                        if ($adjust_for_closed)
                                            { $num_days = $closed_days[0] - 1; }
                                    
                                        for ($i = 0; $i <= $num_days; $i++)
                                        {
                                            if ($closed_days[$i + 1] == '1')
                                            {
                                                if ($i == 0)
                                                    { print "<option value=$i selected>CLOSED\n"; }
                                                else
                                                    { print "<option value=$i>Closed\n"; }
                                            }
                                            elsif ($i == 0)
                                                { print "<option value=$i selected>Today\n"; }
                                            elsif ($i == 1)
                                                { print "<option value=$i>Tomorrow\n"; }
                                            else
                                            {
                                                $future_time = $now + ($i * $seconds_per_day);
                                                ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($future_time);
                                                print "<option value=$i>$weekday[$wday], $month[$mon] $mday\n";
                                            }
                                        }
                                        print "</select></td></tr>\n";
    
                                        # Time - Hour
                                        ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($now);
                                        if ( ($min >= 0) and ($min < 15) )
                                            { $selection = 2; }       # 30
                                        elsif ( ($min >= 15) and ($min < 30) )
                                            { $selection = 3; }        # 45
                                        elsif ( ($min >= 30) and ($min < 45) )
                                        { 
                                            $selection = 0;         # 00
                                            $hour = $hour + 1;
                                            $hour = 0 if $hour >= 24;
                                        }
                                        else
                                        {
                                            $selection = 1;         #15
                                            $hour = $hour + 1;
                                            $hour = 0 if $hour >= 24;
                                        }
    
                                        if ($hour == 0)
                                        {
                                            $hour = 12;
                                            $am = 1;
                                        }
                                        elsif ($hour == 12)
                                            { $am = 0; }
                                        elsif ($hour < 12)
                                            { $am = 1; }
                                        else
                                        {
                                            $hour = $hour - 12;
                                            $am = 0;
                                        }
                                        print "<tr><td>Time:</td>\n";
                                        print "<td><select name='hour'>\n";
                                        for ($i = 1; $i <= 12; $i++)
                                        {
                                            if ($i == $hour)
                                                { printf("<option value=%d selected>%02d\n", $i, $i); }
                                            else
                                                { printf("<option value=%d>%02d\n", $i, $i); }
                                        }
                                        print "</select>\n";
                                        print " : \n";
    
                                        # Time - Minute
                                        print "<select name='minute'>\n";
                                        for ($i = 0; $i <= 3; $i++)
                                        {
                                            if ($selection == $i)
                                                { printf("<option value=%d selected>%02d\n", $i * 15, $i * 15); }
                                            else
                                                { printf("<option value=%d>%02d\n", $i * 15, $i * 15); }
                                        }
                                        print "</select>\n";
    
                                        # Time - AM/PM
                                        if ($am == 0)
                                        {
                                            print "<input type=radio name='ampm' value='am'> AM \n";
                                            print "<input type=radio name='ampm' value='pm' checked> PM </td></tr>\n";
                                        }
                                        else
                                        {
                                            print "<input type=radio name='ampm' value='am' checked> AM \n";
                                            print "<input type=radio name='ampm' value='pm'> PM </td></tr>\n";
                                        }
                                        print "</table></center>\n";
    
                                        # Submit / Cancel
                                        print "<p><center><hr width=50%><p></center>\n";
                                        print "<center><table width=50%>\n";
                                        print "<tr align=center><td><input type=submit value='Submit'></td></tr>\n";
                                        print "</table></center>\n";
                                        print "</form>\n";
    
                                        print "<p><center><a href='$url'>Go Back</a></center>\n";
                                    } # if (select ...)
                                    else
                                        { &ReportTimeout($url); }
                                }
                                else
                                    { &ReportError("There are no areas which permit web reservations at this branch.", $url); }
                            }
                            else
                                { &ReportUnexpectedResponse($url); }
                        } 
                        else
                           { &ReportTimeout($url); }
                    } # if (MessageFields[0] == $osiREQ_ID)
                    else
                        { &ReportUnexpectedResponse($url); }
                }
                else
                    { &ReportTimeout($url); }
            }
            else
                { &ReportTimeout($url); }
            close(COMM_SOCKET);
        }
        elsif ($values{'action'} == 2)     # Request the reservation
        {
            # Validate the User Id
            $num_digits = $values{'num_digits'};
            $user_id_prefix = $values{'prefix'};
            $user_id_prompt = $values{'user_id_prompt'};
            $pin_prompt = $values{'pin_prompt'};
            $pin_required = $values{'pin_required'};
            $use_description = $values{'use_description'};

            if (&IsUserIdWellFormed($values{'user_id'}) == 0)
                { &ReportMalformedUserId($values{'user_id'}, $user_id_prompt, $url); }
            elsif ( (&ConnectToManagementConsole($branch_ip, $branch_port) == 1)
            &&      (&Check_Socket(COMM_SOCKET, $msg_timeout)) )
            {
                @message_fields = split(/\|/, &Receive());
                if ($message_fields[0] == $osiREQ_ID)
                {
                    # Send osiMSG_WEBID with req. for Area List
                    $req_hour = $values{'hour'};
                    print "Hour: $req_hour<br>\n" if $debug == 1;

                    $ampm = $values{'ampm'};
                    print "AMPM: $ampm<br>\n" if $debug == 1;

                    if ($req_hour == 12)
                        { $req_hour = 0 if $ampm =~ /am/; }
                    else
                        { $req_hour = $req_hour + 12 if $ampm =~ /pm/; }

                    if (length($values{'pin'}) > 0)
                        { $pin = $values{'pin'}; }
                    else
                        { $pin = " "; }

                    if (length($values{'user_id'}) > 0)
                        { $user_id = $values{'user_id'}; }
                    else
                        { $user_id = " "; }
                        
                    &Send("$osiMSG_WEBID|$timestamp|$ENV{'SERVER_NAME'}|$osiREQ_FUTUREPC|$timestamp|$values{'user_id'}|$values{'area'}|$req_hour:$values{'minute'}|$values{'day'}|0|$pin|$language| |0\0");
                    if (&Check_Socket(COMM_SOCKET, $msg_timeout))
                    {
                        @message_fields = split(/\|/, &Receive());
                        if ($message_fields[0] == $osiMSG_NEXTAVAILPC)
                        {
                            $resv_id = $message_fields[5];
                            $resv_id =~ s/^A//;

                            print "Reservation Made (ID=$resv_id):<br>\n" if $debug == 1;

                            # Send request for Reservation Details
                            &Send("$osiREQ_RESVDETAIL|$timestamp|1|$resv_id\0");
                            if (&Check_Socket(COMM_SOCKET, $msg_timeout))
                            {
                                @message_fields = split(/\|/, &Receive());
                                if ($message_fields[0] == $osiMSG_RESVDETAIL)
                                {
                                    $subset = $message_fields[3];
                                    if ($subset == 1)
                                    {
                                        ($resv_type, $user_id, $pin, $pc_id, $time, $date, $length, $wait_time, $language) = &ParseReservationInformationMessage(@message_fields);

                                        if ($use_description > 0)
                                        {
                                            # Send request for Extended Reservation Details
                                            &Send("$osiREQ_RESVDETAIL|$timestamp|2|$resv_id\0");
                                            if (&Check_Socket(COMM_SOCKET, $msg_timeout))
                                            {
                                                @message_fields = split(/\|/, &Receive());
                                                $num_fields = @message_fields;

                                                if ($message_fields[0] == $osiMSG_RESVDETAIL)
                                                {
                                                    $subset = $message_fields[3];
                                                    if ($subset == 2)
                                                    {
                                                        for ($i = 4; $i < $num_fields; $i++)
                                                        {
                                                            if ($message_fields[$i] =~ /^A/)
                                                                { $pc_desc = &RemoveFieldIdFromMessageField($message_fields[$i], 'A', "PC Description"); }
                                                            elsif ($message_fields[$i] =~ /^B/)
                                                                { $pc_location = &RemoveFieldIdFromMessageField($message_fields[$i], 'B', "PC Location"); }
                                                        } # for
                                                    } # if subset == 2
                                                } # if $message_fields[0] == $osiMSG_RESVDETAIL
                                            } # if (Check_Socket ...)
                                        } # if $use_description

                                         print "<font face='$font' size=3>\n";
                                        print "<center>The following Reservation has been made:</center><br></font>\n";

                                        print "<font face='$font' size=2>\n";

                                        if ($debug == 1)
                                            { print "<form action='$url?debug' method='POST'>\n"; }
                                        else
                                            { print "<form action='$url' method='POST'>\n"; }
                                        
                                        print "<center><table width=50%>\n";

                                        # Hidden fields
                                        print "<input type=hidden name='branch' value='$branch'>\n";
                                        print "<input type=hidden name='action' value=5>\n";
                                        print "<input type=hidden name='resv_id' value='$resv_id'>\n";
                                        print "<input type=hidden name='user_id' value='$user_id'>\n";
                                        print "<input type=hidden name='pc_id' value='$pc_id'>\n";

                                        print "<tr><td>$branch_label:</td><td>$branch_name</td></tr>\n";
                                        print "<tr><td>$user_id_prompt:</td><td>$user_id</td></tr>\n";

                                        $pin =~ s/./*/g if ($pin_required > 0);
                                        print "<tr><td>$pin_prompt:</td><td>$pin</td></tr>\n";

                                        if ( ($use_description == 1) and ($pc_desc) and (length($pc_desc) > 0) )
                                            { print "<tr><td>PC:</td><td>$pc_desc</td></tr>\n"; }
                                        else
                                            { print "<tr><td>PC:</td><td>$pc_id</td></tr>\n"; }
                                        print "<tr><td>Date:</td><td>$date</td></tr>\n";
                                        print "<tr><td>Time:</td><td>$time</td></tr>\n";
                                        print "<tr><td>Length:</td><td>$length minutes</td></tr>\n";
                                        print "</table></center>\n";

                                        print "<p><center><hr width=50%></center><p>\n";
                                        print "<center><table width=25% border=1 bordercolordark=#003300 bordercolor=#007700 bordercolorlight=#00FF00>\n";
                                        print "<tr align=center><td><input type=submit value='Accept'></td></tr>\n";
                                        print "</table></center></form>\n";

                                        print "<p>\n";
                                        if ($debug == 1)
                                            { print "<form action='$url?debug' method='POST'>\n"; }
                                        else
                                            { print "<form action='$url' method='POST'>\n"; }

                                        # Hidden fields
                                        print "<input type=hidden name='branch' value='$branch'>\n";
                                        print "<input type=hidden name='action' value=3>\n";
                                        print "<input type=hidden name='resv_id' value='$resv_id'>\n";

                                        print "<center><table width=25% border=1 bordercolordark=#330000 bordercolor=#770000 bordercolorlight=#FF0000>\n";
                                        print "<tr align=center><td><input type=submit value='Cancel this Reservation'></td></tr>\n";
                                        print "</table></center></form>\n";
                                    } # if $subset == 1
                                    else
                                        { &ReportUnexpectedResponse($url); }
                                } # if $message_fields[0] == $osiMSG_RESVDETAIL
                                else
                                    { &ReportUnexpectedResponse($url); }
                            } # if (Check_Socket ...)
                            else
                                { &ReportTimeout($url); } 
                        } # if $msg_fields[0] == $osiMSG_NEXTAVAILPC
                        elsif ($message_fields[0] == $osiMSG_BADID)
                            { &ReportError("The $user_id_prompt you entered is not valid", $url); }
                        elsif ($message_fields[0] == $osiMSG_NORESV)
                            { &ReportError("The reservation could not be made", $url); }
                        elsif ($message_fields[0] == $osiMSG_INVALIDUSER)
                        {
                            print "<center>The reservation could not be made.";
                            
                            if ($message_fields[2] == $osi_BADUSERID)
                                { print "  (The $user_id_prompt is invalid.)"; }
                            elsif ($message_fields[2] == $osi_BADPATRONSTATUS)
                                { print "  (The user status is invalid.)"; }
                            elsif ($message_fields[2] == $osi_TOOMANYRESERVATIONS)
                                { print "  The user has made too many reservations for today.  ($message_fields[5])"; }
                            elsif ($message_fields[2] == $osi_EXISTINGRESERVATION)
                                { print "  ($message_fields[5])"; }
                            elsif ($message_fields[2] == $osi_ACTIVESESSION)
                                { print "  ($message_fields[5])"; }
                            elsif ($message_fields[2] == $osi_PCUSEDENIED)
                                { print "  ($message_fields[5])"; }
                            elsif ($message_fields[2] == $osi_AREARESTRICTED)
                                { print "  ($message_fields[5])"; }
                            elsif ($message_fields[2] == $osi_SELFSERVICEDENIED)
                                { print "  ($message_fields[5])"; }
                            
                            print "</center><br>\n";
                        }
                        else
                            { &ReportUnexpectedResponse($url); }
                    } # if (Check_Socket ...)
                    else
                        { &ReportTimeout($url); }
                } # if ($MessageFields[0] == $osiREQ_ID)
                else
                    { &ReportUnexpectedResponse($url); }
            } # if (Check_Socket ...)
            else
                { &ReportTimeout($url); }
            close(COMM_SOCKET);
        } # if $action == 2
        elsif ($values{'action'} == 3)     # Verify cancelation
        {
            $resv_id = $values{'resv_id'};
            print "Reservation Id: $resv_id<br>\n" if $debug == 1;

            print "<p>\n";
            if ($debug == 1)
                { print "<form action='$url?debug' method='POST'>\n"; }
            else
                { print "<form action='$url' method='POST'>\n"; }

            # Hidden fields
            print "<input type=hidden name='branch' value='$branch'>\n";
            print "<input type=hidden name='action' value=4>\n";
            print "<input type=hidden name='resv_id' value='$resv_id'>\n";

            print "<font face='$font' size=3>\n";
            print "<center>Are you sure you want to cancel the reservation?</center><br></font>\n";
            print "<font face='$font' size=2>\n";
            print "<center><table width=33% border=1 bordercolordark=#330000 bordercolor=#770000 bordercolorlight=#FF0000>\n";
            print "<tr align=center><td><input type=submit value='Yes, Cancel the Reservation'></td></tr>\n";
            print "</table></center></form>\n";

            print "<p>\n";
            if ($debug == 1)
                { print "<form action='$url?debug' method='GET'>\n"; }
            else
                { print "<form action='$url' method='GET'>\n"; }

            print "<center><table width=33% border=1 bordercolordark=#003300 bordercolor=#007700 bordercolorlight=#00FF00>\n";
            print "<tr align=center><td><input type=submit value='No, I want to keep the Reservation'></td></tr>\n";
            print "</table></center></form>\n";
        } # if $action == 3
        elsif ($values{'action'} == 4)     # Cancel the reservation
        {
            $resv_id = $values{'resv_id'};
            print "Reservation Id: $resv_id<br>\n" if $debug == 1;

             &CancelReservation($branch_ip, $branch_port, $resv_id, $url);
        } # if $action == 4
        elsif ($values{'action'} == 5)     # Accept the reservation
        {
            $resv_id = $values{'resv_id'};
            $user_id = $values{'user_id'};
            $pc_id = $values{'pc_id'};
            print "Reservation Id: $resv_id<br>\n" if $debug == 1;
            print "User Id: $user_id<br>\n" if $debug == 1;
            print "PC Id: $pc_id<br>\n" if $debug == 1;

             &AcceptReservation($branch_ip, $branch_port, $resv_id, $user_id, $pc_id, $url);
        } # if $action == 4
}
else
    { &ReportUnknownRequest($url); }

&PrintFooter();
print "</body></html>\n";
