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

#  This file is part of Open Admin for Schools.

# Edit a test/assessment item record.

my %lex = ('Edit Assessment Item' => 'Edit Assessment Item',
	   'Main' => 'Main',
	   'GB Main' => 'GB Main',
	   'Your item MUST have a group and a score!' => 
	     'Your item MUST have a group and a score!',
	   'There was an error storing your data' => 'There was an error storing your data',
	   'or New Group' => 'or New Group',
	   'Update Assessment Item' => 'Update Assessment Item',
	   'The test/assessment is now stored' => 'The test/assessment is now stored',
	   'Your new group was added' => 'Your new group was added',
	   'Name' => 'Name',
	   'Description' => 'Description',
	   'Date' => 'Date',
	   'Max Raw Score' => 'Max Raw Score',
	   'Weight' => 'Weight',
	   'Group' => 'Group',
	   'The default weight is' => 'The default weight is',
	   'Error' => 'Error',
	   'Please Log In' => 'Please Log In',
	   'must be a number' => 'must be a number',

	   );

use DBI;
use CGI;
use CGI::Session;
use Number::Format qw{round};

my $self = 'gbTestEdit.pl';

# Set the current date
my @tim = localtime(time);
my $year = @tim[5] + 1900;
my $month = @tim[4] + 1;
my $day = @tim[3];
my $currdate = "$year-$month-$day"; 

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

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

my $q = new CGI;

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


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

my $logged_in = $session->param(logged_in);

my $subjsec = $session->param('subjsec');

print $q->header( -charset, $charset );
my %arr = $q->Vars;
my $testid = $arr{id};

my $title = $lex{'Edit Assessment Item'};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$tchcss" type="text/css">$chartype\n};
print qq{</head><body>\n};
print qq{[ <a href="$tchpage">$lex{Main}</a> |\n};
print qq{<a href="gbmain.pl">$lex{'GB Main'}</a> ]\n};

if ( not $logged_in ){
    print qq{<p>$lex{'Please Log In'}</p>\n};
    print qq{</body></html>\n};
    exit;
}

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


# Load the different groups, using %group hash
my %group;
$sth = $dbh->prepare("select distinct grp from gbtest where grp != '' and 
		     grp is not null and subjsec = ?");
$sth->execute($subjsec);
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
while (my $grp = $sth->fetchrow){
    if ($grp){ $group{$grp} = 1;}
}


# Load the markscheme field from the subject
$sth = $dbh->prepare("select markscheme from subject where subjsec = ?");
$sth->execute($subjsec);
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
my $markscheme = $sth->fetchrow;
my @fields = split (/[\n|\r]/, $markscheme);
foreach my $fld (@fields) { 
    if ($fld) {
	my ($grp, $percent) = split /=/, $fld;
	$group{$grp} = $percent;
    }
}


$sth = $dbh->prepare("select description from subject where subjsec = ?");
$sth->execute( $subjsec );
if ($DBI::errstr){ print $DBI::errstr; exit; }
my $subject = $sth->fetchrow;

print qq{<h1>$title - $subject ($subjsec)</h1>\n};

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

} elsif ( $arr{page} == 1 and $arr{multiplier} eq 'Custom' ) {
    addCustomWeight();
    
} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    updateRecord();
}


#------------------
sub addCustomWeight {
#------------------

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

    # form.
    print qq{<form action="$self" method="post">\n};
#    print qq{<input type="hidden" name="id" value="$testid">\n};
#    print qq{<input type="hidden" name="subjsec" value="$subjsec">\n};
#    print qq{<input type="hidden" name="page" value="1">\n};
    
    foreach my $key ( sort keys %arr ) {
	if ( $key eq 'multiplier' ) { next; } # skip multiplier; not passed on.
	print qq{<input type="hidden" name="$key" value="$arr{$key}">\n};
    }

    print qq{<div>Test Weight <input type="text" style="width:5ch;" name="weight" };
    print qq{value="$defaultItemWeight"> $defaultItemWeight = 1x weight</div>\n};

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

}



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

    # build a hash to map a weight number -> multiplier value (ie. 500 -> 5, 750 -> 6)
    my %weightToMult;
    foreach my $key (keys %wtmult) { # %wtmult from gbook.conf file
	my $value = round( $wtmult{$key} * $defaultItemWeight, 0);
	$weightToMult{$value} = $key;
    }
    #foreach my $key (keys %weightToMult) { print "K:$key V:$weightToMult{$key}<br>\n"; }

    # Get the test info....
    my $sth = $dbh->prepare("select subjsec, name, description, tdate, score, weight, grp 
			    from gbtest where id = ?");
    $sth->execute( $testid );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my ( $subjsec, $name, $desc, $tdate, $score, $weight, $grp) = $sth->fetchrow;

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

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

    # Name
    print qq{<tr><td class="bra">$lex{Name}</td>\n};
    print qq{<td><input type="text" name="name" };
    print qq{style="width:12ch;" maxlength="32" value="$name">\n};
    print qq{ ex.Asn11, T13,HW23;keep short,max 6 characters;letters and numbers only</td></tr>\n};

    # Description
    print qq{<tr><td class="bra">$lex{Description}</td>\n}; 
    print qq{<td><input type="text" name="description" style="width:50ch;" maxlength="255" };
    print qq{value="$desc">};
    print qq{</td></tr>\n};


    # Date Entry
    print qq{<tr><td class="bra">$lex{Date}</td>\n};
    print qq{<td><input type="text" style="width:10ch;" name="tdate" id="date" value="$tdate">};
    print qq{<button type="reset" id="start_trigger">...</button>\n};    


    # Max Raw Score
    print qq{<tr><td class="bra">$lex{'Max Raw Score'}</td>\n};
    print qq{<td><input type="text" name="score" style="width:4ch;" maxlength="8" value="$score">};
    print qq{ Use Integers to keep score entry simple; Use natural score total, not 100</td></tr>\n};


    # Weight
    print qq{<tr><td class="bra">$lex{Weight}</td>\n};;
    if ( $useMultipliers ) { # found in etc/gbook.conf; we have a $weight value

	my $key = $weightToMult{$weight}; # key will be a number 1-9; an index.
	print qq{<td><select name="multiplier">\n};

	if ( not defined $key ){  # no 1-9 value.
	    #print qq{K:$key W:$weight<br>\n};
	    my $mult = round( $weight / $defaultItemWeight, 2); # gives us a 1.09, etc. type
	    print qq{<option value="$weight">Custom ($mult\X)</option>\n};
	}

	foreach my $idx (sort {$a <=> $b} keys %wtmult) { # 5 => 1, 6 => 1.5, etc.
	    my $mult = $wtmult{$idx}; # mult is 0.5,1,1.5,etc. idx is a 1 to 9 number.
	    my $wt = round($mult * $defaultItemWeight,0); # since $weight is defined
	    $mult = round($mult,3); # more reasonable display for 0.33333, etc.
	    # rounding needed for comparison below ($wt == $weight)
	    # print qq{<div>WT:$wt WEIGHT:$weight</div>\n};
	    
	    print qq{<option value="$wt"};
	    if ($wt == $weight) { print ' selected'; }
	    print qq{>$mult\X</option>\n};
	}
	print qq{<option>Custom</option></select> Normally leave at 1x (1 times) weight</td></tr>\n};

    } else {
	print qq{<td><input type="text" name="weight" style="width:4ch;" value="$weight">};
	print qq{<i>$lex{'The default weight is'} $defaultItemWeight</i>};
	print qq{</td></tr>\n};
    }

    # Group
    print qq{<tr><td class="bra">$lex{Group}</td>};
    print qq{<td><select name="grp"><option>$grp</option>\n};
    foreach my $gp (sort keys %group) {
	print qq{<option>$gp</option>\n};
    }
    print qq{</select> $lex{'or New Group'} };
    print qq{ <input type="text" name="newgrp" size="8">};
    print qq{ (ex Term1,Exam1,T1HW,T1Test)</td></tr>\n};

    # Update
    print qq{<tr><td></td><td class="la"><input type="submit" };
    print qq{value="$lex{'Update Assessment Item'}"></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
    }) };
    print qq{</script>\n};

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

    exit;

}
    



#---------------
sub updateRecord { # write the updated record.
#---------------

    # print qq{<div>SUB updateRecord</div>\n};
    # foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
     
    my $id = $arr{id};
    delete $arr{id};
    
    if ($arr{newgrp}){ # Update the grouping
	$newgroupflag = 1;
	$arr{grp} = $arr{newgrp};
	delete $arr{newgrp};
    }

    # weight or multiplier both will be raw values (ie. 500, etc)
    if ( $arr{multiplier} and not $arr{weight} ) {
	$arr{weight} = $arr{multiplier};
	delete $arr{multiplier};
    }
    # $weight is now set...

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

    # Remove any double quotes replacing with single quote, since they can cause problems.
    my $val = $arr{description};
    $val =~ s/"/'/g;
    $arr{description} = $val;
    
    
    if ( not $arr{grp} or not $arr{score} ) {
	print qq{<h1>$lex{'Your item MUST have a group and a score!'}\n};
	print qq{</h1></body></html>\n};
	exit;
    }

    # Check that Max Score is a number, not text.
    if ( $arr{score} =~ m/\D/ ) { 
	print qq{<p>$lex{'Max Raw Score'} $lex{'must be a number'}</p>\n};
	print qq{</body></html>\n};
	exit;
    }

    my $sth = $dbh->prepare("update gbtest set name = ?, description = ?, 
			    tdate = ?, score = ?, weight = ?, grp = ? where id = ? ");

    
    $sth->execute($arr{name}, $arr{description}, $arr{tdate}, $arr{score},
		  $arr{weight}, $arr{grp}, $id);

    if ( not $DBI::errstr ) {
	print qq{<h1>$lex{'The test/assessment is now stored'}</h1>\n};

	if ($newgroupflag){ 
	    print qq{<div>$lex{'Your new group was added'}</div>\n};
	}

    } else { 
	print qq{<h3>$lex{'There was an error storing your data'} };
	print qq{ $DBI::errstr</h3>\n};
    }

    print qq{<p>[ <a href="gbmain.pl">$lex{'GB Main'}</a> ]</p>\n};
    print qq{</body></html>\n};

    exit;

} # End of updateRecs
