<?php

// ------------------------------------------------------------------------------------
// Database-specific code
// ------------------------------------------------------------------------------------
include_once "../resources/offering.php";

function dbConnect() {

    // database login details
    global $dbname;
    global $dbhost;
    global $dbuser;
    global $dbpass;

    // link
    global $link;

    $dbname = DATABASE;
    $dbhost = HOST;
    $dbuser = USER;
    $dbpass = PASSWORD;
    // connect to the database
    $link = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
}

function readElement($VarName) {

    global $link;
    global $scorm_id;
    global $oid;
    global $id;
    global $end_date;
    global $rslt;
    global $contentdtl_id;

    $safeVarName = mysqli_escape_string($link, $VarName);

    $result = mysqli_query($link, "select value from scorm_track where ((offering_id=$oid) and (user_id=$id) and (scorm_id=$scorm_id) and (model='$safeVarName'))");
    list($value) = mysqli_fetch_row($result);

    return $value;
}

function readNameElement() {
    global $link;
    global $id;
    $name = "";
    try {
        $result3 = mysqli_query($link, "select first_name,last_name from user_account where user_id=$id");
        if (mysqli_num_rows($result3)) {
            if ($row4 = mysqli_fetch_array($result3)) {
                $name = $row4['last_name'] . ',' . $row4['first_name'];
                $name=addslashes($name);
            }
        }
    } catch (Exception $e) {
        //echo $e->getMessage();
        error_log("Caught $e");
    }
    print_r($name);
    //return $name;
    // return $value['first_name'] .' '. $value['last_name'];
}

function writeElement($VarName, $VarValue) {

    global $link;
    global $scorm_id;
    global $oid;
    global $id;
    global $end_date;
    global $rslt;
    global $contentdtl_id;

	try {
		$safeVarName = mysqli_escape_string($link, $VarName);
		$safeVarValue = mysqli_escape_string($link, $VarValue);

		$result = mysqli_query($link, "select value from scorm_track where ((offering_id=$oid) and (user_id=$id)and(scorm_id=$scorm_id) and (model='$safeVarName'))");
		// if nothing found ...
		if (!mysqli_num_rows($result)) {
			mysqli_query($link, "insert into scorm_track (offering_id,user_id,scorm_id,model,value) values ($oid,$id,$scorm_id,'$safeVarName','$safeVarValue')");
		} else {
			mysqli_query($link, "update scorm_track set value='$safeVarValue' where ((offering_id=$oid) and (user_id=$id) and (scorm_id=$scorm_id) and (model='$safeVarName'))");
		}
	} catch (Exception $e) {
        //echo $e->getMessage();
        error_log("Caught $e");
    }
    return;
}

function updateContentTrack() {
    global $link;
    global $scorm_id;
    global $oid;
    global $id;
    global $end_date;
    global $rslt;
    global $contentdtl_id;
    global $date_time;
    global $date;

    $offering = new Offering();
	
	try {

		$offering->scorm_id = $scorm_id;
		//$stmt = $offering->get_scorm_total_time();
		//if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
			//extract($row);
			//if ($total_time == NULL || $total_time == '0' || $total_time == "") {
				//mysqli_query($link, "update content_track set completed='Y',content_progress='100',last_viewed_ts='" . $date_time . "' where offering_id=$oid and user_id=$id and contentdtl_id=$contentdtl_id");
			//} else {
				//$location = readElement('cmi.core.lesson_location');
				//if ($location != "") {
					//$location = round($location);
					//$content_progress = ($location / $total_time) * 100;
					//mysqli_query($link, "update content_track set completed='Y',content_progress=ROUND($content_progress,0),last_viewed_ts='" . $date_time . "' where offering_id=$oid and user_id=$id and contentdtl_id=$contentdtl_id");
				//} else {
					mysqli_query($link, "update content_track set completed='Y',content_progress='100',last_viewed_ts='" . $date_time . "' where offering_id=$oid and user_id=$id and contentdtl_id=$contentdtl_id");
				//}
			//}
		//}

		$weightage = 0;
		$result3 = mysqli_query($link, "select weightage from result_criteria where scorm_id=$scorm_id and offering_id=$oid");
		if (mysqli_num_rows($result3)) {
			if ($row4 = mysqli_fetch_array($result3)) {
				$weightage = $row4['weightage'];
			}
			$result5 = mysqli_query($link, "select * from scorm_offer_criteria where offering_id=$oid and user_id=$id and scorm_id=$scorm_id");
			if (!mysqli_num_rows($result5)) {
				mysqli_query($link, "insert into scorm_offer_criteria (offering_id,user_id,scorm_id,xapi_id,weightage,last_updated_ts) values ($oid,$id,$scorm_id,0,$weightage,'$date_time')");
			} else {
				mysqli_query($link, "update scorm_offer_criteria set weightage='$weightage',last_updated_ts='$date_time' where offering_id=$oid and user_id=$id and scorm_id=$scorm_id");
			}
		}

		$offering->user_id = $id;
		$offering->offering_id = $oid;
		$offering->datetime = $date_time;
		if ($comp = $offering->cal_update_completion()) {
			if ($comp == "100") {
				$offering->date = $date;
				$stmt_criteria = $offering->check_course_criteria_ref();
				if ($stmt_criteria->rowCount() > 0) {
                                    
                                    //extra added from track_content
                                        $row = $stmt_criteria->fetch(PDO::FETCH_ASSOC);
                                        extract($row);
					$offering->attended_date = $date_time;
					$offering->result = "complete";
                                        if(($row['completion_points']!= NULL)){
                                            $offering->completion_points = $row['completion_points'];
                                        }else{
                                            $offering->completion_points = NULL; 
                                        }
					$offering->score = 0;
					$offering->last_updated_ts = $date_time;
					$val = $offering->update_result();
					if ($val) {
                                            $points = $offering->Sum_completionPoints();
                                            if($points !=NULL){
                                                 $update_pt = $offering->update_userpoint($points);     
                                                 if($update_pt){

                                                 } 
                                            }
                                        }
				}
			}
		}
	} catch (Exception $e) {
      //  echo $e->getMessage();
        error_log("Caught $e");
    }
}

function updateScormContentTrack() {
    global $link;
    global $scorm_id;
    global $oid;
    global $id;
    global $end_date;
    global $rslt;
    global $contentdtl_id;
    global $date_time;
    global $date;

    $offering = new Offering();
	try {

		$offering->scorm_id = $scorm_id;
		//$stmt = $offering->get_scorm_total_time();
		//if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
			//extract($row);

			//if ($total_time == NULL || $total_time == '0' || $total_time == "") {
			//} else {
				$location = readElement('cmi.core.lesson_location');
				if ($location == NULL || $location == "") {
					
				} else {
					$content_progress=0;
					
					//Check string has comma
					if (strpos($location, ',') !== false) {
						$location_arr = preg_split("/\,/", $location);
						//check string is a numbers
						if(is_numeric($location_arr[0]) && is_numeric($location_arr[1])) {
							//check $location_arr[1] has non zero value
							if($location_arr[1] > 0) {
								$content_progress = round(($location_arr[0] / $location_arr[1]) * 100);
								if ($content_progress > 100) {
									$content_progress = 100;
								}
							}
						}
					}
					
					mysqli_query($link, "update content_track set content_progress=ROUND($content_progress,0),last_viewed_ts='" . $date_time . "' where offering_id=$oid and user_id=$id and contentdtl_id=$contentdtl_id");
				}
			//}
		//}

		$weightage = 0;
		$result3 = mysqli_query($link, "select weightage from result_criteria where scorm_id=$scorm_id and offering_id=$oid");
		if (mysqli_num_rows($result3)) {
			if ($row4 = mysqli_fetch_array($result3)) {
				$weightage = $row4['weightage'];
			}
			$result5 = mysqli_query($link, "select * from scorm_offer_criteria where offering_id=$oid and user_id=$id and scorm_id=$scorm_id");
			if (!mysqli_num_rows($result5)) {
				mysqli_query($link, "insert into scorm_offer_criteria (offering_id,user_id,scorm_id,xapi_id,weightage,last_updated_ts) values ($oid,$id,$scorm_id,0,$weightage,'$date_time')");
			} else {
				mysqli_query($link, "update scorm_offer_criteria set weightage='$weightage',last_updated_ts='$date_time' where offering_id=$oid and user_id=$id and scorm_id=$scorm_id");
			}
		}

		$offering->user_id = $id;
		$offering->offering_id = $oid;
		$offering->datetime = $date_time;
		$comp = $offering->cal_update_completion();
	
	} catch (Exception $e) {
        //echo $e->getMessage();
        error_log("Caught $e");
    }
}

// ------------------------------------------------------------------------------------
// LMS-specific code
// ------------------------------------------------------------------------------------
function setInLMS($varname, $varvalue) {
    return "OK";
}

function getFromLMS($varname) {
    global $link;
    global $id;
    global $scorm_id;
    global $end_date;
    global $rslt;
    global $contentdtl_id;

    switch ($varname) {

        case 'cmi.core.student_name':
            $result1 = mysqli_query($link, "select first_name,last_name from user_account where user_id='" . $id . "'");
            if ($row = mysqli_fetch_array($result1)) {
                $name = $row['first_name'];
                $varvalue = $name;
            }

            break;

        case 'cmi.core.student_id':
            $varvalue = $id;
            break;

        case 'adlcp:masteryscore':
            $result2 = mysqli_query($link, "select mastery_score from scorm where scorm_id='" . $scorm_id . "'");
            if ($row2 = mysqli_fetch_array($result2)) {
                $score = $row2['mastery_score'];
                $varvalue = $score;
            }
            //$varvalue = 80;
            break;

        case 'cmi.launch_data':
            $varvalue = "";
            break;

        default:
            $varvalue = '';
    }

    return $varvalue;
}

function scorm_reconstitute_array_element($element_name, $children) {

    global $link;
    global $scorm_id;
    global $oid;
    global $id;
    global $end_date;
    global $rslt;
    global $contentdtl_id;

    // reconstitute comments_from_learner and comments_from_lms
    $current = '';
    $current_subelement = '';
    $current_sub = '';
    $count = 0;
    $count_sub = 0;
    $userdata = array();

    $result = mysqli_query($link, "select model,value from scorm_track where offering_id=" . $oid . " and user_id=" . $id . " and scorm_id='" . $scorm_id . "'");
    while ($row = mysqli_fetch_array($result)) {

        // make the value safe by escaping quotes and special characters
        //$jvarvalue = addslashes($varvalue);
        // javascript to set the initial cache value
        $userdata[$row["model"]] = $row['value'];
    }

    // filter out the ones we want
    $element_list = array();
    foreach ($userdata as $element => $value) {
        if (substr($element, 0, strlen($element_name)) == $element_name) {
            $element_list[$element] = $value;
        }
    }

    // sort elements in .n array order
    uksort($element_list, "scorm_element_cmp");


    // generate JavaScript
    foreach ($element_list as $element => $value) {

        $element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
        preg_match('/\_(\d+)\./', $element, $matches);

        if (count($matches) > 0 && $current != $matches[1]) {
            if ($count_sub > 0) {
                echo '    ' . $element_name . '_' . $current . '.' . $current_subelement . '._count = ' . $count_sub . ";\n";
            }
            $current = $matches[1];
            $count++;
            $current_subelement = '';
            $current_sub = '';
            $count_sub = 0;
            $end = strpos($element, $matches[1]) + strlen($matches[1]);
            $subelement = substr($element, 0, $end);
            echo '    ' . $subelement . " = new Object();\n";
            // now add the children
            foreach ($children as $child) {
                echo '    ' . $subelement . "." . $child . " = new Object();\n";
                echo '    ' . $subelement . "." . $child . "._children = " . $child . "_children;\n";
            }
        }

        // now - flesh out the second level elements if there are any

        $element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
        preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);


        // check the sub element type
        if (count($matches) > 0 && $current_subelement != $matches[1]) {
            if ($count_sub > 0) {
                echo '    ' . $element_name . '_' . $current . '.' . $current_subelement . '._count = ' . $count_sub . ";\n";
            }
            $current_subelement = $matches[1];
            $current_sub = '';
            $count_sub = 0;
            $end = strpos($element, $matches[1]) + strlen($matches[1]);
            $subelement = substr($element, 0, $end);
            echo '    ' . $subelement . " = new Object();\n";
        }

        // now check the subelement subscript
        if (count($matches) > 0 && $current_sub != $matches[2]) {
            $current_sub = $matches[2];
            $count_sub++;
            $end = strrpos($element, $matches[2]) + strlen($matches[2]);
            $subelement = substr($element, 0, $end);
            echo '    ' . $subelement . " = new Object();\n";
        }

        echo '    ' . $element . ' = \'' . addslashes($value) . "';\n";
    }

    $results = print_r($element_name . '._count = ' . $count, true);

    if ($count_sub > 0) {
        echo '    ' . $element_name . '_' . $current . '.' . $current_subelement . '._count = ' . $count_sub . ";\n";
    }
    if ($count > 0) {
        echo '    ' . $element_name . '._count = ' . $count . ";\n";
    }
}

function scorm_element_cmp($a, $b) {
    preg_match('/.*?(\d+)\./', $a, $matches);
    $left = intval($matches[1]);
    preg_match('/.?(\d+)\./', $b, $matches);
    $right = intval($matches[1]);
    if ($left < $right) {
        return -1; // Smaller.
    } else if ($left > $right) {
        return 1;  // Bigger.
    } else {
        // Look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern.
        if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
            $leftterm = intval($matches[2]);
            $left = intval($matches[3]);
            if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
                $rightterm = intval($matches[2]);
                $right = intval($matches[3]);
                if ($leftterm < $rightterm) {
                    return -1; // Smaller.
                } else if ($leftterm > $rightterm) {
                    return 1;  // Bigger.
                } else {
                    if ($left < $right) {
                        return -1; // Smaller.
                    } else if ($left > $right) {
                        return 1;  // Bigger.
                    }
                }
            }
        }
        // Fall back for no second level matches or second level matches are equal.
        return 0;  // Equal to.
    }
}

function data_submitted() {

    if (empty($_POST)) {
        return false;
    } else {
        return (object) fix_utf8($_POST);
    }
}

function fix_utf8($value) {
    if (is_null($value) or $value === '') {
        return $value;
    } else if (is_string($value)) {
        if ((string) (int) $value === $value) {
            // Shortcut.
            return $value;
        }
        // No null bytes expected in our data, so let's remove it.
        $value = str_replace("\0", '', $value);

        // Note: this duplicates min_fix_utf8() intentionally.
        static $buggyiconv = null;
        if ($buggyiconv === null) {
            $buggyiconv = (!function_exists('iconv') or @ iconv('UTF-8', 'UTF-8//IGNORE', '100' . chr(130) . '€') !== '100€');
        }

        if ($buggyiconv) {
            if (function_exists('mb_convert_encoding')) {
                $subst = mb_substitute_character();
                mb_substitute_character('');
                $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
                mb_substitute_character($subst);
            } else {
                // Warn admins on admin/index.php page.
                $result = $value;
            }
        } else {
            $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
        }

        return $result;
    } else if (is_array($value)) {
        foreach ($value as $k => $v) {
            $value[$k] = fix_utf8($v);
        }
        return $value;
    } else if (is_object($value)) {
        // Do not modify original.
        $value = clone($value);
        foreach ($value as $k => $v) {
            $value->$k = fix_utf8($v);
        }
        return $value;
    } else {
        // This is some other type, no utf-8 here.
        return $value;
    }
}

?>