<?php
session_start();
include 'config/database.php';
include_once 'security/session_config.php';
include_once 'security/csrf.php';
include_once 'config/properties.php';
include_once "resources/offering.php";
require_once 'config/i18n.php';
include_once "resources/manageusers.php";
include_once "resources/EncryptDecrypt.php";
$csrf_token = get_csrf_token();
// initialize objects
$offering = new Offering();
$users = new ManageUsers();

//logo
$cust_company_logo = "";
$cust_company_image_path = "";
$cust_company_name = "";
$cust_company_banner = "";
$cust_company_banner_image_path = "";

$stmt_company = $users->UserCompanyDetails($_SESSION['uid']);
if ($row_company = $stmt_company->fetch(PDO::FETCH_ASSOC)) {
    extract($row_company);
    $cust_company_logo = $logo_path;
    $cust_company_name = $name;
}
$cust_company_image_path = ADMIN_HTTP_PATH . $properties['jdbc.comp_image_folder'] . "/" . $cust_company_logo;

$page_url = "contentview.php?";
$user_id = $_SESSION['uid'];

$offering_id = $_GET['offer'];
$offering->offering_id = $offering_id;
$offering->user_id = $user_id;
$offering->date = $date;

$currentDate = $date;

$stmt_course_assigned = $offering->checkCourseAssigned();
if ($stmt_course_assigned->rowCount() > 0) {
    $m = 0;
    $val = 0;
    $cont_count = 0;
    $stmt_comp = $offering->check_course_status();
    if ($stmt_comp->rowCount() > 0) {
        if ($row_comp = $stmt_comp->fetch(PDO::FETCH_ASSOC)) {
            extract($row_comp);
            if (($result == "complete") || ($result == "incomplete")) {
                $m = 1;
            }
            $val = $content_completion;
            $cont_count = $total_contents;
        }
    }
    ?>
    <html>

    <head>
        <meta name="csrf-token" content="<?= htmlspecialchars($csrf_token) ?>">
        <?php include "./head.php" ?>
        <title>
            <?php echo _("CN0101"); ?>
        </title>
        <link rel="stylesheet" href="assets/css/content/style.css">
    </head>

    <body>
        <!-- preloader start -->
        <div class="preloader js-preloader">
            <div class="preloader__bg" style="transform: scale(1, 0);"></div>
        </div>
        <!-- preloader end -->

        <nav class="navbar navbar-default sticky" id="navbar_top">
            <div class="d-flex justify-between items-center">

                <div class="col-auto">
                    <div class="navbar-header">
                        <a class="navbar-brand" href="#"><img src="<?php echo $cust_company_image_path; ?>"
                                alt="<?php echo $cust_company_name; ?>"></a>
                    </div>
                </div>

                <div class="col-auto">
                    <button class="button -sm rounded-8 -white text-dark-1 ml-5" id="menu-toggle"><i class="fa fa-bars"
                            id="icon_change"></i></button>
                </div>

                <div class="col-auto item lg:d-none">
                    <div class="text-18 lh-12 text-white" id="content_name_current"></div>
                </div>

                <div class="col-auto">
                    <div class="header-right d-flex items-center mr-10">
                        <div class="d-flex header-right__buttons">
                            <button class="button -sm rounded-8 -white text-dark-1" id="backToCourse"
                                title="<?php echo _("CT0105"); ?>"><i class="fa fa-arrow-left"></i></button>
                            <button class="button -sm rounded-8 -white text-dark-1 ml-5 download"
                                onclick='downloadContent()' title="<?php echo _("CRT2103"); ?>"><i
                                    class="fa fa-download"></i></button>
                            <button class="button -sm rounded-8 -white text-dark-1 ml-5" onclick='toggleFullScreen()'><i
                                    class="fa fa-expand"></i></button>
                        </div>
                    </div>
                </div>
            </div>
        </nav>

        <p style="display:none;"><span id="video_pos"></span></p>
        <input type='hidden' id='timer_new' value='' />
        <input type='hidden' id='time_out' value='<?php echo $timeout; ?>' />
        <div id='timer' style='display:none;'>
            <label id="hours">00</label>:<label id="minutes">00</label>:<label id="seconds">00</label>
        </div>

        <div class="content-wrapper js-content-wrapper" id="wrapper">
            <aside class="lesson-sidebar bg-light-3">
                <div class="px-15 sm:px-10">

                    <div>
                        <div class="progress mb-0 mt-20">
                            <div class="progress-bar progress-bar-info" role="progressbar"
                                aria-valuenow="<?php echo $val; ?>" aria-valuemin="0" aria-valuemax="100"
                                style="width:<?php echo $val; ?>%">
                            </div>
                        </div>
                        <div class="d-flex y-gap-10 justify-between items-center mt-3">
                            <div class="progress-text">
                                <?php echo $val; ?>% Complete
                            </div>
                        </div>
                    </div>

                    <div class="accordion -block-2 text-left js-accordion mt-15" id="menu">
                        <?php
                        $stmt = $offering->offer_display_course_lesson();
                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                            extract($row);
                            ?>
                            <div class="accordion__item is-active">
                                <div class="accordion__button py-10 px-10 bg-light-4">
                                    <div class="d-flex items-center">
                                        <div class="accordion__icon">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
                                                fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                                stroke-linejoin="round" class="feather feather-chevron-down icon">
                                                <polyline points="6 9 12 15 18 9"></polyline>
                                            </svg>
                                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
                                                fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                                stroke-linejoin="round" class="feather feather-chevron-up icon">
                                                <polyline points="18 15 12 9 6 15"></polyline>
                                            </svg>
                                        </div>
                                        <div>
                                            <span class="text-14 text-dark-1">Lesson
                                                <?php echo $seq_no; ?>:
                                            </span><br />
                                            <span class="text-17 fw-500 text-dark-1 pt-10">
                                                <?php echo $lesson_name; ?> &nbsp;
                                                <?php
                                                if ($lesson_dependency == "Y") {
                                                    $offering->seq_no = $seq_no;
                                                    $stmt_content_count = $offering->content_count_lesson();
                                                    if ($row_content_count = $stmt_content_count->fetch(PDO::FETCH_ASSOC)) {
                                                        extract($row_content_count);
                                                    }
                                                    if ($total_content != $viewed_content) {
                                                        ?>
                                                        <i class='fa fa-lock' id='lock_<?php echo $lesson_id; ?>'></i>
                                                        <?php
                                                    } else {
                                                        ?>
                                                        <i class='fa fa-unlock'></i>
                                                        <?php
                                                    }
                                                }
                                                ?>
                                            </span>
                                        </div>
                                    </div>
                                </div>

                                <div class="accordion__content">
                                    <div class="accordion_content_inner px-15 py-20">
                                        <div class="y-gap-30" id="content_list">

                                            <?php
                                            $offering->lesson_id = $lesson_id;
                                            $stmt1 = $offering->offer_display_course_content();
                                            $cont_count = 0;
                                            $content_icon = "";
                                            while ($row1 = $stmt1->fetch(PDO::FETCH_ASSOC)) {
                                                extract($row1);
                                                $cont_count = $cont_count + 1;
                                                $supported_image = array(
                                                    'gif',
                                                    'jpg',
                                                    'jpeg',
                                                    'png',
                                                    'bmp'
                                                );
                                                $supported_audio = array(
                                                    'mp3',
                                                    'wav',
                                                    'wave',
                                                    'm4a',
                                                    'm4p',
                                                    'm4r',
                                                    'ogg'
                                                );
                                                $supported_video = array(
                                                    'ogv',
                                                    'oga',
                                                    'ogx',
                                                    'ogm',
                                                    'spx',
                                                    'opus',
                                                    'webm',
                                                    'mp4',
                                                    'm4b',
                                                    'm4v',
                                                    'mov',
                                                    'qt',
                                                    'mkv'
                                                );
                                                $supported_document = array(
                                                    'doc',
                                                    'docx',
                                                    'xls',
                                                    'xlsx',
                                                    'pdf',
                                                    'ppt',
                                                    'pptx',
                                                    'txt',
                                                    'xml',
                                                    'xsl',
                                                    'rtf'
                                                );
                                                $ext = strtolower(pathinfo($content_path, PATHINFO_EXTENSION));
                                                if (in_array($ext, $supported_image)) {
                                                    $content_icon = "fa fa-sm fa-picture-o";
                                                } else if (in_array($ext, $supported_audio)) {
                                                    $content_icon = "fa fa-sm fa-file-audio-o";
                                                } else if (in_array($ext, $supported_video)) {
                                                    $content_icon = "fa fa-sm fa-youtube-play";
                                                } else if (in_array($ext, $supported_document)) {
                                                    $content_icon = "fa fa-sm fa-file-text";
                                                } else {
                                                    $content_icon = "fa fa-sm fa-file";
                                                }
                                                ?>
                                                <a href="javascript:;" class="d-flex items-center lesson_content"
                                                    data-type="content" data-content='<?php echo $contentdtl_id; ?>'
                                                    data-name='<?php echo htmlentities($content_title); ?>'>
                                                    <div
                                                        class="d-flex justify-center items-center size-30 rounded-full bg-purple-3 mr-10">
                                                        <div class="<?php echo $content_icon; ?> text-11"></div>
                                                    </div>
                                                    <div class="">
                                                        <div class="text-15 content_title_tag">
                                                            <?php echo htmlentities($content_title); ?>
                                                        </div>

                                                        <div class="d-flex x-gap-20 items-center pt-5">
                                                            <div class="text-12 lh-1 text-green-5 content_completion">
                                                                <?php if ($offering_count != 0) { ?>
                                                                    <i class="fa fa-check-circle-o"></i>
                                                                    <?php echo _("HM0125"); ?>
                                                                <?php } ?>
                                                            </div>
                                                        </div>

                                                    </div>
                                                </a>
                                                <?php
                                            }
                                            $stmt1 = $offering->offer_cyu_lesson();
                                            while ($row1 = $stmt1->fetch(PDO::FETCH_ASSOC)) {
                                                extract($row1);
                                                ?>
                                                <a href="javascript:;" class="d-flex items-center lesson_content"
                                                    data-type="assessment" data-content="<?php echo $assessment_id; ?>"
                                                    data-name="<?php echo htmlentities($assessment_name); ?>">
                                                    <div
                                                        class="d-flex justify-center items-center size-30 rounded-full bg-purple-3 mr-10">
                                                        <div class="fa fa-graduation-cap text-11"></div>
                                                    </div>
                                                    <div class="">
                                                        <div class="text-15 content_title_tag">
                                                            <?php echo _("CT0104"); ?>
                                                        </div>
                                                    </div>
                                                </a>
                                                <?php
                                            }
                                            ?>

                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php }
                        ?>

                    </div>
                </div>
            </aside>

            <div class="main_content" id="page-content-wrapper" style="display:block;">


                <div class="video-responsive">
                    <div class='viewer' id='document' style='display: none;'>
                        <div id='loadIframe'></div>
                    </div>
                    <div class='viewer uk-responsive-width' id='video' style='display: none;'>
                        <video controls disablePictureInPicture controlsList='nodownload' playsinline id='video_player'
                            style="width:100%;height:100%;"></video>
                    </div>
                    <div class='viewer' id='audio' style='display: none;'>
                        <audio id='audio_player' controls controlsList='nodownload'></audio>
                    </div>
                    <div class='viewer' id='image' style='display: none;overflow-y:scroll;'>
                        <img id='image_viewer'>
                    </div>
                    <div class='viewer' id='youtube' style='display: none;'>
                        <iframe id='youtube_viewer' frameborder='0' allowfullscreen uk-responsive></iframe>
                        <!--                                    <iframe id='youtube_viewer' frameborder='0' allow='autoplay; encrypted-media;camera;microphone' allowfullscreen='allowfullscreen' mozallowfullscreen='mozallowfullscreen' msallowfullscreen='msallowfullscreen' oallowfullscreen='oallowfullscreen' webkitallowfullscreen='webkitallowfullscreen'></iframe>-->
                    </div>
                    <div class='viewer' id='other' style='display: none;'>
                        <div class='wpb_wrapper'>
                            <div class='color-dark text-center mg-top-100 mg-bottom-60'>
                                <p class='fs-14' id='other_viewer'></p>
                            </div>
                        </div>
                    </div>
                    <div class='viewer px-20' id='perge_data' style='display: none;overflow-y: scroll;'>
                    </div>

                </div>


                <div class="footer border-top-dark">
                    <div class="d-flex justify-between items-center bg-white">
                        <button class="button -icon bg-color-primary h-60 text-white mt-5" id="prev-button">
                            <i class="fa fa-angle-double-left text-13 mr-8"></i>

                        </button>
                        <div class="form-checkbox px-30 py-5 ml-5" id="mark-button">
                            <?php if ($m != 1) { ?>
                                <div class="checkbox d-flex items-center">
                                    <input type="checkbox" id="mark">
                                    <div class="form-checkbox__mark">
                                        <div class="form-checkbox__icon icon-check"></div>
                                    </div>
                                    <div class="text-16 fw-500 ml-5" id='label_text'></div>
                                </div>
                            <?php } ?>
                        </div>
                        <button class="button -icon bg-color-primary h-60 text-white ml-5" id="next-button">

                            <i class="fa fa-angle-double-right text-13 ml-8"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <?php include "./footer_secondary.php"; ?>
        <script src="assets/js/glightbox.min.js"></script>
        <script>
            //right click disabled
            // $(function () {
            // $(this).bind('contextmenu', function () {
            // return false;
            //});
            // $('img').on('dragstart', false);
            //});
            /* Full Screen view*/
            function toggleFullScreen() {
                var elem = document.getElementById("page-content-wrapper");
                if ((document.fullScreenElement !== undefined && document.fullScreenElement === null) || (document.msFullscreenElement !== undefined && document.msFullscreenElement === null) || (document.mozFullScreen !== undefined && !document.mozFullScreen) || (document.webkitIsFullScreen !== undefined && !document.webkitIsFullScreen)) {
                    if (elem.requestFullScreen) {
                        elem.requestFullScreen();
                    } else if (elem.mozRequestFullScreen) {
                        elem.mozRequestFullScreen();
                    } else if (elem.webkitRequestFullScreen) {
                        elem.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
                    } else if (elem.msRequestFullscreen) {
                        elem.msRequestFullscreen();
                    }
                }
            }
            if (document.addEventListener) {
                document.addEventListener('webkitfullscreenchange', exitHandler, false);
                document.addEventListener('mozfullscreenchange', exitHandler, false);
                document.addEventListener('fullscreenchange', exitHandler, false);
                document.addEventListener('MSFullscreenChange', exitHandler, false);
            }
            function exitHandler() {
                if (!document.webkitIsFullScreen && !document.mozFullScreen && !document.msFullscreenElement) {
                    if (document.cancelFullScreen) {
                        document.cancelFullScreen();
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    } else if (document.webkitCancelFullScreen) {
                        document.webkitCancelFullScreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                }
            }

        </script>

        <script>
            /Display Content/
            var offer = null, user = null;
            var allListItems;
            var id, mode_value = "", contentType = "";
            var next_allowed = "";
            var path_download = "";
            var m_value = "<?php echo $m; ?>";
            var current_content_value = "0";
            var online = "";
            var interval = null;
            var completed = "";
            var button_value = "";
            var previous_status = null;
            var totalSeconds = 0;
            var hoursLabel = document.getElementById("hours");
            var minutesLabel = document.getElementById("minutes");
            var secondsLabel = document.getElementById("seconds");
            var windowsize = 0;
            var backToCourseFlag = false;

            $(document).ready(function () {
                windowsize = $(window).width();
                allListItems = document.querySelectorAll("a.lesson_content");
                offer = "<?php echo $_GET['offer'] ?>";
                user = "<?php echo $_SESSION['uid'] ?>";
                Array.from(allListItems).forEach(link => {
                    link.addEventListener('click', function (event) {
                        insertTime();
                        showContent($(this), $(this).data('type'), $(this).data('content'));
                    });
                });
                var content = "<?php echo $_GET['value']; ?>";
                var type = "<?php echo $_GET['type']; ?>";
                var firstItem = document.querySelector('[data-type="' + type + '"][data-content="' + content + '"]');
                firstItem.click();

                $("#backToCourse").click(function () {
                    backToCourseFlag = true;
                    insertTime_onBackPress();
                });
            });
            window.onbeforeunload = function () {
                if (backToCourseFlag === false) {
                    insertTime();
                }
            };
            function insertTime() {
                const csrf_token = $('meta[name="csrf-token"]').attr('content');
                //const csrf_token = $('meta[name="csrf-token"]').attr('content');
                if (online === 'Y' && m_value === '0' && mode_value === 'content') {
                    if (next_allowed !== "No") {
                        if (completed !== 'Y') {
                            if (current_content_value !== "0") {
                                $.ajax({
                                    type: 'POST',
                                    async: true,
                                    url: 'modules/track_content.php',
                                    data: {
                                        mode: 'time',
                                        oid: '<?php echo $_GET["offer"]; ?>',
                                        cid: current_content_value,
                                        time: $('#hours').text() + ':' + $('#minutes').text() + ':' + $('#seconds').text(),
                                        time_diff: $('#video_pos').text(),
                                        type: contentType,
                                        csrf_token: csrf_token
                                    },
                                });
                            }
                        }
                    }
                }
                return;
            }

            window.backToCourseView = function () {
                window.location = "../courseview.php?offering=<?php echo $offering_id; ?>#content";
            };

            function insertTime_onBackPress() {
                if (online === 'Y' && m_value === '0' && mode_value === 'content') {
                    if (next_allowed !== "No") {
                        if (completed !== 'Y') {
                            if (current_content_value !== "0") {
                                var timeValue = $('#hours').text() + ":" + $('#minutes').text() + ":" + $('#seconds').text();
                               const csrf_token = $('meta[name="csrf-token"]').attr('content');
                                //const csrf_token = $('meta[name="csrf-token"]').attr('content');
                                $.ajax({
                                    type: 'POST',
                                    async: true,
                                    url: 'modules/track_content.php',
                                    data: { "mode": "time", "oid": "<?php echo $_GET['offer']; ?>", "cid": current_content_value, "time": timeValue, "time_diff": $('#video_pos').text(), "type": contentType, "csrf_token": csrf_token },
                                    success: function (data) {
                                        if (contentType == "xapi") {
                                            document.getElementById("youtube_viewer").contentWindow.insertxapi_backToCourse('y');
                                        } else {
                                            window.location = "courseview.php?offering=<?php echo $offering_id; ?>#content";
                                        }
                                    },
                                    error: function (xhr, type, exception) {
                                        if (contentType === "xapi") {
                                            document.getElementById("youtube_viewer").contentWindow.insertxapi_backToCourse('y');
                                        } else {
                                            window.location = "courseview.php?offering=<?php echo $offering_id; ?>#content";
                                        }
                                    }
                                });
                            }
                        } else {
                            window.location = "courseview.php?offering=<?php echo $offering_id; ?>#content";
                        }
                    } else {
                        window.location = "courseview.php?offering=<?php echo $offering_id; ?>#content";
                    }
                } else {
                    window.location = "courseview.php?offering=<?php echo $offering_id; ?>#content";
                }
                return;
            }

            function backToCourse() {
                backToCourseFlag = true;
                insertTime_onBackPress();
            }

            document.addEventListener("DOMContentLoaded", function () {
                //Expand accordians open on page load
                const content = document.querySelectorAll('.accordion__content');
                for (let l = 0; l < content.length; l++) {
                    content[l].style.maxHeight = content[l].scrollHeight + "px";
                }
                if ($(window).width() < 768) {
                    $('#wrapper').addClass('toggled');
                    $('aside').toggle("slide", function () {
                        var visibilityStatus = $('aside').attr("data-visible");
                        $('aside').attr('data-visible', visibilityStatus);
                    });
                }
            });
            $("#menu-toggle").click(function (e) {
                e.preventDefault();
                $("#wrapper").toggleClass("toggled");
                $('aside').toggle("slide", function () {
                    var visibilityStatus = $('aside').attr("data-visible");
                    $('aside').attr('data-visible', visibilityStatus);
                });
                $("#icon_change").toggleClass("fa-bars fa-times");
            });

            function sidebar_click(thisobj) {
                $(".lesson_content").removeClass("active_content");
                $(thisobj).addClass('active_content');
                var $container = $('aside');
                $scrollTo = $('.active_content');

                $container.scrollTop(
                    $scrollTo.offset().top - $container.offset().top + $container.scrollTop() - 100
                );
                id = $(thisobj).data('content');
                ctype = $(thisobj).data('type');
                process();
                $('#content_name_current').html('<?php echo _("CT0106") . ' : '; ?>' + $(thisobj).data('name'));
            }
            function process() {
                var currentItem = document.querySelector('[data-content="' + id + '"][data-type="' + ctype + '"]');
                var currentIndex = Array.from(allListItems).indexOf(currentItem);
                var m = currentIndex <= 0 ? true : false;
                var n = currentIndex >= allListItems.length - 1 ? true : false;
                if (m) {
                    $('#prev-button').css("visibility", "hidden");
                } else {
                    $('#prev-button').html('<i class="fa fa-angle-double-left text-13 ml-8"></i> <?php echo _("CT0102") . '<br />'; ?>' + allListItems[currentIndex - 1].querySelector(".content_title_tag").textContent);
                    $('#prev-button').css("visibility", "visible");
                }
                if (n) {
                    $('#next-button').css("visibility", "hidden");
                } else {
                    $('#next-button').html('<?php echo _("CT0101") ?><br />' + allListItems[currentIndex + 1].querySelector(".content_title_tag").textContent + '<i class="fa fa-angle-double-right text-13 ml-8"></i>');
                    $('#next-button').css("visibility", "visible");
                }
            }
            $('#next-button').click(function () {
                //insertTime();
                goTo(1);
            });
            $('#prev-button').click(function () {
                //insertTime();
                goTo(-1);
            });
            function goTo(direction) {
                direction = direction || 1;
                var currentItem = document.querySelector('[data-content="' + id + '"][data-type="' + ctype + '"]');
                var currentIndex = Array.from(allListItems).indexOf(currentItem);
                var newIndex = currentIndex + (direction);
                allListItems[newIndex].click();
            }
            function showContent(thisobj, mode, id) {
                $('#video_player').get(0).pause();
                $('#audio_player').get(0).pause();
                sidebar_click(thisobj);
                mode_value = mode;
                $.ajax({
                    url: 'modules/get_content.php',
                    data: { "offer": offer, "id": id, "mode": mode },
                    type: 'GET',
                    dataType: "json",
                    cache: false,
                    async: false,
                    success: function (response) {
                        $('.viewer').hide();
                        next_allowed = response.next_allowed;
                        contentType = response.type;
                        var current_date = "<?php echo $currentDate; ?>";
                        if ((response.result === "complete") || (response.result === "incomplete") || response.end_date < current_date) {
                            m_value = 1;
                        }
                        if (response.status === "Perge") {
                            $('#perge_data').show();
                            $('#perge_data').html("<center><h4>This content is no more available</h4></center>");
                        } else {
                            if (next_allowed === "No" && (response.result == null || response.result === 'awaited')) {
                                if ($('#lock_' + response.lesson_id + '').hasClass("fa-unlock")) {
                                    $('#lock_' + response.lesson_id + '').removeClass('fa fa-lg fa-unlock').addClass('fa fa-lg fa-lock');
                                }
                                $('#mark-button').hide();
                                $('#perge_data').show();
                                $('#perge_data').html(response.html);
                                if (interval != null) {
                                    clearInterval(interval); // stop the interval
                                }
                                $('.download').hide();
                                totalSeconds = 0;
                                setTime1();
                            } else {
                                if (response.mode === 'content') {
                                    path_download = response.path_download;
                                    online = response.online;
                                    $('.viewer').hide();
                                    if (response.result === null || response.result === 'awaited') {
                                        if ($('#lock_' + response.lesson_id + '').hasClass("fa-lock")) {
                                            $('#lock_' + response.lesson_id + '').removeClass('fa fa-lg fa-lock').addClass('fa fa-lg fa-unlock');
                                        }
                                    }
                                    if (response.type === "Scorm" || response.type === "HTML5" || response.type === "Web content" || response.type === "YouTube" || response.type === "SlideShare" || response.type === "Wikipedia" || response.type === "Scribd" || response.type === "HTML" || response.type === "xapi" || response.type === "lti") {
                                        $('.download').hide();
                                    } else {
                                        if (response.online === "Y") {
                                            $('.download').hide();
                                        } else {
                                            $('.download').show();
                                            if (response.status === "Perge") {
                                                $('.download').prop("disabled", true);
                                            } else {
                                                $('.download').prop("disabled", false);
                                            }
                                        }
                                    }
                                    status_update(offer, user, id, "view");
                                    totalSeconds = response.total_time;
                                    completed = response.completed;
                                    current_content_value = id;
                                    if (m_value === '0') {
                                        $('#mark-button').show();
                                        previous_status = response.prev_status;
                                        if (previous_status === null && response.type === "video") {
                                            $('#mark').attr("disabled", true);
                                            $("#mark").css('cursor', 'auto');
                                            $("#label_text").css('cursor', 'auto');
                                            $("#label_text").css('color', 'gray');
                                        } else {
                                            $('#mark').attr("disabled", false);
                                            $("#mark").css('cursor', 'pointer');
                                            $("#label_text").css('cursor', 'pointer');
                                            $("#label_text").css('color', 'black');
                                        }
                                        button_value = response.button_value;
                                        $('#label_text').text(response.button_value);
                                        $('#mark').prop('checked', false);

                                        if (button_value === "Completed") {
                                            $('#mark').prop('checked', true);
                                            if (response.type === "Scorm" || response.type === "xapi") {
                                                $('#mark').attr("disabled", true);
                                                $("#mark").css('cursor', 'auto');
                                                $("#label_text").css('cursor', 'auto');
                                            }
                                        } else if (button_value === "Incomplete") {
                                            $("#mark").attr("disabled", true);
                                            $("#mark").css('cursor', 'auto');
                                            $("#label_text").css('cursor', 'auto');
                                        }
                                    } else {
                                        $('#mark-button').hide();
                                    }
                                    $('#video_pos').text('');
                                    if (response.type === "video") {
                                        if (completed !== 'Y' && m_value !== 1) {
                                            $('body > style').remove();
                                            $('<style>video::-webkit-media-controls-timeline{display: none;}</style>').appendTo('body');
                                        } else {
                                            if (response.result === 'awaited') {
                                                $('body > style').remove();
                                                $('<style>video::-webkit-media-controls-timeline{display: none;}</style>').appendTo('body');
                                            } else {
                                                $('body > style').remove();
                                                $('<style>video::-webkit-media-controls-timeline{display: block;}</style>').appendTo('body');
                                            }
                                        }
                                        $('#video').show();
                                        $("#video_player").html('<source src="' + response.path + '" type="video/mp4"></source><source src="' + response.path + '" type="video/ogg"></source>');
                                        $("#video_player")[0].load();
                                        var timeDiffeCheck = response.time_diff;
                                        if (timeDiffeCheck == null) {
                                            timeDiffeCheck = '';
                                        }
                                        if (timeDiffeCheck != '') {
                                            var a = response.time_diff.split(':'); // split it at the colons
                                            var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
                                            $('#video_player').prop('currentTime', seconds);
                                        }
                                    } else if (response.type === "audio") {
                                        //$('#audio').show();
                                        $('#audio').show();
                                        $("#audio_player").html('<source src="' + response.path + '" type="audio/ogg"></source><source src="' + response.path + '" type="audio/mpeg"></source>');
                                        $("#audio_player")[0].load();
                                        $('#audio_player').get(0).play();
                                    } else if (response.type === "image") {
                                        $('#image_viewer').attr('src', response.path);
                                        $('#image').show();
                                    } else if (response.type === "document") {
                                        $('#document').show();
                                        $('#loadIframe').html("<iframe id='document_viewer' src='" + response.path + "' frameborder='0' scrolling='no' seamless='' allowfullscreen='allowfullscreen'></iframe><div style = 'width: 80px; height: 80px; position: absolute; opacity: 0; right: 0px; top: 0px;'>&nbsp;</div>");
                                    } else if (response.type === "other") {
                                        var src = 'Document format not supported. Please <a href="' + response.path + '" target="_blank" style="color:blue"> Download</a> it.';
                                        $('#other').show();
                                        $('#other_viewer').html(src);
                                    } else if (response.type === "live") {
                                        $('#youtube').show();
                                        $('#youtube_viewer').attr('src', response.path);
                                    } else {
                                        $('#youtube').show();
                                        $('#youtube_viewer').attr('src', response.path);
                                    }
                                    if (interval !== null) {
                                        clearInterval(interval); // stop the interval
                                    }
                                    if (online === 'Y' && m_value === '0' && mode_value === 'content') {
                                        if (next_allowed !== "No") {
                                            if (completed !== 'Y') {
                                                interval = setInterval(setTime, 1000);
                                            } else {
                                                setTime1();
                                            }
                                        }
                                    } else {
                                        setTime1();
                                    }
                                } else if (response.mode === "assessment") {
                                    var src = 'quiz_cyu.php?oid=' + offer + '&aid=' + id + '&result=' + m_value;
                                    $('#youtube').show();
                                    $('#youtube_viewer').attr('src', src);
                                    totalSeconds = 0;
                                    if (interval != null) {
                                        clearInterval(interval); // stop the interval
                                    }
                                    setTime1();
                                    $('#mark-button').hide();
                                    $('.download').hide();
                                }
                            }
                        }
                    },
                    error: function (data) {
                       
                        if (data.responseText && data.responseText.indexOf("SESSION_EXPIRED") !== -1) {
                            window.location.href = "<?php echo LOGOUT_URL; ?>";
                        } else {
                            alert("<?php echo _('GN0401'); ?>");
                        }
                    }
                });
            }
            function status_update(offer, user, content, mode) {
                //const csrf_token = $('meta[name="csrf-token"]').attr('content');
               const csrf_token = $('meta[name="csrf-token"]').attr('content');
                $.ajax({
                    url: 'modules/track_content.php',
                    data: { "oid": offer, "uid": user, "cid": content, "mode": mode, "csrf_token": csrf_token },
                    dataType: "html",
                    //async: false,
                    type: 'POST',
                success: function (data) {
                        //     console.log("Data:", data.status);
                        //    if (data && data.status === 'session_expired') {
                        //         alert("Session expired. Please login again.");
                        //         window.location.href = 'login.php';
                        //     }
                        // if (data.indexOf("SESSION_EXPIRED") !== -1) {
                        // alert("Session expired. Please login again.");
                        // window.location.href = 'login.php';
                        // }
                        //insertTime();
                        if (interval !== null) {
                            clearInterval(interval); // stop the interval
                        }
                        if (mode === "completed") {
                            completed = 'Y';
                            $('#label_text').text("<?php echo _("CT0107") ?>");
                            $('#mark').prop('checked', true);
                            $('.progress-bar').css("width", data + "%");
                            $('#progress_value').text(data + "%");
                            $('.progress-text').html(data + "% Complete");
                            $('.active_content').find('.content_completion').html("<i class='fa fa-check-circle-o'></i> Completed");
                        } else if (mode === "incompleted") {
                            completed = 'N';
                            $('#label_text').text("<?php echo _("CT0108") ?>");
                            $('#mark').prop('checked', false);
                            if (data === "") {
                                $('#progress_value').text("0%");
                                $('.progress-bar').css("width", "0%");
                                $('.progress-text').html("0% Complete");
                            } else {
                                $('#progress_value').text(data + "%");
                                $('.progress-bar').css("width", data + "%");
                                $('.progress-text').html(data + "% Complete");
                            }
                            $('.active_content').find('.content_completion').html("");

                        }
                        if (online === 'Y' && m_value === '0' && mode_value === 'content') {
                            if (next_allowed !== "No") {
                                if (completed !== 'Y') {
                                    interval = setInterval(setTime, 1000);
                                } else {
                                    setTime1();
                                }
                            }
                        } else {
                            setTime1();
                        }
                    },
                    failure: function () {
                        alert("<?php echo _("GN0401") ?>");
                    }
                });
            }
            $('video').on('ended', function () {
                if (previous_status === null) {
                   const csrf_token = $('meta[name="csrf-token"]').attr('content');
                    //const csrf_token = $('meta[name="csrf-token"]').attr('content');
                    var tt = $('#hours').text() + ":" + $('#minutes').text() + ":" + $('#seconds').text();
                    $.ajax({
                        url: 'modules/track_content.php',
                        data: { "oid": offer, "uid": user, "cid": id, "time": tt, "mode": "video_viewed", "csrf_token": csrf_token },
                        dataType: "html",
                        async: false,
                        type: 'POST',
                        success: function (data) {
                            $('#mark').attr("disabled", false);
                            $("#mark").css('cursor', 'pointer');
                            $("#label_text").css('cursor', 'pointer');
                            $("#label_text").css('color', 'black');
                        },
                        error: function () {
                            alert("<?php echo _("GN0401") ?>");
                        }
                    });
                }
            });
            function downloadContent() {
               const csrf_token = $('meta[name="csrf-token"]').attr('content');
                //const csrf_token = $('meta[name="csrf-token"]').attr('content');
                $.ajax({
                    url: 'modules/track_content.php',
                    data: { "path": path_download, "oid": offer, "uid": user, "cid": current_content_value, "mode": "download", "csrf_token": csrf_token },
                    dataType: "html",
                    type: 'POST',
                    success: function (data) {
                        const link = document.createElement('a');
                        link.setAttribute('href', 'modules/track_content.php?path=' + path_download + '&oid=' + offer + '&cid=' + current_content_value + '&mode=download');
                        link.click();
                        //window.location.href = 'modules/track_content.php?path=' + path_download + '&oid=' + offer + '&cid=' + current_content_value + '&mode=download';
                    },
                    failure: function () {
                        alert("<?php echo _("GN0401") ?>");
                    }
                });
            }
            $('#mark').click(function () {
                if ($(this).prop("checked") === true) {
                    $('#video_pos').text('');
                    $('body > style').remove();
                    $('<style>video::-webkit-media-controls-timeline{display: block;}</style>').appendTo('body');
                    insertTime();
                    status_update(offer, user, id, "completed");
                } else if ($(this).prop("checked") === false) {
                    insertTime();
                    status_update(offer, user, id, "incompleted");
                    $('body > style').remove();
                    $('<style>video::-webkit-media-controls-timeline{display: none;}</style>').appendTo('body');
                }
            });
            function setTime() {
                ++totalSeconds;
                var hour = Math.floor(totalSeconds / 3600);
                var minute = Math.floor((totalSeconds - hour * 3600) / 60);
                var second = totalSeconds - (hour * 3600 + minute * 60);
                secondsLabel.innerHTML = pad(second);
                minutesLabel.innerHTML = pad(minute);
                hoursLabel.innerHTML = pad(hour);
            }
            function setTime1() {
                var hour = Math.floor(totalSeconds / 3600);
                var minute = Math.floor((totalSeconds - hour * 3600) / 60);
                var second = totalSeconds - (hour * 3600 + minute * 60);
                secondsLabel.innerHTML = pad(second);
                minutesLabel.innerHTML = pad(minute);
                hoursLabel.innerHTML = pad(hour);
            }
            function pad(val) {
                var valString = val + "";
                if (valString.length < 2) {
                    return "0" + valString;
                } else {
                    return valString;
                }
            }
        </script>

        <script type="text/javascript" language="javascript">
            var idleMax = $('#time_out').val(); // Logout after 1 minute of IDLE
            var idleTime = 0;
            var idleInterval = setInterval("timerIncrement()", 1000);  // 1 second interval    
            //mousemove
            $(document).mousemove(function (event) {
                idleTime = 0; // reset to zero
                $('#timer_new').val(idleTime);
            });
            //onclick
            $(document).on('click', function (e) {
                idleTime = 0; // reset to zero
                $('#timer_new').val(idleTime);
            });
            //keypress
            $(document).on('keypress', function (e) {
                idleTime = 0; // reset to zero
                $('#timer_new').val(idleTime);
            });
            //scroll
            $(document).on('scorll', function (e) {
                idleTime = 0; // reset to zero
                $('#timer_new').val(idleTime);
            });
            //document viewer clicks
            window.onload = function () {
                var oFrame = document.getElementById("document_viewer");
                if (oFrame != null) {
                    oFrame.contentWindow.document.onclick = function () {
                        idleTime = 0; // reset to zero
                        $('#timer_new').val(idleTime);
                    };
                    oFrame.contentWindow.document.onmousemove = function () {
                        idleTime = 0; // reset to zero
                        $('#timer_new').val(idleTime);
                    };
                    oFrame.contentWindow.document.onscorll = function () {
                        idleTime = 0; // reset to zero
                        $('#timer_new').val(idleTime);
                    };
                }
            };
            //Scorm
            window.scormclick = function () {
                idleTime = 0; // reset to zero
                $('#timer_new').val(idleTime);
            };
            // count minutes
            function timerIncrement() {
               const csrf_token = $('meta[name="csrf-token"]').attr('content');
                //const csrf_token = $('meta[name="csrf-token"]').attr('content');
                idleTime = idleTime + 1;
                $('#timer_new').val(idleTime);
                if (idleTime > idleMax) {
                    //inserting total time to DB before logout
                    if (online === 'Y' && m_value === '0' && mode_value === 'content') {
                        if (next_allowed !== "No") {
                            if (completed !== 'Y') {
                                if (current_content_value !== "0") {
                                    $.ajax({
                                        type: 'POST',
                                        async: true,
                                        data: {
                                            mode: 'time',
                                            oid: '<?php echo $_GET["offer"] ?>',
                                            uid: '<?php echo $_SESSION["uid"] ?>',
                                            cid: current_content_value,
                                            time: $('#hours').text() + ':' + $('#minutes').text() + ':' + $('#seconds').text(),
                                            time_diff: $('#video_pos').text(),
                                            csrf_token: csrf_token
                                        },
                                        success: function (data) {
                                            window.location = "logout.php";
                                        }
                                    });
                                }
                            }
                        }
                    }
                }
            }
        </script>
        <script>
            // Get the video element with id="video_player"
            var vid1 = document.getElementById("video_player");
            // Assign an ontimeupdate event to the video element, and execute a function if the current playback position has changed
            vid1.ontimeupdate = function () {
                myFunction();
            };
            function myFunction() {
                // Display the current position of the video in a p element with id="video_pos"
                document.getElementById("video_pos").innerHTML = vid1.currentTime;
            }
        </script>




    </body>

    </html>
    <?php
} else {
    echo "<div class='col-md-12 mg-top-10'>";
    echo "<div class='alert alert-danger'><h4 class='mg-bottom-5'>";
    echo _("CR0501");
    echo "</h4></div>";
    echo "</div>";
}
?>