#!/usr/bin/perl
#  Copyright 2001-2024 Leslie Richardson

#  This file is part of Open Admin for Schools.

#  Open Admin for Schools is free software; you can redistribute it 
#  and/or modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2 of 
#  the License, or (at your option) any later version.

my %lex = ('Track Report' => 'Track Report',
	   'Main' => 'Main',
	   'Date format Error' => 'Date format Error',
	   'Aging Date' => 'Aging Date',
	   'Name' => 'Name',
	   'Birthdate' => 'Birthdate',
	   'Sex' => 'Sex',
	   'House' => 'House',
	   'Homeroom' => 'Homeroom',
	   'Month' => 'Month',
	   'Day' => 'Day',
	   'Age' => 'Age',
	   'Error' => 'Error',
	   'Continue' => 'Continue',
	   'Blank=Today' => 'Blank=Today',

	   );


use DBI;
use CGI;

eval require "../etc/admin.conf";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}


# Get Date
my @tim = localtime(time);
my $year = @tim[5] + 1900;
my $month = @tim[4] + 1;
if (length($month) == 1) { $month = '0'.$month; }
my $day = @tim[3];
if (length($day) == 1) { $day = '0'.$day; }
my $currdate = "$year-$month-$day";
my $currdate1 = "@month[$month] $day, $year";

my $q = new CGI;
my %arr = $q->Vars;
print $q->header( -charset, $charset );

my $title = $lex{'Track Report'};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{$chartype\n</head>\n};
print qq{<body>[ <a href="$homepage">$lex{Main}</a> ]\n};


if ( not $arr{page} ) {
    showStartPage();
} else {
    delete $arr{page};
}



my $agingdate;

if ($arr{agingdate}){

    $agingdate = $arr{agingdate};
    if (length($agingdate) == 10) { # ie. is: YYYY-MM-DD format
	(my $yr,$mo,$da) = split /-/,$agingdate;
	if (length($mo) == 1) { $mo = '0'.$mo; }
	if (length($da) == 1) { $da = '0'.$da; }
	if (length($yr) == 2) { $yr = '20'.$yr; }
	$agingdate = "$yr-$mo-$da";
	$splitdate = $mo.$da;
    } else { # Date format error!
	print qq{$lex{'Date format Error'}!<br>\n};
	print qq{</body></html>\n};
	exit;
    }

} else { # Blank value, use today, set above... along with $month,$day.
    $agingdate = $currdate;
    $splitdate = $month.$day;
}


my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);


$sth = $dbh->prepare("select lastname, firstname, initial, grade, homeroom, sex, birthdate, house 
  from student order by birthdate");
$sth->execute;
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
$rows = $sth->rows;

print qq{<h1>$title</h1><h4>$currdate</h4>\n};
print qq{<p><b>$lex{'Aging Date'}: $agingdate  Split Date: $splitdate</b></p>\n};

my $first = 1;
my ($prevmonthday, $currmonthday);

while (my ($lastname, $firstname, $initial, $grade, $homeroom, $sex, $birthdate, $house) = $sth->fetchrow) {

    my ($yr,$mon,$day) = split /-/, $birthdate;
    my $student = "$sex$lastname$firstname:$lastname, $firstname $initial:$birthdate:$sex:$house:$homeroom";

    $prevmonthday = $currmonthday;
    $prevyear = $curryear;
    $currmonthday = $mon.$day;
    $curryear = $yr;
    if ($first) {  # for setup... loop after getting @rec started and dates set.
	$first = 0;
	push @rec, $student;
	next;
    }

    
    #print qq{P:$prevmonthday S:$splitdate  C:$currmonthday  PY:$prevyear CY:$curryear<br>\n};
    if (($prevmonthday <= $splitdate and $currmonthday > $splitdate and $curryear == $prevyear) or 
	( $currmonthday > $splitdate and $curryear > $prevyear) or
	( $prevmonthday <= $splitdate and $curryear > $prevyear) ) { 

	prRec(@rec); # print the table of this age group.
	@rec = ();
	
    } # End of Loop for printing 
    
    push @rec, $student; # whether it is zeroed by func above.
    
} # End of loop counter

prRec(@rec); 
print qq{</body></html>\n};


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

#--------
sub prRec { # print the records in @rec array
#--------

    my @rec = @_;

    ($blank,$name,$bday,$sex,$house,$homeroom) = split /:/, @rec[0];
    ($yr,$mon,$day) = split /-/, $bday;
    my $age = &calcAge($bday,$agingdate);
    ($ageyear,$agemonth) = split /:/,$age;
    $ageyear = $ageyear." Year Olds";

    print qq{<table border="1" cellpadding="3" cellspacing="0">\n};
    print qq{<caption><b>$ageyear</b></caption>\n};
    print qq{<tr><th>$lex{Name}</th><th>$lex{Birthdate}</th>\n};
    print qq{<th>$lex{Sex}</th><th>$lex{House}</th><th>$lex{Homeroom}</th>\n};
    print qq{<th>$lex{Month}</th><th>$lex{Day}</th><th>$lex{Age}</th></tr>\n};

    my @sortedrec = sort @rec;

    foreach my $arrayref (@sortedrec) {
	($blank,$name,$bday,$sex,$house,$homeroom) = split /:/, $arrayref;
	($yr,$mon,$day) = split /-/, $bday;
	my $age = &calcAge($bday,$agingdate);
	my ($ageyear,$agemonth) = split /:/,$age;
	$age = $ageyear."y ".$agemonth."m";
	print qq{<tr><td><b>$name</b></td><td>$bday</td><td>$sex</td>\n};
	print qq{<td>$house</td><td>$homeroom</td>\n};
	print qq{<td align="right">@month[$mon]</td>\n};
	print qq{<td>$day</td><td>$age</td></tr>\n};
    }
    print qq{</table>\n<p>&nbsp;</p>\n};

}

#----------
sub calcAge {
#----------

    # Passed (birthdate, $currdate)
    my $birthDate = shift;
    my $currentDate = shift;
    my ($byear,$bmonth,$bday) = split /-/,$birthDate;
    my ($cyear,$cmonth,$cday) = split /-/,$currentDate;
    my $age = $cyear - $byear;
    my $month = $cmonth - $bmonth;

    if ($cmonth < $bmonth){
	$month = $month + 12;
	if ($cday < $bday){ $month--;}
	$age--;
    }
    elsif ($cmonth == $bmonth and $cday < $bday){
	$age--; 
	$month = 11;
    } elsif ($cmonth > $bmonth and $cday < $bday) {
	$month--;
    }
    return "$age:$month";
}



#----------------
sub showStartPage {
#----------------

    print qq{<link rel="stylesheet" type="text/css" media="all" };
    print qq{href="/js/calendar-blue.css" title="blue">\n};
    print qq{<script type="text/javascript" src="/js/calendar.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/lang/calendar-en.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/calendar-setup.js"></script>\n};

    print qq{<p style="width:60ch;border:1px solid gray;padding:0.5em;">};
    print qq{The <b>Aging Date</b> is the day of the year where the child
    	  has to be a certain age by that date in order to play hockey in a certain age group.
      	  (ie. 8 years old by Sept 30th).</p>\n};

    
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<div style="font-size:120%;">$lex{'Aging Date'} <input type="text" };
    print qq{name="agingdate" style="width:10ch;" id="agingdate">\n};
    print qq{<button type="reset" id="start_trigger">...</button></div>};
    print qq{<div>$lex{'Blank=Today'}, yyyy-mm-dd format</div>\n};
    print qq{<p><input type="submit" value="$lex{Continue}"></p>\n};
    print qq{</form>\n};


    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :    "agingdate", // id of the input field
        ifFormat       :    "%Y-%m-%d", // format of the input field
        button         :    "start_trigger", // trigger for the calendar (button ID)
        singleClick    :    false,        // double-click mode
        step           :    1             // show all years in drop-down boxes 
    })};

    print qq{</script>\n};
    print qq{</body></html>\n};

    exit;


}
