/**
 * Processes all the entries imported from custom report in the datbase
 * updating skillsoft_au_track and gradebook
 *
 * @param $trace false default, flag to indicate if mtrace messages should be sent
 * @param string $prefix - The string to prefix all mtrace reports with
 * @return unknown_type
 */
function skillsoft_process_received_customreport($handle, $trace = false, $prefix = '    ')
{
    global $CFG, $DB;
    set_time_limit(0);
    $starttime = microtime(true);
    if ($trace) {
        mtrace($prefix . get_string('skillsoft_customreport_process_start', 'skillsoft'));
    }
    //Get a count of records and process in batches
    $conditions = array('userid' => '0');
    $countofunprocessed = $DB->count_records('skillsoft_report_results', $conditions);
    if ($trace) {
        mtrace($prefix . get_string('skillsoft_customreport_process_totalrecords', 'skillsoft', $countofunprocessed));
    }
    //	$limitfrom=0;
    //	$limitnum=1000;
    //
    //	do {
    //		if ($trace) {
    //			mtrace($prefix.get_string('skillsoft_customreport_process_batch','skillsoft',$limitfrom));
    //		}
    //		if ($unmatchedreportresults = $DB->get_records_select('skillsoft_report_results','userid=0',null,'id ASC','*',$limitfrom,$limitnum)) {
    //			foreach ($unmatchedreportresults as $reportresults) {
    //				$reportresults->userid = skillsoft_getusername_from_loginname($reportresults->loginname);
    //				if ($reportresults->userid != 0)
    //				{
    //					$id = $DB->update_record('skillsoft_report_results',$reportresults);
    //				}
    //			}
    //		}
    //		$limitfrom += 1000;
    //	} while (($unmatchedreportresults != false) && ($limitfrom < $countofunprocessed));
    //Perform the match of userid using SQL alone
    $sql = "UPDATE {skillsoft_report_results} ";
    $sql .= "SET userid = ";
    $sql .= "(SELECT id FROM {user} WHERE ";
    $sql .= $DB->sql_concat("'" . $CFG->skillsoft_accountprefix . "'", "{user}." . $CFG->skillsoft_useridentifier);
    $sql .= " = {skillsoft_report_results}.loginname) ";
    $sql .= "WHERE EXISTS ";
    $sql .= "(SELECT id FROM {user} WHERE ";
    $sql .= $DB->sql_concat("'" . $CFG->skillsoft_accountprefix . "'", "{user}." . $CFG->skillsoft_useridentifier);
    $sql .= " = {skillsoft_report_results}.loginname) ";
    $DB->execute($sql);
    //Select all the unprocessed Custom Report Results's
    //We do it this way so that if we create a new Moodle SkillSoft activity for an asset we
    //have TDR's for already we can "catch up"
    $sql = "SELECT t.id as id, s.id AS skillsoftid, u.id AS userid, t.firstaccessdate, t.lastaccessdate, t.completeddate, t.firstscore, t.currentscore, t.bestscore, t.lessonstatus, t.duration, t.accesscount, t.processed, t.attempt ";
    $sql .= "FROM {skillsoft_report_results} t ";
    $sql .= "INNER JOIN {user} u ON u.id = t.userid ";
    $sql .= "INNER JOIN {skillsoft} s ON t.assetid = s.assetid ";
    $sql .= "WHERE t.processed=0 ";
    $sql .= "ORDER BY s.id,u.id,t.firstaccessdate";
    $lastreportresults = new stdClass();
    $lastreportresults->skillsoftid = NULL;
    $lastreportresults->userid = NULL;
    $rs = $DB->get_recordset_sql($sql);
    if ($rs->valid()) {
        foreach ($rs as $reportresults) {
            if ($trace) {
                mtrace($prefix . $prefix . get_string('skillsoft_customreport_process_retrievedresults', 'skillsoft', $reportresults));
            }
            if ($reportresults->attempt != 0) {
                $attempt = $reportresults->attempt;
            } else {
                $attempt = skillsoft_get_last_attempt($reportresults->skillsoftid, $reportresults->userid);
                //Check if "last attempt" is first attempt if not increment
                if ($attempt == 0) {
                    $attempt = 1;
                } else {
                    $attempt = $attempt + 1;
                }
            }
            if ($reportresults->skillsoftid != $lastreportresults->skillsoftid || $reportresults->userid != $lastreportresults->userid) {
                $skillsoft = $DB->get_record('skillsoft', array('id' => $reportresults->skillsoftid));
                $user = $DB->get_record('user', array('id' => $reportresults->userid));
                $handler = new aicchandler($user, $skillsoft, $attempt, $CFG->skillsoft_strictaiccstudentid);
            }
            //Process the ReportResults as AICC Data
            if ($skillsoft->completable) {
                $handler->processreportresults($reportresults, $attempt);
            } else {
                //Only update attempt 1
                $handler->processreportresults($reportresults, 1);
            }
            $reportresults->processed = 1;
            $reportresults->attempt = $attempt;
            $lastreportresults = $reportresults;
            $gradeupdate = skillsoft_update_grades($skillsoft, $user->id);
            $id = $DB->update_record('skillsoft_report_results', $reportresults);
        }
    }
    $rs->close();
    //Update the skillsoft_report_track
    skillsoft_update_customreport_processed($handle);
    $endtime = microtime(true);
    $duration = $endtime - $starttime;
    if ($trace) {
        mtrace($prefix . get_string('skillsoft_customreport_process_end', 'skillsoft') . ' (took ' . $duration . ' seconds)');
    }
}
foreach ($_POST as $key => $value) {
    $tempkey = strtolower($key);
    $_POST[$tempkey] = $value;
}
$command = required_param('command', PARAM_ALPHA);
$sessionid = required_param('session_id', PARAM_ALPHANUM);
$aiccdata = optional_param('aicc_data', '', PARAM_RAW);
$version = optional_param('version', '', PARAM_RAW);
$attempt = optional_param('attempt', '1', PARAM_INT);
if (!empty($command) && ($skillsoftsession = skillsoft_check_sessionid($sessionid))) {
    $skillsoftid = $skillsoftsession->skillsoftid;
    $userid = $skillsoftsession->userid;
    //$attempt = 1;
    if ($skillsoft = $DB->get_record('skillsoft', array('id' => $skillsoftid))) {
        $user = $DB->get_record('user', array('id' => $userid));
        $handler = new aicchandler($user, $skillsoft, $attempt, $CFG->skillsoft_strictaiccstudentid);
        switch (strtolower($command)) {
            case 'getparam':
                $handler->getparam();
                break;
            case 'putparam':
                $handler->putparam($aiccdata);
                break;
            case 'exitau':
                $handler->exitau();
                break;
            case 'putcomments':
            case 'putinteractions':
            case 'putobjectives':
            case 'putpath':
            case 'putperformance':