<!DOCTYPE html>
<html lang="en">

<head>
    <title>External Tool</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <style>
        .modal-body {
            height: 500px;
        }
    </style>
</head>

<body>
    <?php

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        require_once("../config/database.php");
        require_once("lti.php");
        include_once("../resources/EncryptDecrypt.php");

        $mcrypt = new MCrypt();
        $course_id = $mcrypt->decrypt($_POST['param1']);
        $lesson_id = $mcrypt->decrypt($_POST['param2']);
        $user_id = $mcrypt->decrypt($_POST['param3']);
        $comp_id = $mcrypt->decrypt($_POST['param4']);

        ?>

        <div class="container">
            <h2>External Tool</h2>
            <div class="form-group">
                <label>Content Title</label>
                <input class="form-control" type="text" id="content_title" />
            </div>
            <div class="form-group">
                <label>Preconfigured Tool</label>
                <select class="form-control" id="providers">
                    <?php
                    $lti = new LTI();
                    $stmt = $lti->get_lti_types_admin($comp_id);
                    while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
                        $tool_name = $result['tool_name'];
                        $tool_id = $result['lti_types_id'];
                        ?>
                        <option value="<?php echo $tool_id; ?>">
                            <?php echo $tool_name; ?>
                        </option>
                    <?php } ?>
                </select>
            </div>
            <div id="grade_div">
                <div class="form-group">
                    <label>Grade Max</label>
                    <input class="form-control" type="number" min="1" max="100" id="grade_max" readonly />
                </div>

                <div class="form-group">
                    <label>Grade Pass</label>
                    <input class="form-control" type="number" min="1" max="100" id="grade_pass" value="0" />
                </div>
            </div>
            <!-- Trigger the modal with a button -->
            <button type="button" class="btn btn-info btn-lg" id="select_lti_contents">Select
                Content</button>

            <input type='hidden' id='content_return_data2' value=''>

            <button type="button" class="btn btn-info btn-lg" id="submit" onclick="sendData()">Submit
                Content</button>

            <!-- Modal -->
            <div class="modal fade" id="lti-modal" data-backdrop="static" data-keyboard="false">
                <div class="modal-dialog modal-lg" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button class="close" type="button" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">×</span></button>
                            <h5 class="modal-title">LTI Contents</h5>
                        </div>
                        <div class="modal-body modal-lg">
                            <iframe id="ltiIframe" width="100%" height="100%" frameborder="0"></iframe>
                        </div>
                    </div>
                </div>
            </div>

        </div>
        <script>
            $('#select_lti_contents').click(function () {
                $('#lti-modal').modal('show');
                var tool_id = $("#providers option:selected").val();
                $("#ltiIframe").attr("src", "contentitem.php?user_id=<?php echo $user_id ?>&course_id=<?php echo $course_id ?>&id=" + tool_id + "&comp_id=<?php echo $comp_id ?>");
            });
        </script>

        <script>
            $('.document').ready(function () {
                $('#grade_div').hide();
            });
            //modal close
            $('#lti-modal').on('hidden.bs.modal', function () {
                var user = "<?php echo $user_id ?>";
                // Find the iframe that loads the child page by its ID
                var childIframe = document.getElementById('ltiIframe');
                // Access the content window of the iframe
                var childWindow = childIframe.contentWindow;
                // Access the hidden parameter value from the child page
                var data = childWindow.document.getElementById('content_return_data').value;
                if (typeof data !== 'undefined') {
                    document.getElementById('content_return_data2').value = data;
                    var decodeddata = JSON.parse(data);
                    $('#content_title').val(decodeddata.name);
                    if ('grade_point' in decodeddata) {
                        $('#grade_div').show();
                        grade_max = $('#grade_max').val(decodeddata.grade_point);
                    } else {
                        $('#grade_div').hide();
                    }
                }
            });

            function sendData() {
                var grade_pass = 0, grade_max = "";
                var user = "<?php echo $user_id ?>";
                var course_id = "<?php echo $course_id ?>";
                var lesson_id = "<?php echo $lesson_id ?>";
                var tool_id = $("#providers option:selected").val();
                // Get the value from the input element
                var inputValue = document.getElementById('content_return_data2').value;
                if ($('#grade_max').length) {
                    grade_max = $('#grade_max').val();
                    grade_pass = $('#grade_pass').val();
                    if (parseInt(grade_pass) > parseInt(grade_max)) {
                        alert("passing grade value should not exceed max value of grade");
                        return false;
                    }
                }

                if (inputValue != "") {
                    // Use jQuery to send an AJAX request
                    $.ajax({
                        url: 'contentitem_insert.php', // Change this to the URL of your PHP script
                        type: 'POST',
                        data: { data: inputValue, user: user, course_id: course_id, lesson_id: lesson_id, grade_max: grade_max, grade_pass: grade_pass, lti_type: tool_id },
                        success: function (response) {
                            alert("success");
                            setTimeout("window.close()", 500);
                            if (window.opener) {
                                // Reload the opener (the first tab)
                                window.opener.location.reload();
                            } else {
                                console.log("No opener to reload.");
                            }
                        }
                    });
                } else {
                    alert("please select a content");
                }
            }

        </script>
    <?php } else { ?>
        <center><p><b>Please close this window and click external tool</b></p></center>
        <?php } ?>
</body>

</html>