#!/usr/local/bin/perl -w

use strict;

use URI::Escape;
use XML::Simple;

# send back basic header
print "Content-Type: text/html\n\n";

# figure out CGI options
if( $ENV{'REQUEST_METHOD'} eq "POST" ) {
    local $/ = undef;
    $ENV{'QUERY_STRING'} = <>;
}
my %cgioptions = map {split /=/, $_, 2} split /&/, $ENV{QUERY_STRING};
my $year = "2006";

# get date in month year format ready for passing to cal
# my $date = `date +%m\ %Y`;
my ($days, $month, $year) = split(" ", `date +'%d\ %m\ %Y'` );
my $calOutput = `cal -m`;

my @lines = split "\n",$calOutput;

# note: for @lines
# 0 is month+year
# 1 is days of week
# 2-5/6 are days of month
# $startDay ends up as the day of the week on which the 1st falls (0..6)

$lines[0]=~s/^[ \t]*//;
my $startDay =7 - scalar(@_ = split(" ",$lines[2]));
my $lastLine = (defined $lines[7])?$lines[7]:$lines[6];
my ($monthDays) = ($lastLine =~ / ([2,3][0,1,9])$/);


my $ThisScript = "events.pl";

#<!--#include file="header.html" -->
IncludeHTMLFile("../header.html");

print <<JSHEADER
<script type="text/javascript">
  page="pcc";
</script>
JSHEADER
;

#<!--#include file="menu.html" -->
IncludeHTMLFile("../menu.html");

print "<div id=\"pagecontent\">\n";
print "<h1 class=\"pagetitle\">Calendar</h1>\n";

# display the form
print "<form action=\"$ThisScript\" method=\"post\">\n<input type=\"hidden\" name=\"NewEvent\" value=\"True\" />\n<table class=\"formtable\"><tr>\n<td colspan=\"4\">Add a New Event to the calendar</td>\n</tr>\n";


print "<tr>\n<td>Day</td>\n<td><select name=\"Day\">";

for (my $i = 1; $i <=31; $i++){
    print "<option value=\"$i\">$i</option>\n";
}
print "</select></td>\n";
print "<td>Month</td>\n<td><select name=\"Month\">";

for (my $i = 1; $i <=12; $i++){
    print "<option ".($i == $cgioptions{'Month'}?"selected=\"\" ":"")."value=\"$i\">$i</option>\n";
}

print "</select>\n</td>\n</tr>\n";



print "<tr><td colspan=\"4\"><input type=\"text\" name=\"Description\" value=\"\" size=\"60\"/></td>\n</tr>\n<tr><td colspan=\"4\"><input type=\"submit\" value=\"submit\" /></td>\n</tr>\n</table></form>";

# process any cgioptions passed to us

if (defined $cgioptions{'NewEvent'}){
    if (defined $cgioptions{'Description'} && $cgioptions{'Description'} ne ""){
        $cgioptions{'Description'} =~ s/\+/ /gom;
        my $xs = XML::Simple->new();
        
        my @events = ();

        if (-e "../$cgioptions{'Month'}-$year.xml"){
            my $xml = $xs->XMLin("../$cgioptions{'Month'}-$year.xml", forcearray => 1);
            
            foreach my $event (@{$xml->{'event'}}){
                $events[$event->{'day'}[0]] = {'summary' => $event->{'summary'}[0], 'details' => $event->{'details'}[0]};
            }
        } else {
            `touch "../$cgioptions{'Month'}-$year.xml"`;
        }
        
        if (!defined $events[$cgioptions{'Day'}]) {
            $events[$cgioptions{'Day'}] = {'summary' => $cgioptions{'Description'},'details' => $cgioptions{'Description'}};
        } else {
            $events[$cgioptions{'Day'}] = {'summary' => $events[$cgioptions{'Day'}]->{'summary'}."<br/>".$cgioptions{'Description'},'details' => $events[$cgioptions{'Day'}]->{'details'}."<br/>".$cgioptions{'Description'}};
        }
        
        open( OUT, ">../$cgioptions{'Month'}-$year.xml") || die "couldn't open : $!";  
        print OUT "<?xml version=\"1.0\" ?>\n<month>\n";

        for (my $i = 0; $i <= $#events; $i++) {
            if (defined $events[$i]->{'summary'}){
                print OUT "<event>\n<day>$i</day><summary>".uri_unescape($events[$i]->{'summary'})."</summary><details>".uri_unescape($events[$i]->{'details'})."</details>\n</event>\n";
            }
        }
        print OUT "</month>\n";
        close OUT;

        `../calendar.pl > ../calendar.html`;

        print "<table class=\"newevent\"><tr><td colspan=\"2\">Added new event:</td></tr><tr><td>$cgioptions{'Day'}/$cgioptions{'Month'}/05: ".uri_unescape($cgioptions{'Description'})."</td></tr>\n</table>";
    } else {
        print "<table class=\"newevent\"><tr><td>You must provide a brief description of the event!</td></tr>\n</table>";
    }
}

# end of pagecontent
print "</div>";

# <!--#include file="breakingNews.html" -->
IncludeHTMLFile("../breakingNews.html");

# <!--#include file="calendar.html" -->
IncludeHTMLFile("../calendar.html");

# <!--#include file="footer.html" -->
IncludeHTMLFile("../footer.html");

;

#############
# Functions #
#############

sub IncludeHTMLFile( $ ){
    my $filename = shift;
    return undef if !(defined $filename && -e $filename);
    local $/ = undef;
    open (IN, $filename ) or return undef;
    print <IN>;
}
