#!/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',
	   'Edit' => 'Edit',
	   'Name' => 'Name',
	   'Update' => 'Update',
	   'Score' => 'Score',
	   'No User Id' => 'No User Id',
	   'No Password' => 'No Password',
	   'Please Log In' => 'Please Log In',
	   'Record(s) Updated' => 'Record(s) Updated',
	   'Edit not allowed' => 'Edit not allowed',
	   'Scores' => 'Scores',
	   'Date' => 'Date',
	   'Close' => 'Close',
	   'Common Math Assessment' => 'Common Math Assessment',
	   'Outcome' => 'Outcome',
	   'Test' => 'Test',

	   );

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


my $self = 'cmaEdit.pl';


# NOW in config file math.conf
# my @phases = qw(Emergent Matching Quantifying Partitioning Factoring Operating);
# my @seasons = qw(Sep-2012 Nov-2012 Apr-2013 Sep-2013 Nov-2013 Apr-2014 Sep-2014 Nov-2014);

# Configuration Settings -----------------------
my $allow_author = 1; # allow author to edit
my $allow_cma = 1; # allow user with math access code to edit
#-----------------------------------------------

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

my @time = localtime(time);
my $year = $time[5] + 1900;
my $month = $time[4] + 1;
my $currdate = "$year-$month-$time[3]";


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

# Session Setup Here
my $session = new CGI::Session("driver:mysql;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}, $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 $lex{'Please Log In'}. "</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


# Check for access code
my $sth = $dbh->prepare("select field_value from staff_multi 
  where field_name = 'access' and userid = ?");
$sth->execute( $userid );
if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

my $accesscma;
while ( my $val = $sth->fetchrow ) {
    if ( uc $val eq 'CMA' ) { $accesscma = 1; }
    # print qq{VAL:$val ACCESS:$accesscma<br>\n};
}



# Page Header
my $title = "$lex{Edit} $lex{'Common Math Assessment'} $lex{Scores}";
print qq{$doctype\n<html><head><title>$title</title>};
print qq{<link rel="stylesheet" href="$tchcss" type="text/css">\n};

if ( not $arr{page} ) { # date widget
    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} ) {
    editTests();

} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    writeTest();
}


#-------------
sub editTests {
#-------------

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

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

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

    my $datecounter = 1;

    foreach my $id ( keys %arr ) {

	# Get Reading Test fields.
	my $sth = $dbh->prepare("select * from mathca_scores where id = ?");
	$sth->execute( $id );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;
	my %r = %$ref;
	
	my $studnum = $ref->{studnum};

	# Access Controls
	my $failflag;
	if ( not $allow_author and not $allow_cma ) { $failflag = 1; } # nobody edits
	elsif ( $allow_author and $ref->{tauthor} ne $userid ) { $failflag = 1; } # not author
	
	if ( $allow_cma and $accesscma ) { $failflag = 0; }
	# allow override of author failure for catalyst.

	if ( $failflag ) {
	    print qq{<h3>$lex{'Edit not allowed'}</h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}

	# Get Student Name, Grade
	my $sth1 = $dbh->prepare("select lastname, firstname, grade from student where studnum = ?");
	$sth1->execute( $studnum );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ( $lastname, $firstname, $grade ) = $sth1->fetchrow;
	# print qq{Name: $lastname $firstname<br>\n};


	# Get Outcomes for this Grade
	my %outcomes;
	my $sth = $dbh->prepare("select oid, odesc from mathca_outcomes where grade = ?");
	$sth->execute( $grade );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while ( my ($oid, $odesc ) = $sth->fetchrow ) {
	    $outcomes{$oid} = $odesc;
	}


	# Print Table Header and Heading values
	print qq{<table cellpadding="3" cellspacing="0" border="0">\n};
	print qq{<tr><td colspan="2" class="la">\n};

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

	# Test Date
	print qq{<tr><td class="bra">$lex{Test} $lex{Date}</td>};
	print qq{<td><input type="text" name="$id:tdate" id="date$datecounter" };
	print qq{size="10" value="$r{tdate}">\n};
	print qq{<button type="reset" id="start_trigger$datecounter">...</button>\n};
	print qq{</td></tr>\n};
	$datecounter++;

	# School Year
	print qq{<tr><td class="bra">School Year</td>};
	print qq{<td><input type="text" name="$id:schoolyear" };
	print qq{style="width:6ch;" value="$r{schoolyear}">\n};
	print qq{ (ie 2021-2022 = 2022)</td></tr>\n};

	
	# Pretest or Posttest
	print qq{<tr><td class="bra">Pretest or Posttest</td><td class="la">};
	print qq{<select name="$id:prepost"><option>$r{prepost}</option>\n};
	print qq{<option value="pretest">Pre-Test</option>};
	print qq{<option value="posttest">Post-Test</option>};
	print qq{</select></td></tr>\n};

	# Outcome
	print qq{<tr><td class="bra">$lex{Outcome}</td>};
	print qq{<td><select name="$id:outcome">};
	print qq{<option value="$r{outcome}">$r{outcome} $outcomes{"$r{outcome}"}</option>\n};
	foreach my $oid ( sort keys %outcomes ) {
	    print qq{<option value="$oid">$oid $outcomes{$oid}</option>};
	}
	print qq{</td></tr>\n};

	# Score
	print qq{<tr><td class="bra">$lex{Score}</td>};
	print qq{<td class="la">};
	foreach my $score ( 1, 2, 3, 4, 'N/A' ) {
	    my $checked;
	    if ( $score eq $r{score} ) { $checked = qq{checked="checked"} }
	    print qq{<input type="radio" name="$id:score" value="$score" $checked>};
	    print qq{$score \n};
	}
	print qq{</td></tr>\n};

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


    } # record loop end


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

    print qq{<script type="text/javascript">\n};

    foreach my $idx (1 .. ($datecounter - 1)) {

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

    }

    print qq{</script>\n};

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

    exit;

}


#--------------
sub writeTest {
#--------------

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

    foreach my $key ( sort keys %arr ) {

	my ($id, $field ) = split(':', $key );

	if ( $field eq 'tdate' ) { # check validity
	    my $err = checkDate( $arr{$key} );
	    if ( $err == 1 ) {
		print qq{<h4>$lex{Error}: Date Outside School Year: $arr{$key}. Skipping</h4>\n};
		next;
	
	    } elsif ( $err ) {
		print qq{<h4>Date Error: $err. Skipping</h4>\n};
		next;
	    }
	}

	
	my $sth = $dbh->prepare("update mathca_scores set $field = ? where id = ?");  
	$sth->execute( $arr{$key}, $id );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	# print qq{Field:$field Id:$id Value:$arr{$key}<br>\n};

    }


    print qq{<h1>$lex{'Record(s) Updated'}</h1>\n};
    print qq{</body></html>\n};

    exit;

}



#------------
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 qq{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;

}
