<?php
/**
* Page for registration of LMS SCORM data
* 
* This page is used to store commited data from a SCORM page to the LMS
* @package eFront
* @version 1.0
*/

//General initialization and parameters
session_cache_limiter('none');
session_start();

$path = "../libraries/";

/** Configuration file.*/
include_once $path."configuration.php";

//error_reporting(E_ALL);
echo "<pre>";print_r($_POST);print_r($_GET);
//$db->debug=true;
if (!eF_checkUser($_SESSION['s_login'], $_SESSION['s_password'])) {                        //Only avalid user may access this page
    header("location:index.php");
    exit;
}

//print '<META HTTP-EQUIV = "refresh" CONTENT = "2;URL='.basename($_SERVER['PHP_SELF']).'?close=true"/>';

if (isset($_POST['close'])) {                                                              //Close the window
    print '<SCRIPT LANGUAGE="JavaScript">
                //self.opener.location.reload(); 
                window.close();
           </script>';
}

if (isset($_POST['credit']) && $_POST['credit'] == 'no-credit') {                          //The lesson may not be credited, for example the professor deals with it
    echo "system message: <i>LESSON NOT CREDITED</i><br/>";
    exit;
}

//These are values that are present to the POST data, but not needed; so unset them.
unset ($_POST['credit']);
unset ($_POST['session_time']);
unset ($_POST['id']);

$fields['timestamp']  = time();
foreach ($_POST as $key => $value) {                                                       //Store POST parameters in a variable, so that they may be inserted in a database table
    $fields[$key] = $value;
}

$fields['users_LOGIN'] = $_SESSION['s_login'];                                             //The current user
if (!isset($fields['content_ID'])) {
    exit;
}

$result = eF_getTableData("scorm_data", "total_time,id", "content_ID=".$fields['content_ID']." AND users_LOGIN='".$fields['users_LOGIN']."'");      //���� �� ����� � ����� ���� ��� ����� �� SCO �� �� ���, ���� ��� ����������� ��������� (�.�. ������� ��������� ���� --> �� ��� ��� ���� �� ����� ���������� ����������, �� ���������� �� ������ �������������)
if (sizeof($result) > 0) {                                                      //This means that the students re-enters the unit
    if (isset($fields['total_time']) && isset($result[0]['total_time']) && $fields['total_time']) {      //Make sure that time is properly converted, for example 35+35 minutes become 1 hour 10 minutes, instead if 70 minutes
        $time_parts1 = explode(":", $fields['total_time']);
        $time_parts2 = explode(":", $result[0]['total_time']);
        $time_parts[0] = $time_parts1[0] + $time_parts2[0];
        $time_parts[1] = $time_parts1[1] + $time_parts2[1];
        $time_parts[2] = $time_parts1[2] + $time_parts2[2];
//print_r($time_parts1);print_r($time_parts2);print_r($time_parts);
        $time_parts[1] = $time_parts[1] + floor($time_parts[2]/60);
        $time_parts[2] = fmod($time_parts[2], 60);
        $time_parts[0] = $time_parts[0] + floor($time_parts[1]/60);
        $time_parts[1] = fmod($time_parts[1], 60);

        $fields['total_time'] = sprintf("%04d",$time_parts[0]).":".sprintf("%02d",$time_parts[1]).":".sprintf("%05.2f",$time_parts[2]);            //�� �������� ���� ��������� �����, HHHH:MM:SS.SS
    }
    
    eF_updateTableData("scorm_data", $fields, "id=".$result[0]['id']);        //Update old values with new ones
} else {    
    $result = eF_insertTableData("scorm_data", $fields);                      //Insert a new entry that relates the current user with this SCO
}

    $currentUser   = EfrontUserFactory :: factory($_SESSION['s_login'], false, 'student');
    $currentLesson = new EfrontLesson($_SESSION['s_lessons_ID']);
    $currentUnit   = new EfrontUnit($fields['content_ID']);

    if (strtolower($fields['lesson_status']) == 'passed' || strtolower($fields['lesson_status']) == 'completed') {
        $currentUser -> setSeenUnit($currentUnit, $currentLesson, true);
        $seenUnit = true;   
    } else {
    	$seenUnit = false;
    }

    $newUserProgress     = EfrontStats :: getUsersLessonStatus($currentLesson, $currentUser -> user['login']);
    $newPercentage       = $newUserProgress[$currentLesson -> lesson['id']][$currentUser -> user['login']]['overall_progress'];
    $newConditionsPassed = $newUserProgress[$currentLesson -> lesson['id']][$currentUser -> user['login']]['conditions_passed'];
    $newLessonPassed     = $newUserProgress[$currentLesson -> lesson['id']][$currentUser -> user['login']]['lesson_passed'];

    echo "
    	<html>
    	</html>
    	<body>
    	<script type = \"text/javascript\" src = \"js/scriptaculous/prototype.php\"> </script>
    	<script>    		
    		jsonString = '".json_encode(array($newPercentage, $newConditionsPassed, $newLessonPassed))."';
    		
    		if (parent.$('tree_image_".$currentUnit['id']."')) {
    			parent.$('tree_image_".$currentUnit['id']."').src = 'images/drag-drop-tree/".$currentUnit['ctg_type'].($seenUnit ? '_seen' : '').".png';
    		}
            if (parent.$('progress_bar')) {
            	parent.$('progress_bar').select('span.progressNumber')[0].update(parseFloat(jsonString.evalJSON()[0]) + '%');
            	parent.$('progress_bar').select('span.progressBar')[0].setStyle({width:parseFloat(jsonString.evalJSON()[0]) + 'px'});
            	parent.$('passed_conditions').update(parseInt(jsonString.evalJSON()[1]));
            	jsonString.evalJSON()[2] == true ? parent.$('lesson_passed').setStyle({color:'green'}) : parent.$('lesson_passed').setStyle({color:'red'});
            	
            }
    	</script>
    	</body>";


//pr($fields);

?>
