#!/usr/bin/perl
#  Copyright 2001-2024 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',
	   'Attendance' => 'Attendance',
	   'Student Not Found' => 'Student Not Found',
	   'Name' => 'Name',
	   'Date' => 'Date',
	   'Reasons' => 'Reasons',
	   'Period' => 'Period',
	   'Error' => 'Error',
	   'Course' => 'Course',
	   'Add' => 'Add',
	   'Student' => 'Student',
	   'Continue' => 'Continue',
	   'Save' => 'Save',
	   'Records Stored' => 'Records Stored',
	   'More' => 'More',
	   'Not Found' => 'Not Found',
	   'Skipping' => 'Skipping',
	   'Reason' => 'Reason',
	   
	   );

my $self = 'attAddStudent.pl';

use DBI;
use CGI;

eval require "../../etc/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;

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


my $title = "$lex{Add} $lex{Student} $lex{Course} $lex{Attendance}";

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} ) { # load javascript
    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="margin:1em;">\n};
print qq{[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{ <a href="$attpage">$lex{Attendance}</a> ]\n};

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


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

} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    selectStudent();
    
} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    enterAttendance();
    
} elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    writeAttendance();
}


#------------------
sub writeAttendance {
#------------------

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

    my $studnum = $arr{student};
    delete $arr{student};
    
    
    # Calculate DOW (Day of Week)
    my $jd = julian_day( split('-', $date));
    my $dow = day_of_week($jd);
    # used next line with @dowstd array (0 is Sunday).

    print qq{<div style="font-size:140%;">$lex{Attendance} $lex{Date} $date  <b>$dowstd[$dow]</b></div>\n};


    my $sth1 = $dbh->prepare("select lastname, firstname from student where studnum = ?");
    my $sth2 = $dbh->prepare("select description, teacher from subject where subjsec = ?");
    my $sth3 = $dbh->prepare("select count(*) from attend 
      where absdate = ? and studentid = ? and period = ?"); # attendance  duplicate check.
    my $sth6 = $dbh->prepare("select count(*) from tattend 
      where attdate = ? and subjects = ? and periods = ?"); # teacher attendance duplicate check.


    # Attendance Insert
    my $sth4 = $dbh->prepare("insert into attend (studentid, absdate, reason, period, subjsec)
      values ( ?,?,?,?,? )");
    # We're not doing lates here.
    
    my $first = 1;
	    

    my %subjperiods; # subjperiods{subjsec}{period}
    my %teacher; # teacher{subjsec} = $userid;

    foreach my $key ( sort keys %arr ) {

	if ( $arr{$key} ) {  # if we have a value

	    if ( $first ) {
		print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
		print qq{<tr><th>$lex{Student}</th><th>Course</th><th>$lex{Period}</th><th>};
		print qq{$lex{Reason}</th></tr>\n};
		$first = 0;
	    }

		
	    my ( $studnum, $subjsec, $period );
	    ( $studnum, $subjsec, $period ) = split(':', $key );
	    if ( not $period or $period =~ m/\D/ ) { next; } # skip if blank, or has text value

	    # Capture Teacher periods and subjects.
	    $subjperiods{$subjsec}{$period} = 1;

	    my $reason = $arr{$key};

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

	    # Get Course Description and Teacher
	    $sth2->execute( $subjsec );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ($description,$userid) = $sth2->fetchrow;
	    $teacher{$subjsec} = $userid;

	    if ( not $reason ) {
		print qq{<tr><td><b>$lastname</b>, $firstname ($studnum)</td><td>};
		print qq{$description ($subjsec)</td><td>$period</td><td colspan="2"};
		print qq{ style="color:red;">$lex{Attendance} $lex{Reasons} $lex{'Not Found'}};
		print qq{ $lex{'Skipping'}</td></tr>\n};
		next;
	    }


	    # Check for an existing record for this date, student, period.
	    $sth3->execute( $studnum, $date, $period );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my $count = $sth3->fetchrow;
	    if ( $count ) {
		print qq{<tr><td><b>$lastname</b>, $firstname ($studnum)</td><td>};
		print qq{$description ($subjsec)</td><td>$period</td><td colspan="2"};
		print qq{ style="color:red;">A Record already exists!\n};
		print qq{ $lex{'Skipping'}</td></tr>\n};
		next;
	    }

	    # if ( not $late ) { undef $late; }
		
	    # Insert the Record
	    $sth4->execute( $studnum, $date , $reason, $period, $subjsec );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

	    # Show Result
	    print qq{<tr><td><b>$lastname</b>, $firstname ($studnum)</td><td>};
	    print qq{$description ($subjsec)</td><td>$period</td><td>$reason</td></tr>\n};
	    
	} # end, if we have a value
    } # end of for loop for each key

    print qq{</table>\n};
    

    # Teacher Attendance Entry
    if ( %subjperiods ) { # Insert tattend record

	
	my $sth5 = $dbh->prepare("insert into tattend 
          ( userid, attdate, currdate, subjects, periods )
          values ( ?,?,now(),?,? )");
	
	print qq{<table cellpadding="3" cellspacing="0" border="1" style="margin:1em;">\n};
	print qq{<caption style="font-weight:bold;">Teacher Attendance Entry</caption>\n};
	print qq{<tr><th>Teacher</th><th>Date</th><th>Course</th><th>$lex{Period}</th></tr>\n};

	
	foreach my $subjsec ( keys %subjperiods ) {
	    foreach my $period ( keys %{ $subjperiods{$subjsec} } ) {
		# check for duplicates
		$sth6->execute( $date, $subjsec, $period);
		if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		my $count = $sth6->fetchrow;
		if ( $count ) { next; }
		
		# Insert record.
		my $userid = $teacher{$subjsec};
		$sth5->execute( $userid, $date, $subjsec, $period);
		if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		print qq{<tr><td>$userid</td><td>$date</td><td>$subjsec</td><td>Per $period</td></tr>\n};
	    } # period loop
	} # course loop
	    
    } # end of teacher attendance loop
    
    print qq{</table>\n}; # end of teacher attendance table

    print qq{<h1>$lex{'Records Stored'}</h1>\n};

    print qq{[ <a href="$homepage">$lex{Main}</a> |\n};
    print qq{ <a href="$attpage">$lex{Attendance}</a> |\n};
    print qq{ <a href="$self">$lex{More}</a> ]\n};

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

    exit;

} # end of writeAttendance



#------------------
sub enterAttendance {
#------------------

    use Time::JulianDay;

    # Needs findDayInCycle function
    eval require "../../lib/libschedule.pl";
    if ( $@ ) {
	print $lex{Error}. ": $@<br>\n";
	die $lex{Error}. ": $@\n";
    }
    
    
 #   print qq{<div>Enter Attendance</div>\n};
 #   foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    # Passed: date, studnum, reason.

    my $date = $arr{date};
    my $studnum = $arr{student};
    my $reason = $arr{reason};


    # get student record into %r hash.
    my $sth = $dbh->prepare("select * from student where studnum = ? ");
    $sth->execute($studnum);
    my $ref = $sth->fetchrow_hashref;
    my %r = %$ref;

    print qq{<h3 style="font-size:130%;margin:1em;">$r{firstname} $r{lastname} ($studnum)</h3>\n};


    my $jd = julian_day( split('-', $date));

    # Check for a weekend date
    my $dow = day_of_week($jd);
    if ( $dow == 0 or $dow == 6 ) {
	print qq{<h3>Weekend Date</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    # check for a closed date.
    my $sth = $dbh->prepare("select count(*) from dates where date = ?");
    $sth->execute($date);
    my $count = $sth->fetchrow;
    if ( $count ) {
	print qq{<h3>School is Closed</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    # get Term 
    my $grade = $r{grade};
    my $track = $g_MTrackTermType{$grade};
    my $term;
    
    my %temp = %{$g_MTrackTerm{$track}};
    foreach my $trm ( sort keys %temp ) {
	my $start = $temp{$trm}{start};
	my $end = $temp{$trm}{end};

	# Check using jd of current entry date
	my $startjd = julian_day( split('-', $start));
	my $endjd = julian_day( split('-', $end));
	if ( $startjd <= $jd and $endjd >= $jd ) { 
	    $term = $trm; # term is permanent value
	    last;
	}
    }


    
    # get Courses for this student, this term.
    my @courses;
    my $sth = $dbh->prepare("select subjcode from eval where studnum = ? and term = ?");
    $sth->execute($studnum, $term);
    while ( my $subjsec = $sth->fetchrow ) {
	push @courses, $subjsec;
    }

#    print qq{Courses:@courses<br>\n};

   
    # Get DayInCycle
    my $dayincycle = findDayInCycle( $date, $dbh );


    print qq{<div style="font-size:130%;padding:0 0 1em 1em;"><b>Attendance Date:</b> $date };
    print qq{<i>$dowstd[$dow]</i><br><b>Day In Cycle:</b> $dayincycle<br>\n};
    print qq{<b>Grade</b> $grade <b>Track</b> $track <b>Term</b> $term</div>\n};    
    
    # Get courses taught today along with their period.
    my %periods; # periods{#} = @subjsec;
    
    my $sth = $dbh->prepare("select period from schedat where subjsec = ? and day = ? and term = ?");
    foreach my $subjsec ( @courses ) {
	$sth->execute( $subjsec, $dayincycle, $term );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $period = $sth->fetchrow ) { # there may be more than one scheduled today.
	    if ( $period ) { # timetable today.
		push @{ $periods{$period} }, $subjsec;
	    }
	}
    }

    
    my $sth = $dbh->prepare("select description, teacher from subject where subjsec = ?");
    my $sth1 = $dbh->prepare("select lastname, firstname, sal from staff where userid = ?");
    
    my $first = 1;

    # Start Form
    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="hidden" name="page" value="3">\n};
    print qq{<input type="hidden" name="student" value="$studnum">\n};
    print qq{<input type="hidden" name="date" value="$date">\n};

    
    foreach my $period ( sort {$a <=> $b}  keys %periods ) {
	my @crs = @{ $periods{$period} };

#	print qq{Courses for period $period - @crs<br>\n};

	foreach my $crs ( @crs ) {
	
	    if ( $first ) {
		print qq{<table border="1" cellpadding="3" cellspacing="0">\n};
		print qq{<tr><th>Period</th><th>$lex{Course}</th><th>$lex{Reason}</th>\n};
		$first = 0;
	    }


	    print qq{<tr><td class="cn">$period</td>};
	
	    # Get Course/Teacher Information
	    $sth->execute( $crs );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my ($desc, $teacher) = $sth->fetchrow;

	    # Get Teacher Name
	    $sth1->execute( $teacher );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my ($ln,$fn,$sal) = $sth1->fetchrow;

	    
	    print qq{<td>$desc ($sal $fn $ln)</td>\n};
	    
	    print qq{<td><select name="$studnum:$crs:$period"><option>$reason</option>\n};
	    foreach my $rsn ( @attend ) {
		print qq{<option>$rsn</option>};
	    }
	    print qq{</select></td></tr>\n};
	}

    } # end of period loop

    
    if ($first ) {
	print qq{<h3>No Courses Found</h3>\n};
	
    } else {
	# Submit / Save
	print qq{<tr><td colspan="3" class="cn"><input type="submit" value="$lex{Save}"></td></tr>\n};
	print qq{</table>\n};
    }

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

    exit;
}

    

#----------------
sub selectStudent {
#----------------

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

    if ( not $student or not $date ) {
	print qq{<h3>Missing Values</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    
    
    my %names;
    my @students; # found student numbers.
    my $select;
    
    # Setup the Search
    if ($student =~ /\d+/) {  # we have a student number
	$select = qq{studnum = '$student'};
	
    } else { # we have words hopefully with a comma
	    
	($lastname,$firstname)  = split /\,/, $student;
	$firstname =~ s/^\s*//; # strip leading spaces
	$lastname =~ s/^\s*//;
	if ($lastname and $firstname){ # both entered.
	    $select = "lastname = '$lastname' and firstname = '$firstname'";
	} elsif ($lastname and not $firstname){ # only lastname (no comma)
	    if (length($lastname) == 2){ # search by initials: fi, li.
		$fi = substr($lastname,0,1); $li = substr($lastname,1,1);
		$select = "lastname like '$li%' and  firstname like '$fi%'";
	    } else {
		$select = "lastname = '$lastname'";
	    }
		
	} 
    }

#    print "SELECT:$select<br>\n";
	
    # Find the student numbers that match
    $sth = $dbh->prepare("select studnum, lastname, firstname, grade from student
     	 where $select order by lastname, firstname");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my ($studnum, $ln, $fn, $gr) = $sth->fetchrow ) {
	push @students, $studnum;
	$names{$studnum} = qq{<b>$ln</b>, $fn};
	$grade{$studnum} = $gr;
    }


    if ( not @students ) {
	    print qq{<h3>$lex{'Student Not Found'}</h3>\n};
	    print qq{</body></html>\n};
	    exit; 
    }


    # Loop through these students to select one.
    
    my $sth = $dbh->prepare("select lastname, firstname from student
          where studnum = ? order by lastname, firstname");

    my $first = 1;
    foreach my $studnum ( @students ) {
    
	if ( $first ) {
	    print qq{<table border="1" cellpadding="3" cellspacing="0">\n};
	    print qq{<caption>Please select a student</caption>\n};
	    print qq{<tr><th>$lex{Name}</th><th></th></tr>\n};
	    $first = 0;
	}
	
	print qq{<tr><td>$names{$studnum} ($studnum) Grade $grade{$studnum}</td>};
	
    	# Start Form
	print qq{<td>};
	print qq{<form action="$self" method="post" style="display:inline;">\n};
	print qq{<input type="hidden" name="page" value="2">\n};
	print qq{<input type="hidden" name="student" value="$studnum">\n};
	print qq{<input type="hidden" name="date" value="$date">\n};
	print qq{<input type="hidden" name="reason" value="$reason">\n};
	
	print qq{<input type="submit" value="$lex{Continue}">};
	print qq{</form></td></tr>\n};

    }
    if ( not $first ) {
	print qq{</table>\n};
    }		

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

    exit;


} # end of selectStudent



#----------------
sub showStartPage {
#----------------
    
	    
    # Start Form
    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="hidden" name="page" value="1">\n};

    # Start Table
    print qq{<table cellpadding="0" cellspacing="5" border="0">\n};

    # Student
    print qq{<tr><td class="bra">$lex{Student}</td>\n};
    print qq{<td> <input type="text" name="student" style="width:25ch;"></td></tr>\n};
    print qq{<tr><td></td><td class="la">Last,First/Last/Initials/Studnum</td></tr>\n};

    print qq{<tr><td colspan="2"></td></tr>\n};
    
    # Date 
    print qq{<tr><td class="bra">$lex{Date}</td>};
    print qq{<td> <input type="text" id="date" name="date" size="12">\n};
    print qq{<button type="reset" id="start_trigger">...</button></td></tr>\n};

    # Reason
    print qq{<tr><td class="bra">Default $lex{Reason}</td>};
    print qq{<td><select name="reason"><option value=""></option>\n};
    foreach my $rsn ( @attend ) {
	print qq{<option>$rsn</option>};
    }
    print qq{</select></td></tr>\n};
        
    
    print qq{<tr><td></td><td><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",
  ifFormat    : "%Y-%m-%d",
  button      : "start_trigger",
  singleClick : false,
  step : 1
  });
</script>
\n};

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

    exit;
}


