<?php
require_once("../config/database.php");
require_once("lti.php");

$data = $_POST['data'];
$user = $_POST['user'];
$course_id = $_POST['course_id'];
$lesson_id = $_POST['lesson_id'];
$grade_max = $_POST['grade_max'];
$grade_pass=$_POST['grade_pass'];
$lti_type=$_POST['lti_type'];

$returnObject = json_decode($data);

$lti = new LTI();
$content_items = 'https://purl.imsglobal.org/spec/lti-dl/claim/content_items';
$custom_id1 = $returnObject->instructorcustomparameters;

$custom_id=substr($custom_id1, 3);
$name = $returnObject->name;
$grade_max_lti=$returnObject->grade_point;
$launch_container = $returnObject->launchcontainer;
$tool_url = $returnObject->toolurl;
$text = "";

//Tip: grade_types_id not implemeted, in Db it is set to 1. (Types: scale(0-1), Points (0-10), score(0-100))
//As per moodle there be points values also 
$lti->contentdtl_id = $contentdtl_id;
$lti->name = $name;
$lti->custom_id = $custom_id;
$lti->grade_max_lti = $grade_max_lti;
$lti->grade_max = $grade_max;
$lti->grade_pass_actual = $grade_pass;
$lti->launch_container = $launch_container;
$lti->tool_url = $tool_url;
$lti->text = $text;
$lti->user_id = $user;
$lti->lti_types_id = $lti_type;
$lti->date_time = $date_time;
$lti->grade_min=0;
if ($grade_max != "") {
$lti->grade_pass=round(($grade_pass/$grade_max)*100);
}

$lti->course_id = $course_id;
$lti->lesson_id = $lesson_id;
//Fetch Max content_id FROM content_details
$content_id = 0;
$lti_content_id = $lti->fetch_content_id();
if ($result = $lti_content_id->fetch(PDO::FETCH_ASSOC)) {
    $content_id = $result['content_id'] + 1;
}
$lti->content_id = $content_id;
if ($lti->insert_content_details($lti)) {
    $lti->contentdtl_id = $lti->get_last_value('contentdtl_id', 'content_details');
    if ($lti->insert_lti($lti)) {
        if ($grade_max != "") {
            $lti->lti_id = $lti->get_last_value('lti_id', 'lti');
            if ($lti->insert_gradeitems($lti)) {

            }
        }
    }
}
?>