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

#  This file is part of Open Admin for Schools.

my %lex = ('Main' => 'Main',
	   'GB Main' => 'GB Main',
	   'Clone/Duplicate Assessment Items' => 'Clone/Duplicate Assessment Items',
	   'Source Course' => 'Source Course',
	   'Destination Course' => 'Destination Course',
	   'Select these Subject-Sections' => 'Select these Subject-Sections',
	   'Name' => 'Name',
	   'Description' => 'Description',
	   'Group' => 'Group',
	   'Select' => 'Select',
	   'No Tests Found' => 'No Tests Found',
	   'Count' => 'Count',
	   'Add Selected Items' => 'Add Selected Items',
	   'Added Assessment Items...' => 'Added Assessment Items...',
	   'Maintenance Menu' => 'Maintenance Menu',
	   'No Userid Found' => 'No Userid Found',
	   'Error' => 'Error',
	   'Please Log In' => 'Please Log In',

	   );

my $self = 'testclone.pl';

use DBI;
use CGI;
use CGI::Session;
#use strict;

# 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}. " $@\n";
}

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

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


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

my $logged_in = $session->param(logged_in);
if ( not $logged_in){
    print $q->header( -charset, $charset );
    print qq{<html><body>\n};
    print qq{<h3>$lex{'Please Log In'}</h3>\n};
    print qq{</body></html>\n};
    exit;
}

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


# Print Page Header
my $title = $lex{'Clone/Duplicate Assessment Items'};
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;">\n};

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

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



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

if ( not $arr{page} ) {
    showStartPage();
    
} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    showTests();

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

#----------------
sub showStartPage {
#----------------
    
    # Get Teacher's courses
    my %courses;
    $sth = $dbh->prepare("select subjsec, description from subject 
			 where teacher = ? order by description");
    $sth->execute( $userid );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while (my ($subjsec, $desc) = $sth->fetchrow) {
	$courses{"$desc ($subjsec)"} = $subjsec;
    }

    # Start the form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<table cellpadding="4" cellspacing="0" border="1">\n};
    
    # Source Course
    print qq{<tr><td class="bra">$lex{'Source Course'}</td>};
    print qq{<td><select name="source"><option></option>\n};
    foreach my $course (sort keys %courses) {
	print qq{<option value="$courses{$course}">$course</option>\n};
    }
    print qq{</select></td></tr>\n};

    print qq{<tr><td class="bra">Check All Items</td>};
    print qq{<td><input type="checkbox" name="check" value="checked"></td></tr>\n};

    # Destination Courses
    print qq{<tr><td class="bra">$lex{'Destination Course'}</td>\n};
    print qq{<td><select name="destination"><option></option>\n};
    foreach my $course (sort keys %courses) {
	print qq{<option value="$courses{$course}">$course</option>};
    }
    print qq{\n</select></td></tr>\n};

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

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

}



#------------
sub showTests {
#------------

    # foreach my $key ( sort keys %arr) { print qq{K:$key V:$arr{$key}<br>\n}; }
    # passed: destination, source, check (ie. checkall)
    
    my $check = $arr{check};
    delete $arr{check}; # if present
    
    my $srcsubjsec = $arr{source};
    my $destsubjsec = $arr{destination};

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

    $sth->execute( $srcsubjsec );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my $srccrs = $sth->fetchrow;
    
    # Print start of form.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="hidden" name="subjsec" value="$destsubjsec">\n};

    # Table
    print qq{<table cellpadding="4" cellspacing="0" border="1">\n};
    print qq{<caption style="font-weight:bold;">Source - $srccrs ($srcsubjsec)</caption>\n};
    print qq{<tr><th>$lex{Name}</th><th>$lex{Description}</th><th>$lex{Group}</th>};
    print qq{<th>$lex{Select}</th></tr>\n};
    print qq{<tr><td colspan="5" class="cn" style="background-color:#EEE;">};
    print qq{<input type="submit" value="$lex{'Add Selected Items'} => $destcrs ($destsubjsec)">};
    print qq{</td></tr>\n};

    
    # Get the source items, display in form.
    my $sth = $dbh->prepare("select id, name, description, grp from gbtest
			    where subjsec = ? order by tdate, grp");
    $sth->execute( $srcsubjsec );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    my $srccount;
    while (my ($id, $name, $desc, $grp) = $sth->fetchrow) {
	print qq{<tr><td>$name</td><td>$desc</td>\n};
	print qq{<td><input type="text" name="group$id" size="8" value="$grp"></td>\n};
	print qq{<td><input type="checkbox" name="$id" value="1" $check></td></tr>\n};
	$srccount++;
    }
    if ( not $srccount ){
	print qq{<tr><td colspan="5">$lex{'No Tests Found'}</td></tr>\n};
	print qq{</table></body></html>\n};
	exit;
    }

    print qq{<tr><td colspan="5" class="cn" style="background-color:#EEE;">};
    print qq{<input type="submit" value="$lex{'Add Selected Items'} => $destcrs ($destsubjsec)">};
    print qq{</td></tr>\n};
    print qq{</table>\n};

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

    exit;
    
} # End of showTests


#------------
sub addTests {
#------------

    # foreach my $key ( sort keys %arr) { print qq{K:$key V:$arr{$key}<br>\n}; }
    # Passed: subjsec, numeric record id, then all group values (even if not selected)

    # This is the destination course...
    my $subjsec = $arr{subjsec};
    delete $arr{subjsec};

    # load the names of the destination course items to check for collisions.
    my $sth = $dbh->prepare("select name from gbtest where subjsec = ?");
    $sth->execute( $subjsec );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my %testname;
    while ( my $name = $sth->fetchrow) {
	$testname{$name} = 1;
    }
  
  
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<caption><b>$lex{'Added Assessment Items...'}</b></caption>\n};
    print qq{<tr><th>$lex{'Name'}</th><th>$lex{'Description'}</th></tr>\n};


    # Load the markscheme field for destination course, since we will update
    $sth1 = $dbh->prepare("select markscheme from subject where subjsec = ?");
    $sth1->execute( $subjsec );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my $markscheme = $sth1->fetchrow;

    # Setup groupweight to hold any new groups; write update after done loop below.
    my %groupweight;
    # add to the %group hash above; removing duplicates effectively.
    my @fields = split (/[\n|\r]/, $markscheme);
    foreach my $fld (@fields) { 
	if ( $fld ) {
	    my ($grp, $percent) = split '=', $fld;
	    $groupweight{$grp} = $percent;
	}
    }
    # end of markscheme load

    # Get source record
    my $sth = $dbh->prepare("select name, description, tdate, score, weight, grp 
			    from gbtest where id = ?");
    
    # Add Destination Record
    my $sth1 = $dbh->prepare("insert into gbtest (subjsec,name,description,tdate,score,weight,grp)
			     values(?,?,?,?,?,?,?)");

    
    # Insert clone tests/assessment items into the destination course
    foreach my $id ( keys %arr ) { 
	if ($id =~ m/^\d/) { # only digits at the start...
	    my $group = $arr{"group$id"};

	    # Get Source Record
	    $sth->execute($id);
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    my ($name, $desc, $tdate, $score, $weight, $grp) = $sth->fetchrow;

	    if ($grp ne $group) { # changed by user;
		# $group =~ s/\'+//g; # filter...
		$grp = $group;
	    }

	    # Allow group % value to remain the same
	    # $groupweight{$grp} = 0; # 

	    my $originalname = $name;
	    my $originaldesc = $desc;
	    if ($testname{$name}) { # name already exists for this...
		$name .= '0'; # add trailing zero.
	    }

	    # Now do the insertion
	    $sth1->execute($subjsec, $name, $desc, $tdate, $score, $weight,$grp);
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    print qq{<tr><td>$name</td><td>$desc</td></tr>\n};

	} # end of If the id.
    } # end of loop

    # Rewrite the markscheme for this subject.
    my $markscheme;
    foreach my $grp (sort keys %groupweight) {
	$markscheme .= "$grp=$groupweight{$grp}\n";
    }
    $sth = $dbh->prepare("update subject set markscheme = ? where subjsec = ?");
    $sth->execute( $markscheme, $subjsec );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    print qq{</table>\n};

    print qq{<p>[ <a href="$self">$lex{'Clone/Duplicate Assessment Items'}</a> |\n};
    print qq{<a href="mtcemenu.pl">$lex{'Maintenance Menu'}</a> ]</p>\n};
    print qq{</body></html>\n};

    exit;
    
}
