#!/usr/bin/perl
#  Copyright 2001-2018 Leslie Richardson
#  This file is part of Open Administration for Schools

use DBI;
use CGI;
use Number::Format qw(round);


my $self = 'checkdemog.pl';

my %lex = ( 'Main' => 'Main',
	    'Error' => 'Error',
	    'Grade' => 'Grade',
	    'Homeroom' => 'Homeroom',
	    'Group' => 'Group',
	    'Separate with Spaces' => 'Separate with Spaces',
	    'Blank=All' => 'Blank=All',
	    'Continue' => 'Continue',

	    );


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


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

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


my @tim = localtime(time);
my $year = $tim[5] + 1900;
$tim[4]++;
for (0..4){if (length($tim[$_]) == 1){ $tim[$_] = '0'.$tim[$_];}}
my $currdate = "$year-$tim[4]-$tim[3]";
my $currtime = "$tim[2]:$tim[1]:$tim[0]";


print qq{$doctype\n<html><head><title>Check Demographics Data</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">$chartype\n};
print qq{</head><body>[ <a href="$reppage">Report Card</a> |\n};
print qq{<a href="$exppage">Export</a> ]\n};
print qq{<h1>Check Demographics Data</h1>\n};

#if ( not $arr{page} ) {
#    showStartPage();

#} elsif ( $arr{page} == 1 ) {
#    delete $arr{page};
    checkStudents();
#}



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

    # Setup the form and start of table.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<table cellpadding="3" border="1" cellspacing="0">\n};
    
    print qq{<tr><td align="right">$lex{Group}</td><td align="left">\n};
    print qq{<select name="groupType"><option>$lex{Grade}</option>\n};
    print qq{<option>$lex{Homeroom}</option></select>\n};
    print qq{</td></tr>\n};

    print qq{<tr><td class="ra">$lex{Values}</td><td class="la">\n};
    print qq{<input type="text" name="groupValue" size="25"><br>\n};
    print qq{$lex{'Separate with Spaces'}, $lex{'Blank=All'}</td></tr>\n};


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

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

    exit;

}



#-----------------
sub checkStudents {
#-----------------

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

    #    print qq{<form action="$self" method="post">\n};
    #    print qq{<input type="hidden" name="page" value="2">\n};
    #    print qq{<input type="submit" value="Send Selected Student Marks"><br>\n};

    my $sth = $dbh->prepare("select studid, lastname, firstname, studnum, provnum, birthdate, grade, 
      healthid, sex, address1, prov1, pcode1 from student order by lastname, firstname");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr;}
    my $rows = $sth->rows;

    print qq{<table cellpadding="3" border="1" cellspacing="0">\n};
    print qq{<tr><th>Error</th><th>Name</th></tr>\n};

    my $first = 1;

    while ( my ( $studid,$lastname, $firstname, $studnum, $provnum, $birthdate, $grade, 
		 $healthid, $sex, $address1, $prov1, $pcode1 ) = $sth->fetchrow ) {

	# Check Provincial Number
	if ( $provnum ) {
	    my $temppn = $provnum;
	    my $tempcd = chop( $temppn );  
	    my $checkdigit = &checkprovnum( $temppn );
	    if ( $checkdigit != $tempcd ) {
		print qq{<tr><td><b><font color="red">Parity Error</font></b></td>\n};

		print qq{<td><form action="$cgiurl/studed.pl" method="post" style="display:inline;">\n};
		print qq{<input type="hidden" name="id" value="$studid">\n};
		print qq{<input type="submit" name="submit" value="Edit"></form>\n};

		print qq{<i>$lastname</i>, $firstname</a>};
		print qq{($studnum/$birthdate) - Prov #: $provnum</td>};
		print qq{</tr>\n};
		$first = 0;
	    }
	}


	
	# Check Health Number
	$healthid =~ s/ //g;  # strip spaces
	if ( checkHealthId( $healthid ) ) {
	    print qq{<tr><td><b><font color="red">Parity Error</font></b></td>};

	    print qq{<td><form action="$cgiurl/studed.pl" method="post" style="display:inline;">\n};
	    print qq{<input type="hidden" name="id" value="$studid">\n};
	    print qq{<input type="submit" name="submit" value="Edit"></form>\n};

	    print qq{<b>$lastname</b>, $firstname};
	    print qq{($studnum) - HSN#: $healthid</td></tr>\n};
	    $first = 0;
	}

=head
	if ( not $healthid ) {
	    print qq{<tr><td><b>No Health Services Number</b></td>};
	    print" <td><b>$lastname</b>, $firstname ($studnum)</td></tr>\n};
	    $first = 0;
	}
=cut    


	# Check Gender Values ( M or F) and fix if necessary
	if ( $sex ) { # Check Gender
	    if ( $sex ne 'M' and $sex ne 'F' ) { # Error
		if ( $sex eq 'm' or $sex eq 'f' ) { #fix case.
		    $sex = uc( $sex );
		    my $sth1 = $dbh->prepare("update student set sex = ? where studnum = ?");
#		    $sth1->execute( $sex, $studnum );
		    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr;}
		    $first = 0;
		} else { # not fixable.
		    print qq{<tr><td><b>Gender Error</b></td>};

		    print qq{<td><form action="$cgiurl/studed.pl" method="post" style="display:inline;">\n};
		    print qq{<input type="hidden" name="id" value="$studid">\n};
		    print qq{<input type="submit" name="submit" value="Edit"></form>\n};

		    print qq{ <b>$lastname</b>, $firstname ($studnum) - Gender:$sex</td></tr>\n};
		    $first = 0;
		}
	    }
	    
	} else {
	    
	    print qq{<tr><td><b>Missing Gender</b></td>};

	    print qq{<td><form action="$cgiurl/studed.pl" method="post" style="display:inline;">\n};
	    print qq{<input type="hidden" name="id" value="$studid">\n};
	    print qq{<input type="submit" name="submit" value="Edit"></form>\n};

	    print qq{<b>$lastname</b>, $firstname ($studnum)</td></tr>\n};
	    $first = 0;
	}



	# Get and Check the Grade
	if ( $grade eq 'k' or $grade eq 'pk' or  $grade eq 'p3' ) { 
	    $grade = uc( $grade );
	    my $sth1 = $dbh->prepare("update student set grade = ? where studnum = ?");
#	    $sth1->execute( $grade, $studnum );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	} else { # Do more checking.
	    my @gradelist = qw(K PK P3 1 2 3 4 5 6 7 8 9 10 11 12 );
	    my $pass = 0;
	    foreach my $gr ( @gradelist ) {
		if ( $grade eq $gr ) { $pass = 1; last; }
	    }

	    if ( not $pass ) {
		print qq{<tr><td><b>Grade Error</b></td>};

		print qq{<td><form action="$cgiurl/studed.pl" method="post" style="display:inline;">\n};
		print qq{<input type="hidden" name="id" value="$studid">\n};
		print qq{<input type="submit" name="submit" value="Edit"></form>\n};

		print qq{<b>$lastname</b>, $firstname ($studnum) - Grade:$grade</td></tr>\n};
		$first = 0;
	    }
	}


	# Get Address Info; returns an address hash.

	# foreach my $key ( sort keys %sr ) { print qq{K:$key V:$sr{$key}<br>\n}; }
	# Check Address, Province, Postal Code.
	
	if ( not $address1 ) {
	    print qq{<tr><td><b>Missing Address</b></td>};

	    print qq{<td><form action="$cgiurl/studed.pl" method="post" style="display:inline;">\n};
	    print qq{<input type="hidden" name="id" value="$studid">\n};
	    print qq{<input type="submit" name="submit" value="Edit"></form>\n};

	    print qq{ <b>$lastname</b>, $firstname ($studnum)</td></tr>\n};
	    $first = 0;
	}

	# Check Postal Code
	if ( not $pcode1 ) {
	    print qq{<tr><td><b>Missing Postal Code</b></td>};

	    print qq{<td><form action="$cgiurl/studed.pl" method="post" style="display:inline;">\n};
	    print qq{<input type="hidden" name="id" value="$studid">\n};
	    print qq{<input type="submit" name="submit" value="Edit"></form>\n};

	    print qq{<b>$lastname</b>, $firstname ($studnum)</td></tr>\n};
	    $first = 0;
	    
	} else { # Test the code
	    my $testpc = $pcode1;
	    if ( !( $testpc =~ m/^\s*([a-z]\s*\d){3}\s*$/i ) ) { # failure!
		print qq{<tr><td><b>Invalid Postal Code - $testpc</b></td>};

		print qq{<td><form action="$cgiurl/studed.pl" method="post" style="display:inline;">\n};
		print qq{<input type="hidden" name="id" value="$studid">\n};
		print qq{<input type="submit" name="submit" value="Edit"></form>\n};

		print qq{<b>$lastname</b>, $firstname ($studnum)</td></tr>\n};
		$first = 0;
	    }
	}

	# Check Province (and fix, if possible)
	my $fail = 0;
	if ( not $prov1 ) {
	    print qq{<tr><td><b>Missing Province Code</b></td>};

	    print qq{<td><form action="$cgiurl/studed.pl" method="post" style="display:inline;">\n};
	    print qq{<input type="hidden" name="id" value="$studid">\n};
	    print qq{<input type="submit" name="submit" value="Edit"></form>\n};

	    print qq{<b>$lastname</b>, $firstname ($studnum)</td></tr>\n};
	    $first = 0;

	} else { # test for case problems and also 'Sask' variant.
	    my $testprov = $prov1;
	    if ( uc($testprov) ne $prov1 ) { # we have a case error.
		$prov1 = uc( $testprov );
		$fail = 1;
	    } elsif ( lc( $testprov ) eq 'sask' ) {
		$prov1 = 'SK';
		$fail = 1;
	    }

	    if ( $fail ) { # rewrite update
		my $sth1 = $dbh->prepare("update student set prov1 = ? where studnum = ?");
#		$sth1->execute( $prov1, $studentid );
		if ($DBI::errstr) { print $DBI::errstr; die;}		
	    }

	}


    } # End of Student Loop

    if ( $first ) {
	print qq{<tr><td colspan="2">No Errors Found</td></tr>\n};
    }
    
    print qq{</table></body></html>\n};

    exit;

} # end of selectStudents



#----------------------
# Lower Level Functions
#----------------------

#----------------
sub checkprovnum {
#----------------

    my @pn = split(//,$_[0]);
    for ( my $i=1; $i<=8; $i += 2) {
	$pn[$i] *= 2;
	if ($pn[$i] > 9) {
	    my @tmp = split(//,$pn[$i]);
	    $pn[$i] = $tmp[0] + $tmp[1];
        }
    }
    
    my $tempnum = 0;
    foreach my $pnum (@pn) {
	$tempnum += $pnum;
    }
    @pn = split(//,$tempnum);   
    my $retval= pop(@pn);
    $retval = 9 - $retval;
    return $retval;

}


#----------------
sub checkHealthId {
#----------------

    my $hn = shift;
    my @hn = split(//,$hn);
    my ($i, $total);
    foreach my $num (reverse @hn){
	$i++;
	$num *= $i;
	$total += $num;
    }
    my $remainder = $total % 11;  # should be zero, if correct.
    
    return $remainder;

}
