#!/usr/bin/perl
#  Copyright 2001-2023 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 = ('Enrollment Summary' => 'Enrollment Summary',
	   'Main' => 'Main',
	   'Room' => 'Room',
	   'Teacher' => 'Teacher',
	   'Grade' => 'Grade',
	   'Male' => 'Male',
	   'Female' => 'Female',
	   'Young' => 'Young',
	   'HRm' => 'HRm',
	   'Total' => 'Total',
	   'Gr' => 'Gr',
	   'Totals' => 'Totals',
	   'Error' => 'Error',
	   'Continue' => 'Continue',
	   

	   );

my $self = 'rptenrolhroom_past.pl';

use DBI;
use CGI;

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


my ($sec, $min, $hour, $mday, $mon, $year, $wday, 
 $yday, $iddst) = localtime(time);
$year = $year + 1900;
$mon++;
$wday++;
my $currdate = "$dow[$wday], $month[$mon] $mday, $year";

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



# Load Remote database
my $dbhr;
if ( $arr{db} ) { # from start page
    my $db = $arr{db};
    my $dsn = "DBI:mysql:database=$db;host=$remotehost";
    $dbhr = DBI->connect($dsn,$remoteuser,$remotepassword);
}


my $title = qq{$schoolname Year End $lex{'Enrollment Summary'}};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">$chartype\n</head>};
print qq{<body>\n};	   

print qq{[ <a href="$homepage">$lex{Main}</a> | \n};
print qq{<a href="/ssp.html">SSP</a> ]\n};

print qq{<h1>$title</h1>\n};

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




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

    # Get remote databases
    my $remotedbase = 'information_schema';
    my $dsnr = "DBI:mysql:database=$remotedbase;host=$remotehost";
    my $dbhr = DBI->connect($dsnr,$remoteuser,$remotepassword);


    my $sth = $dbhr->prepare("select distinct table_schema from TABLES order by table_schema");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my %remotedb;

    while ( my $db = $sth->fetchrow ) {
	if ( $db eq 'mysql' or $db eq 'information_schema' ) { next; }

#	print qq{DB:$db<br>\n};
	if ( $db =~ m/$dbase/ ) {
#	    print qq{Match! $dbase - $db<br>\n};
	    $remotedb{$db} = 1;
	}

    }

    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};

    print qq{<table cellpadding="3" cellspacing="0" border="0" };
    print qq{style="padding:0.5em;border:1px solid gray;">\n};

    print qq{<tr><td class="bla">$lex{Select} $lex{'School Year'}</td><td></td></tr>\n};
    foreach my $db ( sort keys %remotedb ) {

	my $temp = $db;
	$temp =~ s/$dbase//; # strip database name;
	my $year = $temp - 1; # previous year;
	$year = qq{$year-$temp}; # now in 2018-2019 format
	
	print qq{<tr><td class="la"><input type="radio" name="db" value="$db"> $year ($db)</td></tr>\n};
    }

    print qq{<tr><td colspan="2"><hr></td></tr>\n};

    print qq{<tr><td class="la"><input type="submit" value="$lex{Continue}"></td></tr>\n};
    print qq{</table></form>\n};

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

    exit;

}


#-------------
sub showReport {
#-------------

    # foreach my $key ( sort keys %arr ) { print "K:$key VAL:$arr{$key}<br>\n"; }

    my $temp = $arr{db};
    $temp =~ s/$dbase//; # strip database name;
    my $year = $temp - 1; # previous year;
    $year = qq{$year-$temp}; # now in 2018-2019 format

    print qq{<h3>School Year $year</h3>\n};

    
    # Get the Grades
    my %grades;
    my $sth = $dbhr->prepare("select distinct grade from student 
       where grade is not NULL and grade != ''");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $grade = $sth->fetchrow ) {
	$grades{$grade} = 1;
    }
    my @grades = ( sort { $a <=> $b } keys %grades );
    #foreach my $gr ( @grades ) { print "G:$gr<br>\n"; }


    $sth = $dbhr->prepare("select homeroom, grade, sex, youngest from student where grade = ?
		     		 order by homeroom, lastname,firstname");


    print qq{<table border="1" cellpadding="3" cellspacing="0">\n};
    print qq{<tr><th>$lex{Room} - $lex{Teacher}</th>\n<th>};

    print qq{$lex{Grade}</th><th>$lex{Male}</th><th>$lex{Female}</th>\n};
    print qq{<th>$lex{Young}</th><th>$lex{HRm} $lex{Total}</th><th>$lex{Gr} $lex{Total}</th></tr>\n};

    my $youngest = 0;
    my $youngtot = 0;

    my $boytotal = 0;
    my $girltotal = 0;
    my $boycount = 0;
    my $girlcount = 0;
    my $boygrade = 0;
    my $girlgrade = 0;

    my $curroom = -1; $currgrade = -1;
    my $first = 1;

    foreach my $grade ( @grades ) {

	$sth->execute( $grade );
	if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

	while ( my ( $hroom, $gr, $sex, $young ) = $sth->fetchrow ) {
   
	    $oldroom = $curroom;
	    $oldgrade = $currgrade;
	    $curroom = $hroom;
	    $currgrade = $gr;

	    if (($oldroom ne $curroom and not $first ) or
		( $oldroom eq $curroom and $oldgrade ne $currgrade and not $first )) { 
		# we have a new room (or same room but different grade)
		$hrtotal = $boycount + $girlcount;

		my ($sal, $firstname, $lastname);
		if ( $oldroom ){  # If oldroom present, find it's teacher.
		    my $sth1 = $dbhr->prepare("select sal, firstname, lastname 
                      from staff as s, staff_multi as sm 
                      where s.userid = sm.userid and sm.field_name = ? and sm.field_value = ?");
		    $sth1->execute( 'homeroom', $oldroom );
		    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
		    ($sal, $firstname, $lastname) = $sth1->fetchrow;
		}

		# Print out teacher name, totals for this room and then reset the variables.
		print qq{<tr><td class="la">$oldroom - $sal $firstname $lastname</td>};
		print qq{<td>$oldgrade</td><td>$boycount</td>\n};
		print qq{<td>$girlcount</td><td><i>$youngest</i></td>};
		print qq{<td>$hrtotal</td><td></td></tr>\n};

		$girlcount = 0;
		$boycount = 0;
		$youngest = 0;
	    }
    
	    if ( $oldgrade ne $currgrade and not $first ) { # we have a new grade also
		$grtotal = $boygrade + $girlgrade;
		print qq{<tr class="gray"><td></td><td>$oldgrade</td>\n};
		print qq{<td><b>$boygrade</b></td><td><b>$girlgrade</b></td><td></td><td></td>\n};
		print qq{<td><b>$grtotal</b></td></tr>\n};

		$girlgrade = 0;
		$boygrade = 0;
	    }

	    $first = 0;

	    if ( "\U$sex" eq "F") {
		$girlcount++;
		$girltotal++;
		$girlgrade++;
	    } else {
		$boycount++;
		$boytotal++;
		$boygrade++;
	    }

	    if ( $young ) { # if has any value.
		$youngest++;
		$youngtot++;
	    }

	} # End of Main Loop
    }

    my $total = $boycount + $girlcount;

    if ( $curroom ) {

	my $sth1 = $dbhr->prepare("select sal, firstname, lastname from staff as s, staff_multi as sm 
		     where s.userid = sm.userid and sm.field_name = ? and sm.field_value = ?");
	$sth1->execute('homeroom', $curroom );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my ($sal, $firstname, $lastname) = $sth1->fetchrow;

	print qq{<tr><td>$curroom - $sal $firstname $lastname</td>\n};
	print qq{<td>$currgrade</td><td>$boycount</td>\n};
	print qq{<td>$girlcount</td><td><i>$youngest</i></td><td>$total</td><td></td></tr>\n};
    }

    my $grtotal = $boygrade + $girlgrade;
    print qq{<tr class="gray"><td></td><td>$currgrade</td><td><b>$boygrade</b></td>\n};
    print qq{<td><b>$girlgrade</b></td><td></td><td></td><td><b>$grtotal</b></td></tr>\n};

    my $grandtotal = $boytotal + $girltotal;
    print qq{<tr class="blue"><td colspan=2 class="bcn">$lex{Totals}</td>};
    print qq{<td class="bcn">$boytotal</td><td class="bcn">$girltotal</td>\n};
    print qq{<td class="bcn">$youngtot</td><td></td><td class="bcn">$grandtotal</td></tr>\n};
    print qq{</table></body></html>\n};

    exit;
}


