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

#  Description: Grade based subject enrollment. List all the students
#   for all the subjects in that grade. Deselect those that you don't
#   have in those subjects.

my %lex = ('Main' => 'Main',
	   'Student Group' => 'Student Group',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Continue' => 'Continue',
	   'Medical' => 'Medical',
	   'Add' => 'Add',
	   'Record' => 'Record',
	   'Checked' => 'Checked',
	   'Blank=All' => 'Blank=All',
	   'Separate with Spaces' => 'Separate with Spaces',
	   'Category' => 'Category',
	   'New' => 'New',
	   'Next Page' => 'Next Page',
	   'Description' => 'Description',
	   'Record(s) Stored' => 'Record(s) Stored',
	   'Contact' => 'Contact',
	   'Error' => 'Error',
	   'Checked' => 'Checked',
	   'Student Number' => 'Student Number',
	   'Results' => 'Results',
	   'Record Exists' => 'Record Exists',
	   'Skipping' => 'Skipping',
	   'Multiple Categories' => 'Multiple Categories',
	   'Blank' => 'Blank',
	   'Missing' => 'Missing',
	   'or' => 'or',
	   'Not Found' => 'Not Found',

	   );

my $self = 'medadd.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);
$dbh->{mysql_enable_utf8} = 1;

# Print Page Header
my $title = qq{$lex{Add} $lex{Medical} $lex{Record}};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{$chartype\n</head><body>\n};

print qq{[ <a href="$homepage">$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};
    multiAdd();

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


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

    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 class="bra">$lex{'Student Group'}</td>\n<td class="ln">};
    print qq{<select name="group"><option>$lex{Grade}</option><option>};
    print qq{$lex{Homeroom}</option><option>$lex{'Student Number'}</option></select>\n};
    print qq{<input type="input" name="groupid" size="12">\n};
    print qq{$lex{'Separate with Spaces'}, $lex{'Blank=All'}</td></tr>\n};

    # Select an Existing Category
    my @category;
    my $sth = $dbh->prepare("select distinct category from student_medical order by category");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my $ref = $sth->fetchall_arrayref;
    foreach my $val ( @$ref ) {
	if ( $val->[0] ) { push @category, $val->[0]; }
    }
    print qq{<tr><td class="bra">Default $lex{Category}</td>\n};
    print qq{<td><select name="category"><option></option>\n};
    foreach my $cat ( @category ) {
	print qq{<option>$cat</option>\n};
    }
    print qq{</select> $lex{Blank} = $lex{'Multiple Categories'}</td></tr>\n};

    # Add New Category
    print qq{<tr><td class="bra">$lex{New} $lex{Category}</td>\n};
    print qq{<td class="la">};
    print qq{<input type="text" name="newcategory" size="60" maxlength="255">\n};
    print qq{</td></tr>\n};

    # Add New Description
    print qq{<tr><td class="bra">Default $lex{Description}</td>\n};
    print qq{<td class="la">};
    print qq{<textarea name="description" cols="80" rows="4"></textarea>\n};
    print qq{</td></tr>\n};

    # Next Page Selection (studcheck)
    print qq{<tr><td class="bra">};
    print qq{$lex{'Next Page'} $lex{Checked}?</td>\n<td>};
    print qq{<input type="checkbox" name="studcheck" value="1"></td></tr>\n};

    # Submit
    print qq{<tr><td></td><td><input type="submit" value="$lex{Continue}">\n};
    print qq{</td></tr></table>\n</form></body></html>\n};

    exit;

}



#-----------
sub multiAdd { # add students
#-----------

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

    my $category = $arr{category};
    my $description = $arr{description};
    delete $arr{category};
    delete $arr{description};

    
    # Start Form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="3">\n};
    print qq{<p><input type="submit" value="$lex{Add} $lex{Record}"></p>\n};

    # SQL Setup.
    my $sth = $dbh->prepare("select distinct category from student_medical 
          where category is Not Null order by category");
    my $sth1 = $dbh->prepare("select * from student_medical where studnum = ?");
    my $sth2 = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");

    
    # Get Category
    my @category;
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $cat = $sth->fetchrow ) {
	push @category, $cat;
    }

    my (%sort, %name);
    foreach my $studnum ( keys %arr ) {
	# Get Name
	$sth2->execute($studnum);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname) = $sth2->fetchrow;
	$sort{"$lastname$firstname$studnum"} = $studnum;
	$name{$studnum} = qq{<b>$lastname</b>, $firstname};
    }
    

    foreach my $key ( sort keys %sort ) {
	my $studnum = $sort{$key};

	print qq{<table cellpadding="3" cellspacing="0" border="1" style="float:left;margin:0.5em;">\n};
	print qq{<caption style="font-size:150%;font-weight:bold;">$name{$studnum}</caption>\n};
	print qq{<tr><td>\n};
	
	# Get Any Existing Records.
	print qq{<div style="font-weight:bold;">Current Medical Records</div>\n};
	my $first = 1;

	$sth1->execute($studnum);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $ref = $sth1->fetchrow_hashref ) {
	    my %r = %$ref;
	    print qq{<div><b>$r{category}</b> - $r{description}</div>\n};
	    $first = 0;
	}
	if ( $first ) { print qq{<div>No Current Records</div>\n}; }
	print qq{<hr>\n};

	
	# Show Category
	print qq{<div style="font-weight:bold;">Medical Category</div>\n};
	print qq{<select name="C:$studnum"><option>$category</option>\n};
	foreach my $cat ( @category ) {
	    print qq{<option>$cat</option>};
	}
	print qq{</select>\n};

	# New Category
	print qq{ $lex{or} $lex{New} $lex{Category} };
	print qq{<input type="text" name="N:$studnum" size="20"><br>\n};

	# Get Description
	print qq{<div style="font-weight:bold;">Description</div>\n};
	print qq{<textarea rows="4" cols="80" name="D:$studnum">$description</textarea></td></tr>\n};

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

    } # end of student Loop

    print qq{<br clear="left"><input type="submit" value="$lex{Add} $lex{Record} ">\n};
    print qq{</form></body></html>\n};

    exit;

}



#----------------
sub selectStudents { # select students
#----------------

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

    # Display Current Category and Description, if any
    if ( $arr{category} ) {
	print qq{<table cellpadding="3" cellspacing="0" border="1" style="float:left;margin:1em;">\n};
	print qq{<tr class="ra"><td>$lex{Category}</td><td>$arr{category}</td></tr>\n};
	print qq{<tr><td class="ra">$lex{Description}</td><td>$arr{description}</td></tr>\n};
	print qq{</table><p></p><br clear="left">\n};
    } 

    my $studcheck;
    if ( $arr{studcheck} ) {
	$studcheck = qq{checked="checked"};
    }

    $table = 'studentall'; # student data source
    my $group;
    if ( $arr{group} eq $lex{Grade} ) {
	$group = 'grade';
    } elsif ( $arr{group} eq $lex{Homeroom} ) {
	$group = 'homeroom';
    } elsif (  $arr{group} eq $lex{'Student Number'} ) {
	$group = 'studnum';
    } else { $group = 'grade'; } # default to grade.

    my @groups = split /\s/, $arr{groupid};

    my $select;
    my $orderby;
    if ( not @groups ) { # select all students 
	my $sth = $dbh->prepare("select lastname, firstname, studnum, $group from $table
          order by lastname, firstname");
	$sth->execute;
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while ( my ( $lastname, $firstname, $studnum, $grp ) = $sth->fetchrow ) {
	    push @students, $studnum;
	    $lastname =~ s/\(/ /g;
	    $firstname =~ s/\(/ /g;
	    $students{$studnum} = "$lastname, $firstname ($grp)";
	}

	
    } elsif ( $group eq 'studnum' ) { # student numbers

	my $sth = $dbh->prepare("select lastname, firstname, grade from $table 
          where studnum = ?");
	foreach my $studnum ( @groups ) {

	    $sth->execute( $studnum );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my ( $lastname, $firstname, $grade ) = $sth->fetchrow;
	    push @students, $studnum;
	    $lastname =~ s/\(/ /g;
	    $firstname =~ s/\(/ /g;
	    $students{$studnum} = "$lastname, $firstname ($grade)";
	}


    } else { # we have groups of students 

	my $sth = $dbh->prepare("select lastname, firstname, studnum, $group from $table
          where $group = ? order by lastname, firstname");

	foreach my $grp ( @groups ) {
	    $sth->execute( $grp );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    while ( my ( $lastname, $firstname, $studnum, $grp ) = $sth->fetchrow ) {
		push @students, $studnum;
		$lastname =~ s/\(/ /g;
		$firstname =~ s/\(/ /g;
		$students{$studnum} = "$lastname, $firstname ($grp)";
	    }
	}
    }
    # All students now in @students and %students;


    # Form start
    print qq{<form action="$self" method="post">\n};

    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="hidden" name="description" value="$arr{description}">\n};
    print qq{<input type="hidden" name="category" value="$arr{category}">\n};

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

    
    # Print Student Information.
    print qq{<table cellpadding="3" cellspacing="0" border="1" style="float:left;">\n};


    my $studcount = 0;
    foreach my $studnum ( @students ){  #loop through students

	my ($dud, $grp) = split /\(/, $students{$studnum};
	chop $grp; # remove trailing parens.
	$oldgrp = $currgrp;
	$currgrp = $grp;
	if ( $currgrp ne $oldgrp ) { # switch colors;
	    if ( $class eq 'blue' ) { $class = 'gray'; } else { $class = 'blue'; }
	}

	print qq{<tr class="$class"><td>};
	print qq{<input type="checkbox" name="$studnum" };
	print qq{value="1" $studcheck>\n};
	print qq{ $students{$studnum}</td></tr>\n};
	$studcount++;
	if ( $studcount % 20 == 0 ) {
	    print qq{</table><table cellpadding="3" cellspacing="0" border="1" style="float:left;">\n};
	}

    }

    print qq{</table>\n};
    print qq{<br clear="left"><div><input type="submit" value="$lex{Continue}"></div>\n};

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

    exit;

}


#---------------
sub writeRecords {
#---------------

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

    
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th>$lex{Results}</th></tr>\n};
    
    # SQL Setup
    my $sth = $dbh->prepare("select count(*) from student_medical where studnum = ? and category = ?");
    my $sth1 = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
    my $sth2 = $dbh->prepare("insert into student_medical ( studnum, category, description ) values ( ?, ?, ? )");

    foreach my $key ( sort keys %arr ) {

	my ( $type, $studnum ) = split(':',$key);

	if ( $type eq 'D' or $type eq 'N' ) { next; } # we only want category

	my $dkey = "D:$studnum"; # decription
	my $nkey = "N:$studnum"; # new category
	my $ckey = $key;


	# Get Student Name
	$sth1->execute( $studnum );
	if ( $DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my ( $lastname, $firstname ) = $sth1->fetchrow;
	if ( not $lastname ) { 
	    $lastname = qq{<span style="color:red;">$lex{'Not Found'}</span>}; 
	}       

	# Set Category, Description
	if ( $arr{$nkey} ) { $arr{$ckey} = $arr{$nkey}; } # new cat replaces cat.

	my $category = $arr{$ckey};
	my $description = $arr{$dkey};
	
	if ( not $category ) { # an error
	    print qq{<tr><td>$lex{Missing} $lex{Category}: $firstname $lastname : };
	    print qq{$lex{Skipping}</td></tr>\n};
	    next;
	}

	# Check for duplicates, this student, this category
	$sth->execute( $studnum, $category );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my $catcount = $sth->fetchrow;
	if ( $catcount ) {
	    print qq{<tr><td>$lex{'Record Exists'}: $firstname $lastname : };
	    print qq{$category  $lex{Skipping}</td></tr>\n};
	    next;
	}

	# print line for this record.
	print qq{<tr><td><b>$lastname</b>, $firstname ($studnum) - $category</td></tr>\n};

	# Insert the record
	$sth2->execute( $studnum, $category, $description );
	if ( $DBI::errstr ){ print $DBI::errstr; last; }
	
    } # Next Student

    print qq{</table>\n};
    
    if ( not $DBI::errstr ) {
	print qq{<h3>$lex{'Record(s) Stored'}.</h3></p>\n};
    } else {
	print qq{<p>$lex{Error}. $lex{Contact}:\n};
	print qq{ $adminname <a href="mailto:$adminemail">$adminemail</a>\n};
	print qq{$lex{Error}: $DBI::errstr</p>\n};
    }

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

    exit;

} # End of writeRecords
