#!/usr/bin/perl
#  Copyright 2001-2017 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',
	   'Report Card' => 'Report Card',
	   'Synchronize' => 'Synchronize',
	   'Synchronized' => 'Synchronized',
	   'Student' => 'Student',
	   'Course' => 'Course',
	   
	   );

my $self = 'syncmoodle.pl';

use CGI;
use DBI;

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

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



# Load Configuration Variables;
my $sth = $dbh->prepare("select id, datavalue from conf_system where filename = 'admin' or filename = 'repcard'");
$sth->execute;
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
while (	my ($id, $datavalue) = $sth->fetchrow ) {
    eval $datavalue;
    if ( $@ ) {
	print "$lex{Error}: $@<br>\n";
	die "$lex{Error}: $@\n";
    }
}


my $q = new CGI;
print $q->header( -charset, $charset ); 
my %arr = $q->Vars;


my $title = "$lex{Synchronize} Moodle";

print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{$chartype\n</head><body>\n};

print qq{[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{<a href="$reppage">$lex{'Report Card'}</a> ]\n};

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


# Find subjects to not skip over
my %subjects;
my $sth = $dbh->prepare("select distinct subjcode from eval
 where subjcode != '' and subjcode is not NULL"); 
$sth->execute;
while ( my $subjcode = $sth->fetchrow ) {

    # NOTE: $subjcode is actually subjsec (has both course code and section).
    
    # skip if member of %r_SupressSubject or AdditionalComments
    my ($tsubjcode, $dud) = split('-', $subjcode ); 
    if ( $r_SupressSubject{$tsubjcode} or $r_SupressSubject{$subjcode} or
	 $r_AdditionalComments{$tsubjcode} or $r_AdditionalComments{$subjcode} ) {
	next; 
    }

    $subjects{$subjcode} = 1;
}    


$sth = $dbh->prepare("select distinct studnum from eval where subjcode = ?"); 

my $sth1 = $dbh->prepare("select count(*) from ext_moodle where studnum = ? and subjsec = ?"); 
my $sth2 = $dbh->prepare("insert into ext_moodle (studnum, subjsec, subjcode, role)  values (?,?,?,'student')"); 
my $sth3 = $dbh->prepare("delete from ext_moodle where studnum = ? and subjsec = ?");
my $sth4 = $dbh->prepare("select * from ext_moodle where subjsec = ?");

my $sth5 = $dbh->prepare("select * from subject where subjsec = ?");


foreach my $subjsec ( keys %subjects ) { # loop over current course enrollments

    # Get Subject Description
    $sth5->execute( $subjsec );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my $ref = $sth5->fetchrow_hashref;
    my $desc = $ref->{description};
    
    my $first = 1;
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th style="font-weight:bold;">$desc ($subjsec)</th></tr>\n};
    # print qq{<tr><th>$lex{Student}</th></tr>\n};

    my ($subjcode, $section) = split('-', $subjsec);

    # Get Current Moodle student records for this course
    my %moodlekids;
    $sth4->execute( $subjsec );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( $ref = $sth4->fetchrow_hashref ) {
	$moodlekids{$ref->{studnum}} = $ref;
    }

    
    # Get OA Enrolled students
    my %enrolkids;
    $sth->execute( $subjsec );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr;}
    while ( my $studnum = $sth->fetchrow ) {
	$enrolkids{$studnum} = 1;
    }

    # Create Master List from both lists above.
    my %master = %enrolkids;
    foreach my $key ( keys %moodlekids ) { # loop since we don't want record in moodle kids.
	$master{$key} = 1;
    }


    # Loop through master list adding and removing records for this course.
    foreach my $studnum ( keys %master ) {

	if ( $moodlekids{$studnum} and $enrolkids{$studnum} ) { next; } # skip if in both hashes

	if ( $enrolkids{$studnum} and not exists $moodlekids{$studnum} ) { # add student to moodle table
	    
	    $first = 0;
	    $sth2->execute( $studnum, $subjsec, $subjcode );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    print qq{<tr><td>Insert: $studnum</td></tr>\n};
    
	} elsif ( not $enrolkids{$studnum} and exists $moodlekids{$studnum} ) { # remove student from moodle table
	    
	    $first = 0;
	    $sth3->execute( $studnum, $subjsec );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    print qq{<tr><td style="color:red;">Delete $studnum</td></tr>\n};

	}
    
    } # end of master list loop


    if ( $first ) {
	print qq{<tr><td style="color:green;">$lex{Synchronized}</td></tr>\n};
    } 

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

} # end of courses loop

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

exit;
