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

# OUTLINE: Find the current term.  Find the student's classes for this
# term and then match them to the scheduled time.

my %lex = ('Student Search' => 'Student Search',
	   'Main' => 'Main',
	   'Timetable' => 'Timetable',
	   'Term' => 'Term',
	   'Not Found' => 'Not Found',
	   'Current Date' => 'Current Date',
	   'Student' => 'Student',
	   'Course' => 'Course',
	   'Teacher' => 'Teacher',
	   'Day' => 'Day',
	   'Period' => 'Period',
	   'Location' => 'Location',
	   'Error' => 'Error',
	   'Find' => 'Find',
	   'Students' => 'Students',
	   'Lastname/Lastname,Firstname/Initials/StudentNumber' => 
	   'Lastname/Lastname,Firstname/Initials/StudentNumber',
	   'No Courses' => 'No Courses',

	   );

my $self = 'whereswaldo.pl';

use DBI;
use CGI;
use Time::JulianDay;
use Cwd;


# 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 qq{$lex{Error}: $@<br>\n};
    die qq{$lex{Error}: $@\n};
}


# Set Dates
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 $currjd = julian_day( split ('-', $currdate) );


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

my $student = $arr{student};

# 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;
    $schpage = $tchpage;
}


# Print Page Header
print qq{$doctype\n<html><head><title>$lex{'Student Search'}</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{<style>.separator { background-color:#DDD;font-weight:bold; }</style>\n};

print qq{$chartype\n</head><body style="margin:1em;">\n};
print qq{[ <a href="$homepage">$lex{Main}</a> };
if ( not $teachermode ) {
    print qq{| <a href="$schpage">$lex{Timetable}</a>};
}
print qq{ ]\n};

if ( not $student ) {
    showStartPage();
}


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


my @studnum;
if ($student =~ /\d+/) {  # we have a student number
    $studnum = $student;
    push @studnum, $studnum

} else { # we have words hopefully with a comma
    ($lastname,$firstname)  = split /\,/, $student;
    $firstname =~ s/^\s*//;
    $lastname =~ s/^\s*//;
    if ($lastname and $firstname){ # both entered.
	$sth = $dbh->prepare("select studnum from student where lastname = ? and firstname = ?");
	$sth->execute( $lastname, $firstname );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $studnum = $sth->fetchrow ){
	    push @studnum,$studnum;
	}
    } elsif ($lastname and not $firstname){ # only lastname (no comma)
	if (length($lastname) == 2){ # search by initials: fi, li.
	    my $fi = substr($lastname,0,1); my $li = substr($lastname,1,1);
	    $sth = $dbh->prepare("select studnum from student 
              where lastname $sql{like} '$li%' and firstname $sql{like} '$fi%'");
	} else {
	    $lastname = $dbh->quote( $lastname );
	    $sth = $dbh->prepare("select studnum from student 
               where lastname = $lastname order by firstname");
	}

	$sth->execute;
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $studnum = $sth->fetchrow){
	    push @studnum,$studnum;
	}
    } else { # print an error....
	print_error( "$lex{Student} $lex{'Not Found'}" );
	showStartPage();
    }

} 

# If no student number found above, then print again, and die;
if ( not @studnum ) {
    print_error( "$lex{Student} $lex{'Not Found'}" );
    showStartPage();
} 


foreach my $studnum ( @studnum ){

    # Find the student's name and grade (for their track)
    my $sth = $dbh->prepare("select lastname, firstname, grade from student where studnum = ? ");
    $sth->execute( $studnum );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
    my ( $lastname, $firstname, $grade) = $sth->fetchrow;

    # Get the Student's term.
    my $term;
    my $track = $g_MTrackTermType{ $grade };
    
    foreach my $trm ( sort keys %{ $g_MTrackTerm{$track} } ) {
	my $startdate = $g_MTrackTerm{$track}{$trm}{'start'};
	my $enddate = $g_MTrackTerm{$track}{$trm}{'end'};

	my $startjd = julian_day( split ('-', $startdate ));
	my $endjd = julian_day( split ('-', $enddate ));

	if ( $endjd >= $currjd and $startjd <= $currjd ){
	    $term = $trm; last;
	}

    }

    # Now search for this student's classes in this term and matching period
    #  in schedule table.

    $sth = $dbh->prepare("select s.subjsec, s.day, s.period from eval e
     left outer join schedat s on e.subjcode= s.subjsec 
     where e.studnum = ? and  e.term = ? and 
     s.term = ? order by s.day, s.period");
    $sth->execute( $studnum, $term, $term );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}

    # Prep for getting subject info inside the loop.
    my $sth2 = $dbh->prepare("select description, teacher, location from subject 
     where subjsec = ?");

    # Teacher Name
    my $sth3 = $dbh->prepare("select lastname, firstname from staff where userid = ?");

    
    print qq{<h1>$firstname $lastname</h1>\n};
    print qq{<div style="font-size:130%;font-weight:bold;">$lex{Term} $term</div>\n};

    my $first = 1;

    my $currday = -1;
    my $prevday;

    while ( my ( $subjsec, $day, $period ) = $sth->fetchrow ){

	$prevday = $currday;
	$currday = $day;
	if ( $currday != $prevday and not $first ) { 
	    print qq{<tr><td colspan="5" class="separator">};
	    print qq{$lex{Day} $currday</td></tr>\n}; # blank line as separator
	}

	# Course Desc
	$sth2->execute($subjsec);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
	my ($desc, $tch, $location) = $sth2->fetchrow;

	# Teacher Name
	$sth3->execute($tch);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
	my ($lastname, $firstname) = $sth3->fetchrow;
	
	if ( $first ) {
	    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
	    print qq{<tr><th>$lex{Course}</th><th>$lex{Teacher}</th><th>$lex{Day}</th>};
	    print qq{<th>$lex{Period}</th><th>$lex{Location}</th></tr>\n};
	    print qq{<tr><td colspan="5" class="separator">};
	    print qq{$lex{Day} $currday</td></tr>\n}; # blank line as separator
	    $first = 0;
	}

	my $timemap = $g_PeriodMap{$grade};
	my $start = $g_PeriodTime{$timemap}{$period}{'s'};
	my $end = $g_PeriodTime{$timemap}{$period}{'e'};
	$start =~ s/\s+$//; # strip trailing space
	$end =~ s/\s+$//;

	my $time = qq{$start-$end};

	print qq{<tr><td>$desc ($subjsec)</td><td>$firstname $lastname ($tch)</td>\n};
        print qq{<td>$day</td><td>$time Per $period</td><td>$location</td></tr>\n};

    }

    if ( not $first ) {
	print qq{</table>\n};
    } else {
	print qq{<div>$lex{'No Courses'}</div><hr style="width:60ch;margin-left:0;">\n};
    }

}


showStartPage();



#--------------
sub print_error {
#--------------
    my $errstring = shift;
    print qq{<h1>$errstring</h1><hr>\n};
}


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

    print qq{<h2>$lex{Find} $lex{Students}</h2>};
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="submit" value="$lex{Find} $lex{Students}">\n};
    print qq{<input type="text" name="student" size="30"><br>\n};
    print qq{$lex{'Lastname/Lastname,Firstname/Initials/StudentNumber'}};
    print qq{</form>\n};

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

    exit;

}
