#!/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',
	   'Add' => 'Add',
	   'Discipline' => 'Discipline',
	   'Student' => 'Student',
	   'Continue' => 'Continue',
	   'Save' => 'Save',
	   'Date' => 'Date',
	   'No User Id' => 'No User Id',
	   'No Password' => 'No Password',
	   'Please Log In' => 'Please Log In',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Select' => 'Select',
	   'Students' => 'Students',
	   'Missing Value' => 'Missing Value',
	   'Score' => 'Score',
	   'Added' => 'Added',
	   'Or' => 'Or',
	   'Time' => 'Time',
	   'Event' => 'Event',
	   'Location' => 'Location',
	   'Not Selected' => 'Not Selected',
	   'Description' => 'Description',
	   'Author' => 'Author',
	   'Actions' => 'Actions',
	   'All' => 'All',
	   
	   );

use DBI;
use CGI;
use CGI::Session;
use Cwd;

my $self = 'hvAdd.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 qq{$lex{Error}: $@<br>\n};
    die qq{$lex{Error}: $@\n};
}


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

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


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


my ($session, $userid);
# Get current dir so know what CSS to display and shift to teacher settings.
if ( getcwd() =~ /tcgi/ ) { # we are in tcgi
#    my $dir = getcwd();
#    print "DIR:$dir<br>\n";
    $css = $tchcss;
    $homepage = $tchpage;
    $schpage = $tchpage;


    # Session Setup Here
    $session = new CGI::Session("driver:$dbtype;serializer:FreezeThaw",
     undef,{Handle => $dbh}) or die CGI::Session->errstr;

    # Get/Set  Session Values (a defined userid means it was passed)
    if ( $arr{userid} ){ # we want to login, passed userid/password pair.

	# Check password/userid against database (-1 no user, -2 wrong password);
	my $error = checkPassword($arr{userid}, $arr{password});
	if ($error == -1){ print $q->header( -charset, $charset ); print qq{<h3>$lex{'No User Id'}</h3>}; }
	if ($error == -2){ print $q->header( -charset, $charset ); print qq{<h3>$lex{'No Password'}</h3>}; }

	$cookietime = checkCookieTime( $arr{duration} );

	# Set values for userid and logged_in in session
	$session->param( 'logged_in','1');
	$session->expire( 'logged_in', $cookietime );
	$session->param( 'userid',$arr{userid} );
	$session->param( 'duration',$cookietime );

	$userid = $arr{userid};

	
    } else { # check logged_in value in session

	if ( not $session->param('logged_in') ){
	    $userid = $session->param('userid');
	    print $q->header( -charset, $charset );
	    print qq{<form action="../tlogin.pl" method="post" style="display:inline;">\n};
	    print qq{<input type="hidden" name="userid" value="$userid">\n};
	    print qq{<input type="hidden" name="script" value="$self">\n};
	    print qq{<input type="submit" value="$lex{'Please Log In'}">\n};
	    print qq{</form></body></html>\n};
	    exit;
	}
	# Ok, we have a login. Values below we have in environment.

	$userid = $session->param('userid');
	$duration = $session->param('duration');

	if ( not ($duration =~ /\+/)) { # if not in +20m format, do so.
	    $duration = checkCookieTime( $duration );
	}

	$session->expire('logged_in', $duration );

    } # End of check for logged_in value

    print $session->header( -charset, $charset );

} else {
    print $q->header( -charset, $charset );

}    
# Session Setup End, if teacher site


# Page Header
my $title = qq{$lex{Add} Home Visit};

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

if ( not $arr{page} ) {
    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 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{] <h1>$title</h1>\n};


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

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

}  elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    writeEvent();
}


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

    my (@homerooms, @grades );
    # 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;


    my (%staff, @staff);
    $sth = $dbh->prepare("select lastname, firstname, userid from staff order by lastname, firstname");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my ($ln,$fn,$uid) = $sth->fetchrow ) {
	$staff{$uid} = "$ln, $fn";
	push @staff, $uid;
    }

    
    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><th style="text-align:right;">$lex{Event}</th><th></th></tr>\n};

    
    # Author
    print qq{<tr><td class="bra">$lex{Author}</td>\n};
    if ( $teachermode ) { # display only one teacher.
	print qq{<td><select name="author"><option value="$userid">$staff{$userid}</option>\n};
	
    } else {
        print qq{<td><select name="author"><option></option>\n};
	foreach my $userid ( @staff ) {
	    print qq{<option value="$userid">$staff{$userid} ($userid)</option>\n};
	}
    }
    print qq{</select></td></tr>\n};

    
    # Date
    print qq{<tr><td class="bra">$lex{Date}</td>\n};
    print qq{<td><input type="text" name="date" id="date" size="10" value="$currdate">\n};
    print qq{<button type="reset" id="start_trigger">...</button> yyyy-mm-dd\n};
    print qq{</td></tr>\n};

    # Time
#    print qq{<tr><td class="bra">$lex{Time}</td>\n};
#    print qq{<td><input type="text" name="time" size="10" value="$currtime"> HH:MM};
#    print qq{</td></tr>\n};

    # Location
#    print qq{<tr><td class="bra">$lex{Location}</td>\n};
#    print qq{<td><input type="text" name="location" size="14">};
#    print qq{</td></tr>\n};

=head    
    # Reason for Visit  Now loaded from conf system
    print qq{<tr><td class="bra">Reason for Home Visit</td>\n};
    print qq{<td><select name="reason"><option></option>\n};
    foreach my $reason ( @g_HomeVisitReason ) {
	print qq{<option>$reason</option>\n};
    }
    print qq{</select></td></tr>\n};
    
   
    # Description
    print qq{<tr><td class="bra">$lex{Description}</td>\n};
    print qq{<td><textarea name="description" rows="4" cols="80"></textarea>};
    print qq{</td></tr>\n};
=cut    

    # Divider
    print qq{<tr><th>$lex{Select} $lex{Students}</th><th></th></tr>\n};

    
    # Select Grade
    print qq{<tr><td class="bla">Current Grades</td>};
    print qq{<td style="la">};
    foreach my $gr ( @grades ) {
	print "$gr ";
    }
    print qq{</td></tr>\n};
    
    print qq{<tr><td colspan="2">Enter Grade(s) <input type="text" style="width:4em;" name="grade">};
    print qq{ Separate with Spaces</td></tr>\n};

    # OR
    print qq{<tr><td class="bla" style="color:blue;" colspan="2">$lex{Or}</td></tr>\n};


    # Select Homeroom
    print qq{<tr><td class="bla">Current Homerooms</td>};
    print qq{<td>};
    foreach my $hr ( @homerooms ) {
	print qq{$hr };
    }
    print qq{</td></tr>\n};
    
    
    print qq{<tr><td colspan="2">Enter Homerooms(s) <input type="text" style="width:4em;" name="homeroom">};
    print qq{ Separate with Spaces</td></tr>\n};

=head
    # Actions for All Students
    # Divider
    print qq{<tr><th>$lex{Actions} - $lex{All} $lex{Students}</th><th></th></tr>\n};
    
    # Actions
    print qq{<tr><td class="bra">$lex{Actions}</td>};
    print qq{<td>};
    my $dcount = 1;
    foreach my $act ( sort @g_DiscAction ) {
	print qq{<input type="checkbox" name="A:$act" value="1">$act };
	if ( $dcount % 5 == 0 ) { print qq{</td></tr>\n<tr><td></td><td>}; }
	$dcount++;
    }
    print qq{</td></tr>\n};


=cut    

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


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

    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :    "date", // id of the input field
        ifFormat       :    "%Y-%m-%d", // format of the input field
        button         :    "start_trigger", // trigger for the calendar (button ID)
        singleClick    :    false,        // double-click mode
        step           :    1             // show all years in drop-down boxes 
    });
   </script>\n};

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

    exit;

} # end of showStartPage


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

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

    # Check for any Blanks in required fields
    my $missingflag;
    foreach my $key ('date', 'author' ) { #'description'
	if ( not $arr{$key} ) {
	    $missingflag .= " $key";
	}
    }
    if ( $missingflag ) {
	print "<h3>$lex{'Missing Value'}: $missingflag</h3>\n";
	print "</body></html>\n";
	exit;
    }


    # Check Date format.
    my $err = checkDate( $arr{date} );
    if ( $err == 1 ) {
	print qq{<h3>$lex{Error}: Date Outside School Year: $arr{tdate}</h3>\n};
	print qq{</body></html>\n};
	exit;
	
    } elsif ( $err ) {
	print qq{<h3>Date Error: $err</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    my (@grades, @homerooms);
    my $select;
    if ( $arr{grade} ) {
	@grades = split(/\s+/, $arr{grade} );
    } elsif ( $arr{homeroom} ) {
	@homerooms = split(/\s+/, $arr{homeroom} );
    }

    # Test
#    foreach my $gr ( @grades ) { print qq{Grade:$gr<br>\n}; }
#    foreach my $hr ( @homerooms ) { print qq{Homeroom:$hr<br>\n}; }

    if ( not @grades and not @homerooms ) {
	print qq{<h3>$lex{Students} $lex{'Not Selected'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    my (%students, %sort);
    
    if ( @grades ) {
	
	my $sth = $dbh->prepare("select * from student where grade = ?");
	
        foreach my $gr ( @grades ) {
	    
	    $sth->execute( $gr );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    
	    while ( my  $ref = $sth->fetchrow_hashref ) {
		my $studnum = $ref->{studnum};
		$students{$studnum} = $ref;
		$sort{"$ref->{lastname}$ref->{firstname}$studnum"} = $studnum;
	    }
	}
    }


    if ( @homerooms ) {
	
	my $sth = $dbh->prepare("select * from student where homeroom = ?");
	
        foreach my $hr ( @homerooms ) {
	    $sth->execute( $hr );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    
	    while ( my  $ref = $sth->fetchrow_hashref ) {
		my $studnum = $ref->{studnum};
		$students{$studnum} = $ref;
		$sort{"$ref->{lastname}$ref->{firstname}$studnum"} = $studnum;
	    }
	}
    }
    

#    print qq{<div style="font-size:130%;"><b>$lex{Date}</b> $arr{tdate}</div>\n};

    # Print Form Heading
    print qq{<form action="$self" method="post"> \n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="hidden" name="date" value="$arr{date}">\n};
    print qq{<input type="hidden" name="author" value="$arr{author}">\n};

    my $first = 1;

    # Student Loop
    foreach  my  $key ( sort keys %sort  ) {
	my $studnum = $sort{$key};
	my %r = %{ $students{$studnum}};

	if ( $first ) {
	    print qq{<div class="la"><input type="submit" value="$lex{Continue}"></div>\n};
	    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
	    print qq{<tr><th>$lex{Student}</th><th>$lex{Grade}</th><th>$lex{Homeroom}</th></tr>\n};
	    $first = 0;
	}

	print qq{<tr><td class="la"><input type="checkbox" name="$r{studnum}" value="1" $checked> };
	print qq{<b>$r{lastname}</b>, $r{firstname}</td><td class="cn">$r{grade}</td>};
	print qq{<td class="cn">$r{homeroom}</td></tr>\n};
    }

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

    exit;

    
} # end of selectStudent



#-------------------
sub enterStudentInfo {
#-------------------

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

    my $date = $arr{date};
    delete $arr{date};
    my $author = $arr{author};
    delete $arr{author};
    # Anything left in %arr will be student numbers.

#    foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
  
    if ( not %arr ) {
	print qq{<h3>$lex{Error}: No Student Selection</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    print qq{<h3>Date: $date<br>Author: $author</h3>\n};


    
    my (%sort, %student);
    my $sth = $dbh->prepare("select * from student where studnum = ?");
    foreach my $studnum  (keys %arr ) {
	$sth->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;
	$student{$studnum} = $ref;
	my %r = %{ $ref };
	$sort{"$r{lastname}$r{firstname}$studnum"} = $studnum;
    }


    
    # Print Form Heading
    print qq{<form action="$self" method="post"> \n};
    print qq{<input type="hidden" name="page" value="3">\n};

    print qq{<input type="hidden" name="date" value="$date">\n};
    print qq{<input type="hidden" name="author" value="$author">\n};
    
    print qq{<div class="la"><input class="btn-grn" type="submit" value="$lex{Save}"></div>\n};

    # Student Loop    
    foreach my $key ( sort keys %sort ) {
	my $studnum = $sort{$key};
	my %r = %{ $student{$studnum}};

	print qq{<table cellpadding="3" cellspacing="0" border="1" style="margin:1em;">\n};
	print qq{<tr><th colspan="2">$r{firstname} $r{lastname} ($studnum)</th></tr>\n};
	# print qq{<tr><th>$lex{Student}</th><th>$lex{Grade}</th><th>$lex{Score}</th></tr>\n};

	# Reselect Infraction, if desired
	print qq{<tr><td class="bra">Reason for Home Visit</td>\n};
	print qq{<td><select name="$studnum:reason"><option></option>\n};
	foreach my $reason ( @g_HomeVisitReason ) {
	    print qq{<option>$reason</option>\n};
	}
	print qq{</select></td></tr>\n};

	print qq{<tr><td class="bra">Description</td>};
	print qq{<td><textarea name="$studnum:description" rows="4" cols="80"></textarea></td></tr>\n};
	
	print qq{</table>\n};
	
    } # end of student loop

    
    print qq{<div class="la"><input  class="btn-grn" type="submit" value="$lex{Save}"></div>\n};
    print qq{</form></body></html>\n};

    exit;

} # end of enterStudentInfo


#---------------
sub writeEvent {
#---------------

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

     
    # Global values
    my $date = $arr{date};
    delete $arr{date};
    my $author = $arr{author};
    delete $arr{author};

    
    # Convert the data so can be entered into records
    my %data;  # data by student number (sn), then fieldname;
    foreach my $key ( sort keys %arr ) {
	my ($sn,$val) = split(':', $key);
	if ( $val ) {
	    $data{$sn}{$val} = $arr{$key};
	}
    }

    # Test Data
=head    
    print "Student Data<br>";
    foreach my $studnum ( sort keys %data ) {
	print qq{Student $studnum<br>\n};
	foreach my $field ( sort keys %{ $data{$studnum} } ) {
	    print "Field $field Val:$data{$studnum}{$field}<br>\n";
	}
    }
=cut

    my (%studentname, %sort);
    my $sth = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
    foreach my $studnum ( keys %data ) {
	$sth->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname) = $sth->fetchrow;

	$studentname{$studnum} = "<b>$lastname</b>, $firstname";
	$sort{"$lastname$firstname$studnum"} = $studnum;
    }	

    # Add Record
    my $sth = $dbh->prepare("insert into homevisit (author, date, studnum, reason, description )
      values(?,?,?,?,?)");
    
    # Loop by students (sorted)
    foreach my $key ( sort keys %sort ) {
	my $studnum = $sort{$key};
	my %r = %{ $data{$studnum}};
	
	# Insert Record
	$sth->execute( $author, $date, $studnum, $r{reason}, $r{description} );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

	print qq{<div>$studentname{$studnum} $lex{Added}</div>\n};
	
    } # students loop


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

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

} # end of writeEvent




#------------
sub checkDate {
#------------

    use Time::JulianDay;
    
    my $date = shift;

    my ($y,$m,$d) = split('-',$date);
    
    if ( not $d ) { return 255; }  # wrong format.
    if ( $m > 12 or $m < 1 ) { return 255; }
    if ( $d > 31 or $d < 1 ) { return 255; }

    my $datejd = julian_day( $y, $m, $d );

    my $startjd = julian_day( split('-', $schoolstart ));
    my $endjd = julian_day( split('-', $schoolend ));
    
#    print "DATE:$date - $datejd Start:$schoolstart - $startjd  End:$schoolend - $endjd<br>\n";

    if ( $datejd > $endjd  or $datejd < $startjd ) {
	return 1; # different code for date outside of current year;
    }
    
    return 0;

}
