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

#  This file is part of Open Admin for Schools.

my %lex = ('Weight by Item' => 'Weight by Item',
	   'GB Main' => 'GB Main',
	   'Weight by Group' => 'Weight by Group',
	   'Please Log In' => 'Please Log In',
	   'Name' => 'Name',
	   'Date' => 'Date',
	   'Group' => 'Group',
	   'Weight' => 'Weight',
	   'Update Weights' => 'Update Weights',
	   'Group Weight' => 'Group Weight',
	   'Percent' => 'Percent',
	   'C = custom weight set by direct edit' => 'C = custom weight set by direct edit',
	   'Error' => 'Error',

	   );

my $self = 'weightadj.pl';  # script to adjust test weighting

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

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

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 $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);
$dbh->{mysql_enable_utf8} = 1;

# 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);
if (not $logged_in){
    print $q->header( -charset, $charset );
    print qq{[ <a href="gbmain.pl">$lex{'GB Main'}</a> ]\n};
    print qq{<p>$lex{'Please Log In'}</p>\n};
    print qq{</body></html>\n};
    exit;
}

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

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


# 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 Totals for Weights and setup weight hash.
my $sth = $dbh->prepare("select id, weight from gbtest where subjsec = ? ");
$sth->execute( $subjsec );
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

my $totalweight;
while ( my ($id,$wt) = $sth->fetchrow ) {
    $totalweight += $wt;
    $weight{$id} = $wt;
}

# Write out updates
if ($arr{update}) {
    delete $arr{update};
    weightupdate();
}

# Now get group weights
my $sth = $dbh->prepare("select distinct grp, sum(weight) from gbtest 
			where subjsec = ? group by grp");
$sth->execute( $subjsec );
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
while (my ($grp, $wt) = $sth->fetchrow) {
    $grpweight{$grp} = $wt;
}

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

# select item values
$sth = $dbh->prepare("select id, name, description, tdate, weight, grp from gbtest 
		     where subjsec = ? and name != 'sortorder' order by grp,tdate");
$sth->execute( $subjsec );
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }


# Print Page head
my $title = qq{$lex{'Weight by Item'} - $course};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$tchcss" type="text/css">\n};
print qq{$chartype</head><body style="padding:1em;">\n};

print qq{[ <a href="gbmain.pl">$lex{'GB Main'}</a> | \n};
print qq{<a href="weightgrp.pl">$lex{'Weight by Group'}</a> ]\n};

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

print qq{<form action="$self" method="post">\n};
print qq{<input type="hidden" name="update" value="1">\n};
print qq{<table cellpadding="3" border="1" cellspacing="0">\n};

print qq{<tr><th>$lex{Name}</th><th>$lex{Date}</th>\n};
print qq{<th>$lex{Group}</th><th>$lex{Percent}<br>Within Grp</th>};
print qq{<th>$lex{Weight}<br>Within Grp</th></tr>\n};

my $grpcolor = -1;
my $group;
my $groupweight;

# Loop over all test items
while ( my ( $id, $name, $desc, $tdate, $weight, $grp ) = $sth->fetchrow ){

    if ($group ne $grp){ 
	$grpcolor++;
	if (5 == 4) { #$group){ # Avoids an empty row at top.
	    if (not $totalweight){ $grouppercent = "0.0%";} else {
		$grouppercent = round($groupweight / $totalweight * 100, 1);
	    }
	    print qq{<tr style="background-color:#EEE;color:black;">};
	    print qq{<td colspan="4">$lex{'Group Weight'} - <b>$group</b></td>};
	    print qq{<td>$groupweight ($grouppercent%)</td></tr>\n};
	}
	$groupweight = 0;
	$group = $grp;
    }
    
    $groupweight += $weight;
    my $percent;
    if ($grpweight{$grp}) {
	$percent =  round( $weight / $grpweight{$grp} * 100, 1);
    } else {
	$percent = '0.0';
    }

    print qq{<tr style="background-color: $g_color[$grpcolor];">\n};
    print qq{<td>$name ($desc)</td><td>$tdate</td><td>$grp</td><td>$percent%</td>\n};

    
    # print the select box or else an entry box.
    if ( $useMultipliers ) {  # we have a weight value

	my $key = $weightToMult{$weight}; # key will be a number 1-9; an index.
	print qq{<td><select name="$id">\n};
	if ( not defined $key ){  # no 1-9 value.
	    print qq{Key:$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.
	    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{</select></td></tr>\n};

    } else {
	print qq{<td><input type="text" name="$id" style="width:5ch;" };
	print qq{value="$weight"></td></tr>\n};
    }

} # End of test loop.

print qq{<tr style="background-color:#CCC;color:black;">};
print qq{<td class="cn" colspan="4"><input type="submit" value="$lex{'Update Weights'}">};
print qq{</td><td></td></tr>\n};
 
print qq{</table>\n};

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



#---------------
sub weightupdate {
#---------------

    # foreach my $key (keys %arr) { print qq{K: $key V: $arr{$key}<br>\n}; }
    # passed: record id => weight value;
    
    my $sth = $dbh->prepare("update gbtest set weight = ? where id = ?");
    
    foreach my $id (keys %arr) { # id is the record id of the test. 
	my $weight = $arr{$id};
	$sth->execute( $weight, $id );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    }

    # reset total
#    $totalweight = 0;
#    foreach my $wt (values %weight) { $totalweight += $wt;}

    # reload grpweight values
#    $sth = $dbh->prepare("select distinct grp, sum(weight) from gbtest 
#			 where subjsec = ? group by grp");
#    $sth->execute($subjsec);
#    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
#    while (my ($grp, $wt) = $sth->fetchrow) {
#	$grpweight{$grp} = $wt;
#    }

    print qq{<h3>Weights Updated!</h3>\n};
    
    return;
    
}
