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

$parpage = '/index.html';

my %lex = ('Main' => 'Main',
	   'Homework' => 'Homework',
	   'No Courses Found' => 'No Courses Found',
	   'View' => 'View',
	   'Continue' => 'Continue',
	   'Grade' => 'Grade',
	   'Error' => 'Error',
	   'by' => 'by',
	   'Teacher' => 'Teacher',
	   'Start Date' => 'Start Date',
	   'Date' => 'Date',
	   'Topic' => 'Topic',
	   'Description' => 'Description',
	   'Or' => 'Or',
	   'Not Found' => 'Not Found',
	   'Courses' => 'Courses',

	   );

my $self = 'viewhomework.pl';

use DBI;
use CGI;


# The location where to load the config file from.
my $configlocation = '../etc';

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

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

# Get Current Date
my @tim = localtime(time);
my $year = $tim[5] + 1900;
my $month = $tim[4] + 1;
my $currdate = "$year-$month-$tim[3]";

my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$rouser,$ropassword);
$dbh->{mysql_enable_utf8} = 1;

# Read in values from conf_system;
my $sth = $dbh->prepare("select datavalue from conf_system
  where dataname = ?");
foreach my $dataname ( qw( r_SupressSubject r_AdditionalComments )) {
    $sth->execute( $dataname );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my $datavalue = $sth->fetchrow;
    eval $datavalue;
    if ( $@ ) {
	print $lex{Error}. " $@<br>\n";
	die $lex{Error}. " $@\n";
    }
}



my $title = "$lex{View} $lex{Homework}";
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<meta name="viewport" content="width=device-width, initial-scale=1.0">\n};
print qq{<link rel="stylesheet" href="$parcss" type="text/css">\n};
print qq{$chartype\n</head><body style="padding:0.5em;">\n};

print qq{[ <a href="$parpage">$lex{Main}</a> ]\n};

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


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

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



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

    # Read grades
    my $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; }
    my @grades = (); 
    while ( my $grade = $sth->fetchrow ) {
	push @grades, $grade;
    }
    @grades = sort {$a <=> $b} @grades;


    # Read Teachers
    $sth = $dbh->prepare("select distinct s.teacher, st.lastname, st.firstname 
      from subject s, staff st
      where s.teacher = st.userid and
      (s.teacher is not NULL ) and ( s.teacher != '' )
      order by st.lastname, st.firstname, st.userid");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    my %teacher = ();
    while ( my ( $userid, $lastname, $firstname ) = $sth->fetchrow ) {
	$teacher{"$lastname, $firstname ($userid)"} = $userid;
    }


    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};

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

    # Start Date
    print qq{<tr><td class="bra">$lex{'Start Date'}</td><td class="la">\n};
    print qq{<input type="text" name="date" size="10" value="$currdate">\n};

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

    # Or
    print qq{<tr><td class="cn">$lex{Or}</td><td></td></tr>\n};


    # Select by Teacher
    print qq{<tr><td class="bra">$lex{View} $lex{by} $lex{Teacher}</td><td class="la">\n};
    print qq{<select  name="teacher"><option></option>};
    foreach my $key ( sort keys %teacher ) {
	my $userid = $teacher{$key};
	print qq{<option value="$userid">$key</option>};
    }
    print qq{</select></td></tr>\n};

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

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

    exit;

}



#---------------
sub showHomework {
#---------------

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

    if ( $arr{grade} ) { # find homework by grade

	# Read grades to verify
	my $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; }
	my %grades = (); 
	while ( my $grade = $sth->fetchrow ) {
	    $grades{$grade} = 1;
	}

	if ( not $grades{ "$arr{grade}" } ) { # no grade match; crack attempt
	    print qq{<h3>$lex{Grade} $lex{'Not Found'}:$arr{grade}</h3>\n};
	    print qq{</body></html>\n};
	    exit;

	} else { # print grade
	    print qq{<h1>$lex{Grade} $arr{grade} $lex{Courses}</h1>\n};
	}


	# Find subjects in this grade.
	my $sth = $dbh->prepare("select subjsec, description from subject where grade = ?");
	$sth->execute( $arr{grade} );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	my %subjects = ();
	while ( my ($subjsec, $description) = $sth->fetchrow ) {

	    my ($subjcode, $dud) = split(/-/, $subjsec );
	    # skip supressed subjects
	    if ( $r_SupressSubject{$subjcode} or
		 $r_SupressSubject{$subjsec} ) { next; } #skip 
	    
	    # skip if member of %r_AdditionalComments
	    if ( $r_AdditionalComments{$subjsec} or $r_AdditionalComments{$subjcode} ) {
		next; 
	    }

	    $subjects{"$description ($subjsec)"} = $subjsec;
	}

	if ( not %subjects ) {
	    print qq{<h1>$lex{'No Courses Found'}</h1>\n};
	    print qq{</body></html>\n};
	    exit;
	}


	# Prepare to get homework info
	my $sth1 = $dbh->prepare("select * from plan_homework where subjsec = ? and 
	 to_days(duedatetime) >= to_days('$arr{date}') order by id");

	my $sth2 = $dbh->prepare("select st.lastname, st.firstname, st.sal, s.teacher 
				 from staff st, subject s
				 where st.userid = s.teacher and s.subjsec = ?");

	# Loop through all subjects in this grade.
	foreach my $desc ( sort keys %subjects ) {

	    my $subjsec = $subjects{$desc};

	    # Get Teacher Information
	    $sth2->execute( $subjsec );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    my ( $lastname, $firstname, $sal, $userid ) = $sth2->fetchrow;
	    if ( not $sal ) { $sal = $firstname; } # if not Mr. Smith, Fred Smith

	    my $first = 1;
	    print qq{<h3>$desc - $sal $lastname</h3>\n};

	    # Get Homework info, if any.
	    $sth1->execute( $subjsec );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	    while ( my $ref = $sth1->fetchrow_hashref ) {
		if ( $ref ) {
		    if ( $first ) {
			print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
			print qq{<tr><th>$lex{Date}</th><th>$lex{Topic}</th>};
			print qq{<th>$lex{Description}</th></tr>\n};
			$first = 0;
		    }

		    print qq{<tr><td>$ref->{duedatetime}</td><td>$ref->{topic}</td>};
		    print qq{<td>$ref->{description}</td></tr>\n};
		}
	    } 

	    if ( $first ) {
		print qq{<p>$lex{Homework} $lex{'Not Found'}</p>\n};
	    } else {
		print qq{</table><p></p>\n};
	    }

	} # loop through all subjects.
    } # end of homework by Grade


    print qq{<hr>\n};

    if ( $arr{teacher} ) { # find homework by teacher

	# Read Teachers to verify
	my $sth = $dbh->prepare("select distinct teacher from subject");
	$sth->execute;
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	my %teacher = ();
	while ( my $userid = $sth->fetchrow ) {
	    $teacher{$userid} = 1;
	}

	# Verify teacher
	if ( not $teacher{ $arr{teacher} } ) { # no teacher match; crack attempt
	    print qq{<h3>$lex{Teacher} $lex{'Not Found'}:$arr{teacher}</h3>\n};
	    print qq{</body></html>\n};
	    exit;
	} else { # print teacher name
	    my $sth = $dbh->prepare("select lastname, firstname, sal from staff where userid = ?");
	    $sth->execute( $arr{teacher} );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    my ($lastname, $firstname, $sal ) = $sth->fetchrow;

	    print qq{<h1>$sal $firstname $lastname</h1>\n};
	}


	# Find subjects of this teacher
	$sth = $dbh->prepare("select subjsec, description from subject where teacher = ?");
	$sth->execute( $arr{teacher} );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	my %subjects = ();
	while ( my ($subjsec, $description) = $sth->fetchrow ) {

	    my ($subjcode, $dud) = split(/-/, $subjsec );
	    # skip supressed subjects
	    if ( $r_SupressSubject{$subjcode} or
		 $r_SupressSubject{$subjsec} ) { next; } #skip 
	    
	    # skip if member of %r_AdditionalComments
	    if ( $r_AdditionalComments{$subjsec} or $r_AdditionalComments{$subjcode} ) {
		next; 
	    }

	    $subjects{"$description ($subjsec)"} = $subjsec;
	}

	if ( not %subjects ) {
	    print qq{<h1>$lex{'No Courses Found'}</h1>\n};
	    print qq{</body></html>\n};
	    exit;
	}


	# Prepare to get homework info
	my $sth1 = $dbh->prepare("select * from plan_homework where subjsec = ? and 
	 to_days(duedatetime) >= to_days('$arr{date}') order by id");

	# Loop through all subjects in this grade.
	foreach my $desc ( sort keys %subjects ) {

	    my $subjsec = $subjects{$desc};

	    my $first = 1;
	    # Get Homework info, if any.
	    $sth1->execute( $subjsec );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    while ( my $ref = $sth1->fetchrow_hashref ) {
		if ( $ref ) {
		    if ( $first ) {
			print qq{<h3>$desc</h3>\n};
			print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
			print qq{<tr><th>$lex{Date}</th><th>$lex{Topic}</th>};
			print qq{<th>$lex{Description}</th></tr>\n};
			$first = 0;
		    }
		    print qq{<tr><td>$ref->{duedatetime}</td><td>$ref->{topic}</td>};
		    print qq{<td>$ref->{description}</td></tr>\n};
		}
	    } 
	    if ( $first ) {
		print qq{<p><b>$desc</b> - $lex{Homework} $lex{'Not Found'}</p>\n};
	    } else {
		print qq{</table><p></p>\n};
	    }

	} # loop through all subjects.
    } # end of homework by Teacher


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

} # end of showHomework
