#! /usr/bin/perl 
#  Copyright 2001-2018 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.


use DBI;
use CGI;
use Cwd;
use Number::Format qw(:subs);

my %lex = ('Transfer' => 'Transfer',
	   'Report' => 'Report',
	   'Missing' => 'Missing',
	   'Date' => 'Date',
	   'Student' => 'Student',
	   'Enrollments' => 'Enrollments',
	   'Withdrawals' => 'Withdrawals',
	   'Code' => 'Code',
	   'Count' => 'Count',
	   'Main' => 'Main',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',
	   'Continue' => 'Continue',
	   'Error' => 'Error',
	   'Description' => 'Description',
	   'Edit' => 'Edit',
	   'View' => 'View',
	);

my $self = "rpttranscode.pl";
my $configpath = '../..';


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

# pull in global enrol/withdraw descriptors
eval require "$globdir/global.conf";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@\n";
}


# Get current dir so know what CSS to display and shift to teacher settings.
if ( getcwd() =~ /tcgi/ ) { # we are in tcgi
    $css = $tchcss;
    $homepage = $tchpage;
    $downloaddir = $tchdownloaddir;
    $webdownloaddir = $tchwebdownloaddir;
}

my $maxlines = 28;
my $shortname = "transtat$$";
my $filename = "$shortname.tex";

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


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


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


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

# rounding format
my $fmt = new Number::Format(-decimal_fill => '1', -decimal_digits => '2');


# print page header
print qq{$doctype\n<html><head><title>$lex{Transfer} $lex{Report}</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};

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{$chartype\n</head><body>[ <a href="$homepage">$lex{Main}</a> ]\n};


if ( not $arr{page} ) {
    showStartPage();
    
} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    showTransfers();
    
} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    showType();
}


#-----------
sub showType {
#-----------

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

    my ( $code, $display, $select1, $select2 );
    if ( exists $arr{exitcode} ) {
	$code = $arr{exitcode};
	$display = $g_wdraw{$code};
	$select1 = "type = 'withdraw'";
	if ( not $code ) {
	    $display = qq{<span style="color:red;font-weight:bold;">$lex{Missing} $lex{Code}</span>};
	    $select2 = qq{exittype = '' or exittype is NULL};
	} else {
	    $select2 = qq{exittype = '$arr{exitcode}'};
	}
    } else {
	$code = $arr{entrycode};
	$display = $g_enrol{$code};
	$select1 = "type != 'withdraw'";
	$select2 = "entrytype = '$arr{entrycode}' ";
    }

    
    print qq{<h1>$lex{View} $lex{Enrollments}/$lex{Withdrawals}</h1>\n};
    if ( not $display ) { $display = qq{Missing Code}; }
    print qq{<h3>$display</h3>\n};

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

    my $sth = $dbh->prepare("select * from transfer where
      $select1 and to_days( date ) >= to_days('$arr{startdate}') and 
      to_days( date ) <= to_days('$arr{enddate}') and $select2 order by date");

    $sth->execute();
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; };
    my $count = 1;
    while ( my $ref = $sth->fetchrow_hashref ) {
	print qq{<tr><td>$count. $ref->{firstname} $ref->{lastname}</td><td>$ref->{date}</td>\n};
	print qq{<td><form action="transferEd.pl" method="post" style="display:inline;">\n};
	print qq{<input type="hidden" name="id" value="$ref->{id}">\n};
	print qq{<input type="submit" value="$lex{Edit}"></form>};
	print qq{</td></tr>\n};
	$count++;
    }
    print qq{</table>\n};

    exit;

}


#-----------------
sub showTransfers {
#-----------------

    if ( not $arr{startdate} or not $arr{enddate} ) {
	print qq{<h1>$lex{Missing} $lex{Date}</h1>\n};
	print qq{</body></html>\n};
	exit;
    }

    print qq{<div style="font-size:130%;padding:0.5em;"><b>$lex{'Start Date'}:</b> $arr{startdate} };
    print qq{<b>$lex{'End Date'}:</b> $arr{enddate}</div>\n};

    # Enrols
    print qq{<h1>$lex{Student} $lex{Enrollments}</h1>\n};
    print qq{<table cellspacing="0" cellpadding="3" border="1">\n};
    print qq{<tr><th>$lex{Code}</th><th>$lex{Description}</th><th>$lex{Count}</th><th></th></tr>\n};

    my $sth = $dbh->prepare("select distinct entrytype, count(*) from transfer
      where type != 'withdraw' and to_days( date ) >= to_days('$arr{startdate}') and 
      to_days( date ) <= to_days('$arr{enddate}') group by entrytype order by entrytype");
    $sth->execute();
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; };
    while ( my ( $entrytype, $count ) = $sth->fetchrow ) {
	my $desc;
	if ( not $entrytype ) {
	    $desc = qq{<span style="color:red;font-weight:bold;">$lex{Missing} $lex{Code}</span>};
	} else {
	    $desc = $g_enrol{$entrytype};
	}

	print qq{<tr><td>$entrytype</td><td>$desc</td><td>$count</td>\n};
	print qq{<td><form action="$self" method="post" style="display:inline;">\n};
	print qq{<input type="hidden" name="page" value="2">\n};

	print qq{<input type="hidden" name="startdate" value="$arr{startdate}">\n};
	print qq{<input type="hidden" name="enddate" value="$arr{enddate}">\n};

	print qq{<input type="hidden" name="entrycode" value="$entrytype">\n};
	print qq{<input type="submit" value="$lex{View}"></form></td></tr>\n};

    }
    print qq{</table>\n};


    # Withdraws
    print qq{<h1>$lex{Student} $lex{Withdrawals}</h1>\n};
    print qq{<table cellspacing="0" cellpadding="3" border="1">\n};
    print qq{<tr><th>$lex{Code}</th><th>$lex{Description}</th><th>$lex{Count}</th><th></th></tr>\n};

    my $sth = $dbh->prepare("select distinct exittype, count(*) from transfer
      where type = 'withdraw' and to_days( date ) >= to_days('$arr{startdate}') and 
      to_days( date ) <= to_days('$arr{enddate}') group by exittype order by exittype");
    $sth->execute();
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; };
    while ( my ( $exittype, $count ) = $sth->fetchrow ) {
	my $desc;
	if ( not $exittype ) { 
	    $desc = qq{<span style="color:red;font-weight:bold;">$lex{Missing} $lex{Code}</span>};
	} else {
	    $desc = $g_wdraw{$exittype};
	}
	print qq{<tr><td>$exittype</td><td>$count</td><td>$desc</td>\n};
	print qq{<td><form action="$self" method="post" style="display:inline;">\n};
	print qq{<input type="hidden" name="page" value="2">\n};
	print qq{<input type="hidden" name="startdate" value="$arr{startdate}">\n};
	print qq{<input type="hidden" name="enddate" value="$arr{enddate}">\n};
	print qq{<input type="hidden" name="exitcode" value="$exittype">\n};
	print qq{<input type="submit" value="$lex{View}"></form></td></tr>\n};


    }

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

    exit;
}



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

    # Get default papersize
    my $papersize = $defaultpapersize;
    $papersize =~ s/paper//; # strip off the 'paper' ending;
    $papersize = ucfirst( $papersize );


    # print sortorder and selection input form.
    print qq{<h1>$lex{Transfer} $lex{Report}</h1>\n};
    print qq{<div><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">\n};
    
    print qq{<tr><td class="bra">$lex{'Start Date'}</td><td><input type="text" };
    print qq{name="startdate" id="sdate" size="10" value="$schoolstart">};
    print qq{<button type="reset" id="start_trigger">...</button>\n};
    print qq{</td></tr>\n};

    print qq{<tr><td class="bra">$lex{'End Date'}</td><td><input type="text" };
    print qq{name="enddate" id="edate" size="10" value="$currsdate">};
    print qq{<button type="reset" id="end_trigger">...</button></td></tr>\n};


    print qq{<tr><td class="cn" colspan="2">};
    print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};

    print qq{</table></form></div>\n};

    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :    "sdate", 
        ifFormat       :    "%Y-%m-%d",
        button         :    "start_trigger",
        singleClick    :    false,
        step           :    1
    });

    Calendar.setup({
        inputField     :    "edate",
        ifFormat       :    "%Y-%m-%d",
        button         :    "end_trigger",
        singleClick    :    false,
        step           :    1
    });
   </script>\n};

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

    exit;

}
