#!/usr/bin/perl
#  Copyright 2001-2024 Leslie Richardson

#  This file is part of Open Admin for Schools.


my %lex = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Add' => 'Add',
	   'Score' => 'Score',
	   'Student' => 'Student',
	   'Continue' => 'Continue',
	   'Save' => 'Save',
	   'Homeroom' => 'Homeroom',
	   'Select' => 'Select',
	   'Record' => 'Record',
	   
	   );

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

my $self = 'atpAdd.pl';

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";

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


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


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


# Page Header
my $title = qq{$lex{Add} Attitude/Academic $lex{Scores}};

print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$tchcss" type="text/css">\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};
    enterScores();

}  elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    writeScores();
} 


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

    # Get the homeroom students of this teacher
    
    # Get Homeroom
    my @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 $homeroom = $sth->fetchrow ) {
	push @homerooms, $homeroom;
    }
    @homerooms = sort {$a <=> $b} @homerooms;

    # Get Teacher Name
    my $sth = $dbh->prepare("select firstname, lastname from staff where userid = ?");
    $sth->execute($userid);
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my ($fn,$ln) = $sth->fetchrow;
    

    # Get the Year-Month for entry.
    my ($y,$m,$d) = split('-', $schoolstart); # loaded from admin.conf file
    my @yrmo; # ordered by year-month
    foreach my $m (9..12) { # do fall
	push @yrmo, qq{$y-$m};
    }
    $y++; # increment year
   
    foreach my $m (1..6) { # do fall
	push @yrmo, qq{$y-$m};
    }

    my $hrcount = scalar @homerooms;
    
#    print qq{<div>HR:@homerooms - $hrcount</div>\n};
#    print qq{<div>YR-MO:@yrmo</div>\n};
    
    # Start Form
    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" style="border:1px solid gray;padding:0.5em;">\n};
    print qq{<caption>Please Select Homeroom and Month</caption>\n};

    # Homeroom
    print qq{<tr><td class="bra">Homeroom</td>\n};
    print qq{<td><select name="homeroom">};
    foreach my $hr ( @homerooms ) {
	print qq{<option>$hr</option>\n};
    }
    print qq{</select></td></tr>\n};

    
    # Year-Month Select
    print qq{<tr><td class="bra" style="vertical-align:top;">Year-Month</td>};
    print qq{<td class="la">};
    foreach my $yrmo ( @yrmo ) {
	my ($y,$m) = split('-', $yrmo);
	print qq{<input type="radio" name="yrmo" value="$yrmo"> $month[$m], $y<br>\n};
    }

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

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

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

    exit;

} # end of showStartPage


#--------------
sub enterScores {
#--------------

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

    
    if ( not $arr{yrmo} or not $arr{homeroom} ) {
	print qq{<h3>$lex{Error}: Missing Value</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    my ($y,$m) = split('-', $arr{yrmo});
    
    # Show Choices
    print qq{<p>Scores for Homeroom <b>$arr{homeroom}</b> on <b>$month[$m]</b>, $y</p>\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="yrmo" value="$arr{yrmo}">\n};
    

    my $sth1 = $dbh->prepare("select score from atp_academic where studnum = ? and yrmo = ?");
    my $sth2 = $dbh->prepare("select score from atp_attitude where studnum = ? and yrmo = ?");
    

    my $first = 1;
    my $sth = $dbh->prepare("select * from student where homeroom = ? order by lastname, firstname");
    $sth->execute( $arr{homeroom} );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $sref = $sth->fetchrow_hashref ) {
	my %s = %$sref;
	my $studnum = $s{studnum};

	if ( $first ) {
	    print qq{<div class="la"><input class="btn-grn" type="submit" value="$lex{Save}"></div>\n};
	    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
	    print qq{<tr><th>$lex{Student}</th><th>Academic<br>$lex{Score}</th>};
	    print qq{<th>Attitude<br>$lex{Score}</th></tr>\n};
	    $first = 0;
	}

	print qq{<tr><td class="la"><b>$s{lastname}</b>, $s{firstname}</td>\n};

	# Get acadmic score if any
	$sth1->execute( $studnum, $arr{yrmo} );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $acScore = $sth1->fetchrow;

	# Get attitude score if any
	$sth2->execute( $studnum, $arr{yrmo} );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $atScore = $sth2->fetchrow;
	
	print qq{<td class="cn"><input type="text" style="width:6ch;" name="AC:$s{studnum}" };
	print qq{value="$acScore"></td>\n};
	
	print qq{<td class="cn"><input type="text" style="width:6ch;" name="AT:$s{studnum}" };
	print qq{value="$atScore"></td>\n};
	
	print qq{</tr>\n};
    }

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

    exit;

} # end of enterScores


#---------------
sub writeScores {
#---------------

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

    my $userid = $ENV{'REMOTE_USER'}; # needed to store;
    my $yrmo = $arr{yrmo};
    delete $arr{yrmo};
    
    my $sth1 = $dbh->prepare("select * from studentall where studnum = ?");

    foreach my $key ( keys %arr ) {

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

	my $table = 'atp_attitude';
	if ( $type eq 'AC' ) { # academic table
	    $table = 'atp_academic';
	}

	# Check for existing record for this student. If so, get record id
	my $sth = $dbh->prepare("select id from $table
           where studnum = ? and yrmo = ?");
	$sth->execute( $studnum, $yrmo );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $id = $sth->fetchrow;
	
#	print qq{ID:$id SN:$studnum Tbl:$table YRMO:$yrmo<br>\n};
	
	if ( $id ) { # just update.
	    my $sth1= $dbh->prepare("update $table set score = ? where id = ?");
	    $sth1->execute( $arr{$key}, $id ); # $arr{$key} is the value.
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    
	} else { # insert a new record
	    if ( not $arr{$key} ) { next; } # skip if no value
	    my $sth2 = $dbh->prepare("insert into $table (userid, studnum, yrmo, score)
               values ( ?, ?, ?, ? )");
	    $sth2->execute($userid, $studnum, $yrmo, $arr{$key});
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    
	}
    }

    print qq{<h3>Records Stored/Updated</h3>\n};
    print qq{</body></html>\n};

    exit;

} # end of writeScores
