#!/usr/bin/perl
#  Copyright 2001-2019 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 = ('Main' => 'Main',
	   'Error' => 'Error',
	   'View' => 'View',
	   'Grade' => 'Grade',
	   'No Records Found' => 'No Records Found',
	   'Continue' => 'Continue',
	   'Homeroom' => 'Homeroom',
	   'Discipline' => 'Discipline',
	   'Select by' => 'Select by',
	   'Show Withdrawn' => 'Show Withdrawn',
	   'Students' => 'Students',
	   'Not Found' => 'Not Found',
	   'Student' => 'Student',
	   'OR' => 'OR',
	   'No Selection' => 'No Selection',
	   'Count' => 'Count',
	   'Check Next Page' => 'Check Next Page',
	   
	   );

use DBI;
use CGI;
use Cwd;

my $self = 'hvView.pl';


# Get current dir so know what path for config files.
my $configpath;
my $teachermode;
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $teachermode = 1;
    $configpath = '..'; # go back one to get to etc.
} else {
    $configpath = '../..'; # go back two to get to etc.
}


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

# Teachermode
if ( $teachermode ) { # running on teacher site
    $css = $tchcss;
    $homepage = $tchpage;
    $downloaddir = $tchdownloaddir;
    $webdownloaddir = $tchwebdownloaddir;
}


my $q = new CGI;
print $q->header;
my %arr = $q->Vars;

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


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


# Page Header
my $title = "$lex{View} Home Visits";
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};

=head
if ( not $arr{page} ) { # calendar popup.
    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};
}
=cut

print qq{$chartype\n</head><body style="padding:1em 2em;">\n};

print qq{[ <a href="$homepage">$lex{Main}</a> \n};
if ( not $teachermode ) {
    print qq{<a href="$discpage">| $lex{Discipline}</a> \n};
}
print qq{]\n};
print qq{<h1>$title</h1>\n};


# I'll leave this in place in case we have to pass values 
if ( not $arr{page} ) {
    showStartPage();

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

} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    showVisits();
}



#-----------------
sub selectStudents {
#-----------------

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

    my $checked;
    if ( $arr{checknextpage} ) {
	$checked = qq{checked="checked"};
	delete $arr{checknextpage};
    }

    
    my $studenttable = 'student';
    if ( $arr{showwithdrawn} ) {
	$studenttable = 'studentall';
    }

    my $skipblanks = $arr{skipblanks};
    delete $arr{skipblanks};

    
    my ($select, $selectval, $groupname);
    if ( $arr{grade} ) {
	$select = "where grade = ?";
	$selectval = $arr{grade};
	$groupname = $lex{Grade};

    } elsif ( $arr{homeroom} ) {
	$select = "where homeroom = ?";
	$selectval = $arr{homeroom};
	$groupname = $lex{Homeroom};

    } else {
	print qq{<h3>$lex{'No Selection'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    print qq{<h3>$groupname $selectval</h3>\n};


    # Loop through all students in this grade/homeroom
    my $sth = $dbh->prepare("select lastname, firstname, studnum from $studenttable
       $select order by lastname, firstname");
    $sth->execute( $selectval );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }


    # Check for home visits
    my $sth1 = $dbh->prepare("select count(*) from homevisit where studnum = ?");

    # Check for Withdrawn
    my $sth2 = $dbh->prepare("select count(*) from studentwd where studnum = ?");

    my $first = 1;

    # Student Loop
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;

	
	# Check for visit records
	$sth1->execute( $r{studnum} );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $disccount = $sth1->fetchrow;
	if ( not $disccount and $skipblanks ) { next; }

	
	if ( $first ) {
	    # Start Form
	    print qq{<form action="$self" method="post">\n};
	    print qq{<input type="hidden" name="page" value="2">\n};
	    
	    print qq{<div><input type="submit" value="$lex{Continue}"></div>\n};

	    # Start Table
	    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
	    print qq{<caption style="color:red;">Red = Withdrawn</caption>\n};
	    print qq{<tr><th></th><th>$lex{Student}</th><th>Home Visit<br>$lex{Count}</th></tr>\n};

	    $first = 0;
	}

	
	my $wd;
	if ( $arr{showwithdrawn} ) { # check if withdrawn
	    $sth2->execute( $r{studnum} );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    $wd = $sth2->fetchrow;
	}


	print qq{<tr>};
	if ( $disccount ) { 
	    print qq{<td><input type="checkbox" name="$r{studnum}" value="1" $checked></td>\n}; 
	} else { 
	    print qq{<td></td>\n}; 
	}

	my $name;
	if ( $wd ) {
	    $name = qq{<span style="color:red;"><b>$r{lastname}</b>, $r{firstname}</span>};
	} else {
	    $name = qq{<b>$r{lastname}</b>, $r{firstname}};
	}


	print qq{<td>$name ($r{studnum})</td><td class="cn">$disccount</td></tr>\n};
			   
    }


    if ( $first ) { # no Students
	print qq{<h3>$lex{Students} $lex{'Not Found'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    

    print qq{</table>\n};
    print qq{<div><input type="submit" value="$lex{Continue}"></div>\n};

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

    exit;

}




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

    my (@homerooms, @grades, @schoolyears );
    # Get Homerooms
    my $sth = $dbh->prepare("select distinct homeroom from student 
      where homeroom is not NULL and homeroom != ''");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $hr = $sth->fetchrow ) {
	push @homerooms, $hr;
    }
    @homerooms = sort {$a <=> $b} @homerooms;

    # Get Grades
    $sth = $dbh->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 $gr = $sth->fetchrow ) {
	push @grades, $gr;
    }
    @grades = sort {$a <=> $b} @grades;


    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">\n};


    # Select Grade
    print qq{<tr><td class="bra">$lex{'Select by'} $lex{Grade}</td>};
    print qq{<td><select name="grade"><option></option>\n};
    foreach my $gr ( @grades ) {
	print qq{<option>$gr</option>\n};
    }
    print qq{</select></td></tr>\n};

    # OR
    print qq{<tr><td colspan="2" style="text-align:center;">$lex{OR}</td></tr>\n};


    # Select Homeroom
    print qq{<tr><td class="bra">$lex{'Select by'} $lex{Homeroom}</td>};
    print qq{<td><select name="homeroom"><option></option>\n};
    foreach my $hr ( @homerooms ) {
	print qq{<option>$hr</option>\n};
    }
    print qq{</select></td></tr>\n};


    # Check Next Page
    print qq{<tr><td class="bra">$lex{'Check Next Page'}</td>};
    print qq{<td><input type="checkbox" name="checknextpage" value="1"></td></tr>\n};
    

    # Withdrawn
    print qq{<tr><td class="bra">$lex{'Show Withdrawn'}</td>};
    print qq{<td><input type="checkbox" name="showwithdrawn" value="1"></td></tr>\n};


    # Show Students without Homevisits
    print qq{<tr><td class="bra">Skip Students without Records</td>};
    print qq{<td><input type="checkbox" name="skipblanks" value="1" checked="checked"></td></tr>\n};


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

    exit;

}




#-------------
sub showVisits {
#-------------

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

    my $sth = $dbh->prepare("select * from homevisit where studnum = ? order by date");
    my $sth1 = $dbh->prepare("select lastname, firstname, grade, homeroom from studentall where studnum = ?");
    my $sth2 = $dbh->prepare("select lastname, firstname from staff where userid = ?");

    my $first = 1;

    my (%sort, %name);
    foreach my $studnum ( keys %arr ) {
    
	$sth1->execute( $studnum ) ;
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    	while ( my $ref = $sth1->fetchrow_hashref ) {
	    my %r = %$ref;
	    my ($ln,$fn) = ($r{lastname},$r{firstname});
	    
	    $sort{"$ln$fn$studnum"} = $studnum;
	    $name{$studnum} = "<b>$ln</b>,$fn";
	}
    }

    

    foreach my $key ( sort keys %sort ) {
	my $studnum = $sort{$key};
	
	$sth->execute( $studnum ) ;
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    
	while ( my $ref = $sth->fetchrow_hashref ) {
	    my %r = %$ref;

	    my $studnum = $r{studnum};
	    my $userid = $r{author};

	    if ( $first ) {
		print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
		print qq{<tr><th>Student</th><th>Date</th><th>Author</th>\n};
		print qq{<th>Reason</th><th>Description</th></tr>\n};
		$first = 0;
	    }
	
	    # Get Student Name
#	    $sth1->execute( $studnum );
#	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
#	    my ( $lastname, $firstname ) = $sth1->fetchrow;

	    # Get Staff Name
	    $sth2->execute( $userid );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ( $slastname, $sfirstname ) = $sth2->fetchrow;

	    # Show Record
	    print qq{<tr><td>$name{$studnum}</td><td>$r{date}</td><td>$sfirstname $slastname</td>\n};
	    print qq{<td>$r{reason}</td><td>$r{description}</td></tr>\n};
	
	    
	} # end of student loop.
    }

    if ( $first ) {
	print qq{<div style="font-weight:bold;">};
	print qq{$lex{'No Records Found'}</div>\n};
	
    } else {
	print qq{</table>\n};
    }

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

}
