#!/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.

my %lex = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Student' => 'Student',
	   'Continue' => 'Continue',
	   'Record(s) Stored' => 'Record(s) Stored',
	   'Grade' => 'Grade',
	   'Select' => 'Select',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Select' => 'Select',
	   'Students' => 'Students',
	   'No Students Found' => 'No Students Found',
	   'Enrol' => 'Enrol',
	   'Group' => 'Group',
	   'Blank=All' => 'Blank=All',
	   'Students' => 'Students',
	   'Added' => 'Added',
	   'No User Id' => 'No User Id',
	   'No Password' => 'No Password',
	   'Please Log In' => 'Please Log In',
	   'Show Withdrawn' => 'Show Withdrawn',

	   );

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


my $self = 'lintStudAdd.pl';

my $q = new CGI;
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";


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

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

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

my ( $userid, $duration);
# 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}, $dbh);
    if ($error == -1){ print $q->header( -charset, $charset ); login($lex{'No User Id'}); }
    if ($error == -2){ print $q->header( -charset, $charset ); login($lex{'No Password'}); }

    $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{[ <a href="$tchpage">$lex{Main}</a> ]\n};
        print qq{<h3>$lex{'Please Log In'}</h3></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 );
# Session Setup End


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

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="$tchpage">$lex{Main}</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};
    addRecords();
}


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

    print qq{<form action="$self" method="post"> \n};
    print qq{<input type="hidden" name="page" value="1">\n};


    print qq{<table cellpadding="5" cellspacing="0" border="1">\n};
    print qq{<tr><th>Name</th><th>Start Date</th><th>End Date</th><th>Description</th></tr>\n};
    print qq{<tr style="background-color:#DDD;"><td class="bla" colspan="4">};
    print qq{$lex{Select} $lex{Group}</td></tr>\n};


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

    # my $sth = $dbh->prepare("select * from lint_program order by userid, startdate");
    my $sth = $dbh->prepare("select p.* from lint_program p, staff s where s.userid = p.userid  
        order by s.lastname, s.firstname, startdate desc");
    $sth->execute;
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $ref = $sth->fetchrow_hashref ) {

	# Get Names
	$sth1->execute( $ref->{userid} );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my ( $lastname, $firstname ) = $sth1->fetchrow;

	print qq{<tr><td><input type="radio" name="program" value="$ref->{id}">};
	print qq{$lastname, $firstname</td>\n};
	print qq{<td>$ref->{startdate}</td><td>$ref->{enddate}</td><td>$ref->{groupdesc}</td></tr>\n};

    }


    # Select Students
    print qq{<tr style="background-color:#DDD;"><td class="bla">$lex{Select} $lex{Students}</td>};
    print qq{<td class="la" colspan="3"><select name="grouptype">\n};
    print qq{<option value="grade">$lex{Grade}</option>\n};
    print qq{<option value="homeroom">$lex{Homeroom}</option>\n};
    print qq{</select> };
    print qq{<input type="text" name="groupvalue" style="width:2em;"> $lex{'Blank=All'}\n};
    print qq{ <input type="checkbox" name="showwithdrawn">$lex{'Show Withdrawn'}</td></tr>\n};

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

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

    exit;

} # end of showStartPage



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

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

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


    if ( not $arr{program} ) {
	print qq{<h3><span style="color:red;">Error<span> No Program Selected</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    

    print qq{<form action="$self" method="post"> \n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="hidden" name="program" value="$arr{program}">\n};

    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};


    # Get students
    my $select;
    if ( $arr{grouptype} eq 'grade' ) {
	$select = "where grade = ?";
    } elsif ($arr{grouptype} eq 'homeroom') { # homeroom
	$select = "where homeroom = ?";
    } # else all students.


    $arr{groupvalue} =~ s/\'|"//g; # strip quotes

    my $sth = $dbh->prepare("select lastname, firstname, studnum, grade from $table
      $select order by lastname, firstname");
    $sth->execute( $arr{groupvalue} );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

    my $first = 1;


    while ( my ($lastname, $firstname, $studnum, $grade )  = $sth->fetchrow ) {

	if ( $first ) {
	    print qq{<tr><th>$lex{Select} $lex{Student}</th></tr>\n};
	    $first = 0;
	}

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

    }

    if ( $first ) {
	print qq{</table></form><h1>$lex{'No Students Found'}</h1>\n};
	print qq{</body></html>\n};
	exit;
    }


    # Continue to next page
    print qq{<tr><td class="la"><input type="submit" value="$lex{Continue}">};
    print qq{</td></tr>\n};

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

    exit;

} # end of selectStudents


#---------------
sub addRecords {
#---------------

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

    my $progid  = $arr{program};
    delete $arr{program};
    if ( not $progid ) {
	print qq{<h3>Error: No program found!</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    my $sth = $dbh->prepare("insert into lint_student ( studnum, progid )
      values ( ?,?)"); 

    my $sth1 = $dbh->prepare("select lastname, firstname, grade
     from student where studnum = ?");


    my $first = 1;

    foreach my $studnum ( keys %arr ) {

	# Get student 
	$sth1->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname, $grade) = $sth1->fetchrow;

	# Write the test record 
 	$sth->execute( $studnum, $progid );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

	if ( $first ) {
	    print qq{<div>$lex{Students} $lex{Added}:</div>\n};
	    $first = 0;
	}

	print qq{<div><b>$lastname</b>, $firstname ($studnum)</div>\n};

    }
    
    if ( $first ) { 
	print qq{<h3>Error: No records stored</h3>\n}; 

    } else { # we added
	print qq{<h3>$lex{'Record(s) Stored'}</h3>\n};
    }

    print qq{<p>[ <a href="$self">$title</a> |\n};
    print qq{<a href="$tchpage">$lex{Main}</a> ]</p></body></html>\n};

    exit;

}
