<?php
session_start();
 
if (!isset($_SESSION['initiated']))
{
//    echo "Initialize"; 
    session_regenerate_id(true);
    $_SESSION['initiated'] = true;
} 
//echo '<!--p ' . $_SESSION['initiated'] . ' -->';

//test cookies work
/*
 * $cookie_name = "Game Design School cookie";
$cookie_value = "Game Design School cookie";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
if(!isset($_COOKIE[$cookie_name])) {
    echo "<b>" . lan_enablecookie'] . "</b>";
} 
 * 
 */ 
    $_SESSION['debug'] = 0; 
    $_SESSION['time_start'] = microtime();
?>

<!DOCTYPE html>
<html  lang="en"> 
<head>
    
<style>
.btn-primary {
  --bs-btn-color: #fff;
  --bs-btn-bg: var(--btn-hover-color);
  --bs-btn-border-color: var(--btn-hover-color);
  --bs-btn-hover-color: #fff;
  --bs-btn-hover-bg: var(--accent-color);
  --bs-btn-hover-border-color: var(--accent-color);
  --bs-btn-focus-shadow-rgb: 49,132,253;
  --bs-btn-active-color: #fff;
  --bs-btn-active-bg: #0a58ca;
  --bs-btn-active-border-color: #0a53be;
  --bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
  --bs-btn-disabled-color: #fff;
  --bs-btn-disabled-bg: #0d6efd;
  --bs-btn-disabled-border-color: #0d6efd;
}
</style>
<?php
if ($_SESSION['user_country'] == "AE")
{
    session_destroy();
    return;
} 
if ($_SESSION['debug']) 
    echo "<br><br><br>";
require_once $_SERVER['DOCUMENT_ROOT'] . '/vgd_shared.php';
PrintDebugTime("Alku1 ");
require_once $_SERVER['DOCUMENT_ROOT'] . '/language.php';
PrintDebugTime("Alku2 ");
require_once $_SERVER['DOCUMENT_ROOT'] . '/cache.php';
PrintDebugTime("Alku3 ");
require_once $_SERVER['DOCUMENT_ROOT'] . '/editor/editor_shared.php';
PrintDebugTime("Alku4 ");
 
//include('header.html');
//$header = file_get_contents('header.html');
//$header = str_replace('xxxTITLExxx', "Home - Game Design School", $header);
//echo $header;

/*echo "<br>";
echo "<br>";
echo $_SESSION['language'];
echo lan_login'];*/

$page_id = test_input($_GET['page']);

$preview = test_input($_GET['preview']);
if ($preview == 1)
    CreateCache();

PrintDebugTime("Head 1");

PutCookie();
AddHttpCaching();
//AddHeader(lan_welcometo']);
//    echo "Here";

//HandleCurriculumMenu($_SESSION['loginname'], 'menu2_new.html', "xp_megamenu", $page_id);//$_SESSION['page_id']);
//HandleMenu($_SESSION['loginname'], 'menu2_new.html', "xp_megamenu", $page_id);//$_SESSION['page_id']);
echo "<br>";
echo "<br>";
//xp echo HandleXPBar("", "menu2_xp.html");
PrintDebugTime("Head 1.5");
?>
    
<meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body class="index-page">

 <?php

//$file = file_get_contents('top.html'); 
//echo $file;
try {
//$_SESSION['course_id'] = 'gdg';
//if ($_SESSION['course_id'] != 'gdg')
PrintDebugTime("Head 1.9");
/*if (! $_SESSION['editor_image_cache_created'])
    CreateEditorImageCache();
else
if ($preview == 1)
    CreateEditorImageCache();
*/
PrintDebugTime("Head 2");

AddGoogleTag('home');

if (isset($_REQUEST['save'])) 
{
        if ($_SERVER['REQUEST_METHOD'] == "POST") 
        {
            
                    AddGoogleTag('home-save');
                    if ((empty($_SESSION['user_id'])) || ($_SESSION['user_id'] == 0))
                    {
                        echo "<script language=\"javascript\" type=\"text/javascript\">";
                        echo "window.location=\"register.php?saving=1\";";
                        echo "</script>"; 
                    }  
                    //echo "<br><br><br><br><br>HERE ANSWER:". $answer_exercise;
                    //from page parameters
                    $save = test_input($_GET['save']);
                    $exercise = test_input($_GET['exercise']);
                    //$answer_id = test_input($_GET['answer_id']);
                    $sort_id = test_input($_GET['sort_id']);
                    $answer_exercise = test_input($_POST['answer_' . $exercise]);
                    $upload_file = test_input($_POST['upload_file' . $exercise]);
                    $answer_str = "saveexercise " . $answer_exercise;
                    $return_page = test_input($_GET['return_page']);
                    
                    SaveStats($_SESSION['user_id'], $exercise, $answer_str, $_SERVER['HTTP_REFERER']);
                    //from form data
                    //echo "<br><br><br><br><br>HERE ANSWER:". $answer_exercise;
//                    if ($answer_exercise != "")
                    if ($_SESSION['user_id'] > 0)
                    {
                            //get the answer
                            $conn = CreateConnection("vgd");
                            $answer_exercise = GetMysqlEscapeString($conn, $answer_exercise);
                            $answer_exercise = str_replace("  aa aa", '', $answer_exercise); //replace the word doc red dot zero escape char which brakes saving                           
                            $answer_exercise = str_replace("\xE2\x80\xA8", '', $answer_exercise); //replace the word doc red dot zero escape char which brakes saving                           

                            //echo "<br><br><br><br><br>" ;
                            //echo "Answer: " . $answer_exercise . "<br>";
                            $sql = "SELECT * ";
                            $sql = $sql . " FROM answer WHERE name = '"  . $exercise . "'";
                            $sql = $sql . " AND user_id = " .$_SESSION['user_id'] . " AND sort_id = " . $sort_id;
                            $sql = $sql . " AND course_id = '" . $_SESSION['course_id'] . "' ";
                            $result3 = $conn->query($sql);
                            $answer = GetAnswer($exercise, $sort_id);
                            $found_something = 0;
                            //echo "<br><br><br><br>" . $answer['name'] . "-". $answer['sort_id'] . $upload_file;
                            //if ($answer['name'] != "")// && 
                            if ($result3->num_rows == 0)
                            {
                                    $sql = "INSERT INTO answer (name, course_id, user_id, sort_id, answer, upload_image, created)";
                                    $sql = $sql . " VALUES ('" .  $exercise . "','" . $_SESSION['course_id'] . "', " . $_SESSION['user_id'] . "," . $sort_id . ",'" . $answer_exercise . "','" . $upload_file . "',NOW() ) ";
                            }
                            else
                            {
                                    $sql = "UPDATE answer SET answer = '" . $answer_exercise ."', upload_image = '" . $upload_file . "' ";
                                    $sql = $sql . " WHERE name = '" . $exercise . "' AND user_id = " . $_SESSION['user_id'] . " AND sort_id = " . $sort_id;
                                    $sql = $sql . " AND course_id = '" . $_SESSION['course_id'] . "'";
                            }

                            //echo "<br><br><br>".$exercise."<br>".$answer."<br>".$sql . $_SESSION['answers'];
                            //die("here" . $sql);
                            //CacheCompl();
                            if ( mysqli_query($conn, $sql))
                            {
                                $id = mysqli_insert_id($conn);
                                //if ($_SESSION['user_id'] == 2)
                                {
                                    $e = GetExercise($exercise);
                                    $uploaded_images = false;
                                    echo "here";
                                    for ($i = 0; $i < $e['max_uploads']; $i++)
                                    {
                                        $uploadable_file = 'exercise_image_' . $exercise . $i . '_uploadfile';
                                        //echo "here" .$i . $exercise . $uploadable_file;
                                        $uploadfile = test_input($_POST[$uploadable_file]);
                                        $original_filename = $uploadfile;//test_input($_POST['upload_filename' . $e['name'] . $i]);
                                        echo " - uploadfile" . $uploadfile;
                                        if ($uploadfile != "")
                                        { 
                                            //echo "<br>uploadable_file:" . $uploadable_file;
                                            $sql = "";
                                            if (strcmp($_SESSION['uploads'][$exercise][$i], $uploadfile) != 0)
                                            {
                                                if ($_SESSION['uploads'][$exercise][$i] != "")
                                                {
                                                    $sql = "UPDATE answer_uploads SET upload_filename = '" . $uploadfile . "', original_filename='" . $original_filename ."' WHERE user_id = '" . $_SESSION['user_id'] . "' AND course_id = '" . $_SESSION['course_id'] . "' AND exercise_id =  '" . $e['name'] . "' AND sort_id = " . $i;
                                                    //echo $sql;
                                                }
                                                else 
                                                {
                                                    $sql = "INSERT INTO answer_uploads (user_id, course_id, exercise_id, sort_id, upload_filename, original_filename ) ";
                                                    $sql = $sql . " values (" . $_SESSION['user_id'] . ",'" . $_SESSION['course_id'] . "','" . $e['name'] . "'," . $i . ",'" . $uploadfile . "', '" . $original_filename . "' )";
                                                }
                                            }
                                            //echo "<br><br><br>HEREEEEE" . $sql . "<br>";
                                            if ($sql != "")
                                            {
                                                if ( mysqli_query($conn, $sql))
                                                {
                                                    $id = mysqli_insert_id($conn);
                                                    $uploaded_images = true;
                                                }
                                                else
                                                {
                                                    echo "Error saving upload images..." . $uploadfile . $sql;
                                                }
                                            }
                                        }
                                    }
                                    if ($uploaded_images)
                                    {
                                        echo "<br><div class='container shadow rounded text-center' style='background-color:#a1c154;color:white'>";
                                        echo "<br>" . "Uploaded images saved." . "<br><br>";
                                        echo "</div>";
                                        CacheUploads();                                        
                                    }
                                }
//                                echo "Exercise saved!<br>";
//                                echo lan_exercisesaved . "<br>";
                                CacheAnswers($conn);
                                SetPageStatus($page_id);
                                $_SESSION['menu'] = "";
//not needed anymore                                CacheStats();
                                
                                echo "<script language=\"javascript\" type=\"text/javascript\">";
                                if ($return_page == "page")
                                {
                                    if ($sort_id == 0)
                                        echo "window.location='page.php?page=" . $page_id . "#" . $exercise . "';";
                                    else
                                        echo "window.location='page.php?page=" . $page_id . "&sort_id=" . $sort_id . "#" . $exercise ."';";
                                } 
                                if ($return_page == "cert")
                                {
                                        echo "window.location='10credits.php#" . $exercise . "';";
                                }
                                if ($return_page == "home")
                                {
                                        echo "window.location='home.php';";
                                }
                                echo "</script>";
                                
                                echo "<br><div class='container shadow rounded text-center' style='background-color:#a1c154;color:white'>";
                                echo "<br>" . lan_exercisesaved . "<br><br>";
                                echo "</div>";
                            }  
                            else 
                            {
                                //echo $conn->error;
                                //HandleError($conn, $sql, "");//die("Error: " . $conn->error);
                                echo "<br><div class='container shadow rounded text-center' style='background-color:#ed8d1c;color:white'>";
                                echo "<br><br><br>" . lan_exercisesaved_error . "<br>";
                                echo "Please ensure you're connection is active, you're still logged in, you have not exceeded max 2500 characters or used special characters that could cause this.<br>If not, then please contact us!";
                                echo "</div>";
//                                echo "Error saving exercise... <br>";
                            }
                            CloseConnection($conn);
                    }
        } 
} 
//    http://ec2-52-66-243-33.ap-south-1.compute.amazonaws.com/test.php?page=home

    $course_id = test_input($_GET['course']);
    SetCurrentCourse($course_id);

    $page_id = test_input($_GET['page']);
    $completed = test_input($_GET['completed']);
    $uncompleted = test_input($_GET['uncompleted']);
    $save_id = test_input($_GET['completed']);
    $cookies = test_input($_GET['cookies']);
    $sort_id = test_input($_GET['sort_id']);
    $new_rating = test_input($_GET['rating']);
    $hid = test_input($_GET['hid']);

    $container_break_done = false;
    $exercise_list = "";
    
PrintDebugTime("Head 3");
    $_SESSION['page_id'] = $page_id;
//    $conn = CreateConnection("vgd");
    
//    $user_id = CheckUser($conn, $email, $password);
    if ($page_id == 'canvas')
    {
        echo "<script language=\"javascript\" type=\"text/javascript\">";
        echo "window.location='canvas.php?lesson=1';";
        echo "</script>";
    }
    
    $page = GetPage($page_id);
    $course = GetCourse($_SESSION['course_id']);
    $parent = GetParent($page['parent_id']);
PrintDebugTime("Head 3");
    
    $header = AddHeader($course['course_name'] .  " - " . $page['title'], false, '/header2.html'); 
    //$header = AddHeader($course['course_name'] .  " - " . $page['title']);
    echo $header;
    //do here to get the menu updated correctly after save
    HandleEdugaMenu2($_SESSION['loginname'], $_SERVER['DOCUMENT_ROOT'] . '/menu_edugametion_2025.html', "megamenu", "");
//    echo "<br><br><br>PAGE: " . $page['title'];
PrintDebugTime("Head 4");

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//COOKIES
    if (($cookies == 1) || ($cookies == -1))
    {
        SetCookies($cookies);
        $conn = CreateConnection("vgd");
        $sql = "UPDATE users SET cookies = " . $cookies . " WHERE user_id = " . $_SESSION['user_id'];
//        echo $sql;
        if ( mysqli_query($conn, $sql))
        {
            echo lan_cookiesok;
//            echo "Updated cookies info succesfully!";
            $_SESSION['cookies'] = 1;
        }
        CloseConnection($conn);
    } 
    
//    
//    $header = file_get_contents('header.html');
//    $header = str_replace('xxxTITLExxx', lan_vgd'] .  " - " . $page['title'], $header);
//    echo $header;

        //echo "This page has not been completed";
     
/*    echo "<br><br><br>";
    echo "Pub:".$page['public'] ." <br>";
    echo $_SESSION['fname'] ." <br>";
    echo $_SESSION['member'] ." <br>";*/
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CHECK EDITOR ACCESS
//
    
PrintDebugTime("Head 5");
$editor_access = CheckEditorAccess($_SESSION["course_id"]);
//echo "editor_access " . $editor_access ."<br>";
//if not an editor, grant access 

if ($editor_access == 0)
{
    if ((isset($hid)) && ($hid != "")) //login info is in the link sent in the email 
    {
        //die("Died HEre:" . $user_id . " HID:" . $hid . ":". $completed . $uncompleted . "<br><br><br><br><br><br><br>");
        //die ("USer found...". $_SESSION['user_id'] . $_SESSION['user'] ." - ". $_SESSION['cookies']);
        $conn = CreateConnection("vgd");
        $result = DoHIDLogin($conn, $hid);
        CloseConnection($conn);
        echo "<script language=\"javascript\" type=\"text/javascript\">";
        echo "window.location=\"page.php?page=". $page_id ."\";";
        echo "</script>";
    } 
    //public, trial ohi
    //ok public ja user_id != ''
    //ok, ei public ja on access 
    //$access = $_SESSION['access'][$_SESSION["course_id"]];
//    echo "Trial: " . $_SESSION['trial'];
    if (($page['public'] != 1) && empty($_SESSION['user_id']))
    {
    //echo phpinfo();
        echo "<script language=\"javascript\" type=\"text/javascript\">";
//         echo "window.location=\"register.php\";";
        echo "window.location='/payment/pricing.php?noaccess=1'";
//        echo "window.location='/payment/pricing.php?noaccess=1'";
//        echo "window.location='/payment/pricing.php?hndl=" . $_SESSION["course_id"] . "&noaccess=1';";
        echo "</script>";
    }  
    if (($page['public'] == 1) && empty($_SESSION['user_id']))
    {
        echo "<script language=\"javascript\" type=\"text/javascript\">";
//it's ok        echo "window.location=\"register.php\";";
        echo "</script>";
    }  
    if (($page['public'] != 1) && ($_SESSION['user_id'] != '') && (! CheckHasCourseAccess($_SESSION['course_id'])))
    {
    //echo phpinfo();
/*        echo "<script language=\"javascript\" type=\"text/javascript\">";
        echo "window.location=\"register.php\";";
        echo "</script>";*/
        echo "<script language=\"javascript\" type=\"text/javascript\">";
//            echo "window.location='pricing.php?norights=1&button=pagenorights';";
        echo "window.location='/payment/pricing.php?noaccess=1'";
//        echo "window.location='/payment/pricing.php?noaccess=1'";
//        echo "window.location='/payment/pricing.php?hndl=" . $_SESSION["course_id"] . "&noaccess=1';";
        echo "</script>";
    }
/*    if (($page['public'] == 1) && (CheckIsTrialOver()) && (! CheckHasCourseAccess($_SESSION['course_id'])))
    {
        echo "<script language=\"javascript\" type=\"text/javascript\">";
        echo "window.location=\"/payment/pricing.php?notrial=1\";";
        echo "</script>";
    }  */
    if (($page['public'] != 1) && (! CheckHasCourseAccess($_SESSION['course_id'])))//  && (CheckIsTrialOver()))
    {
        echo (lan_norights);
    //        echo "Public: " . $page['public'];
    //        die ("Sorry, you do not have access rights to this content...");
        echo "<script language=\"javascript\" type=\"text/javascript\">";
        echo "window.location='/payment/pricing.php?noaccess=1'";
//        echo "window.location='/payment/pricing.php?noaccess=1'";
//        echo "window.location='/payment/pricing.php?hndl=" . $_SESSION["course_id"] . "&noaccess=1';";
        echo "</script>";
    }
/*    else
    {
        echo "<script language=\"javascript\" type=\"text/javascript\">";
        echo "window.location='home.php?course=" . $_SESSION["course_id"] . "';";
        echo "</script>";

    }
    if (( $_SESSION['member'] < 1) && ($page['public'] == 0) && ($page_id != 'upsel') && ($page_id != 'learn'))
    {
    }  
//    echo $_SESSION['member'] . "member";
    if (( $_SESSION['member'] < 1) && ($page['public'] == 1) && ( $_SESSION['trial'] < 1) && ($page_id != 'upsel'))
    {
    //        die ("Sorry, you do not have access rights to this content...");
        $access = $_SESSION['access'][$_SESSION["course_id"]];
        if (! $access)
        {
            echo "<script language=\"javascript\" type=\"text/javascript\">";
//            echo "window.location='pricing.php?trialover=1&button=pagetrialover';";
            echo "window.location='home.php?course=" . $_SESSION["course_id"] . "';";
            echo "</script>";
        }
        else
        {
            echo "<script language=\"javascript\" type=\"text/javascript\">";
            echo "window.location='home.php?course=" . $_SESSION["course_id"] . "';";
            echo "</script>";
            
        }
    }*/  
}
else
    echo "Welcome Editor!<br>";
PrintDebugTime("Head 6");

    
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//BANNER
// 
        AddBanner(); 
//        SaveStats($_SESSION['user_id'], $page_id, "open", $_SERVER['HTTP_REFERER'], true, true);

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//NOWONLY
//
/*   if ( $_SESSION['member'] < 1) 
        if (!IsSuperOfferCountry())
           AddNowOnly();*/

//    echo "<div class='container'>";  
//    echo "<div class='row'>";
//    echo "<div class='col-md-12 d-none d-lg-block'>"; //d-none d-lg-block= hidden on mobile , small devices
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//BREADCRUMS
//    $crums = CreateBreadcrums2($page);
//    echo $crums;
   
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CREATE TABS
//    $tabs = CreateTabs2($page['parent_id'], $page_id);
//    echo $tabs;
 
//    echo "</div>";
//    echo "</div>";
//    echo "</div>";
   
   
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//ADD TOP
/*    $file = file_get_contents('top2.html');
    $file = str_replace_first('xxxCDNxxx', CDN, $file);
    $file = str_replace_first('xxxIMAGExxx', $page['image'], $file);
    $file = str_replace('xxxHEADERxxx', $page['title'], $file);//there's more than one
    if ($page['subtitle'] != "")
        $file = str_replace_first('xxxSUBHEADERxxx', $page['subtitle'], $file);
//        $file = str_replace('xxxSUBHEADERxxx', "<div class='top-centered'><h4>" . $page['subtitle'] . "</h4></div>", $file);
    else
        $file = str_replace_first('xxxSUBHEADERxxx',  "", $file);

    echo $file;            
*/
    
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//ADD TOPBAR
/*    $file = file_get_contents('topbar_player.html');
    $file = str_replace_first('xxxCDNxxx', CDN, $file);

    $compl = GetCompl();

    $total = $_SESSION['compl_count'];//$result_t->fetch_assoc();
    $total_pages = TOTAL_PAGES; //CHECK FROM DATABASE!
    $presentage =  strval(intval($total*100 / $total_pages));
    $file = str_replace('xxxTOTALxxx', strval($presentage) . "%", $file);
    if ($presentage < 5)
        $file = str_replace('xxxTOTALCOLORxxx', "black", $file);
    else
        $file = str_replace('xxxTOTALCOLORxxx', "white", $file);

    $file = str_replace('xxxYOUHAVECOMPLETEDxxx', xxxYOUHAVECOMPLETEDxxx, $file);
    
    echo $file;            
*/
    
/*/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//BREADCRUMS
    CreateBreadcrums2($page);
    
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CREATE TABS
    CreateTabs2($page['parent_id'], $page_id);
*/

PrintDebugTime("Bef columns");
    
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CREATE THE COLUMNS FOR THE PAGE
    echo "<div class='container' >";  
    echo "<div class='row'>";
    //https://getbootstrap.com/docs/4.0/utilities/display/
    echo "<div class='col-md-2 d-none d-lg-block'  style='background-color:#FFF'>"; //d-none d-lg-block= hidden on mobile , small devices
//    AddR
//    echo AddBadges(true);
 
/*
//    echo "<br>Exercises: " . $_SESSION['EXERCISE_PERSENTAGE'];
    echo "<br>";
//    echo xxxRANKINGxxx . $_SESSION['rankings'][$_SESSION['USER_LEVEL']];
    echo $_SESSION['rankings'][$_SESSION['USER_LEVEL']];
    echo "<br>";
    echo "<h3><img src='img/xp_star7.png' style='width:40px'> " . $_SESSION['xp_user'] . " / " . $_SESSION['xp_total'] ."</h3>";
    
    $next_level = $_SESSION['USER_LEVEL'] + 1;
    $ranking_next = GetXPRequired($_SESSION['USER_LEVEL']) . " " . GetXPRequired($next_level) . " " . $rankings[$_SESSION['USER_LEVEL']] . " - " . $rankings[$next_level] ;
    echo $ranking_next;
//    echo "Next:". $next_level . " Curr: ".$_SESSION['USER_LEVEL'];
 
//    $file = str_replace_first('xxxXPUSERxxx', , $file);
//    $file = str_replace_first('xxxXPTOTALxxx', , $file);
    
    $totaltotal = $_SESSION['compl_count'] + $_SESSION['answers_count'];
    $totalmax = TOTAL_PAGES + $_SESSION['exercises_total'];
//    $totaltotal = $_SESSION['answers_count'];
//    $totalmax = $_SESSION['exercises_total'];
    $total_persentage =  strval(intval(round($totaltotal*100 / $totalmax)));
//    $str = $str . "<br>";    
//    $str = $str . "<h3><img src='img/xp_star7.png'> 7 / 100</h3>";

    echo $str;
echo "<div class='progress'>";
echo "  <div class='progress-bar' role='progressbar' aria-valuenow='60' aria-valuemin='0' aria-valuemax='100' style='width: 60%;background-color:#FFF''></div>";
echo "  <div class='progress-bar-title'>60%</div>";
echo "</div>";
*/
//    echo "<br>Point%:" . $_SESSION['POINTS_PERSENTAGE'];
    
    //certificate info
/*    $presentage = GetCertificateCompletion();
    echo "<br><br>";
//    echo xxxCERTIFICATECOMPLETIONxxx . "<br>";
    echo "<img src='" . CDN . "img/certificate-GameDesignSchool.jpg' style='width:120px;margin-left:5px;'>";
    echo "<div class='my-progress mx-auto' style='height:20px ; width:120px; background-color:#F2F2F2'>";
    echo "<div class='rounded progress-bar progress-bar-warning ' style='width: " . $presentage . "%; color: black'><span>" . $presentage . "%</span>";
    echo "</div>"; 
    echo "</div>";*/
/*    echo "<img src='" . CDN . "img/certificate-GameDesignSchool.jpg' style='width:120px'>";
    echo "<div class='box' style='background-image: url('" . CDN . "img/certificate-GameDesignSchool.jpg'); background-size: cover; background-position: 50% 50%; background-repeat: no-repeat;'>";
    echo "<h6 style='background-color: #8bd0ef33;'>" . xxxCERTIFICATECOMPLETIONxxx . "</h6>";
    echo "<div class='my-progress mx-auto' style='height:20px ; width:120px; background-color:#F2F2F2'>";
    echo "<div class='rounded progress-bar progress-bar-warning ' style='width: " . $presentage . "%; color: black'><span>" . $presentage . "%</span></div>"; 
    echo "</div>";
    echo "</div>";
    echo "</div>";
    
    echo "<hr>";
    */
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//SIDEMENU

    echo "<br>";
    echo "<h6>" . xxxCOURSECONTENTSxxx . "</h6>";
PrintDebugTime("Bef columns 2");
 
//    echo CreateImgSrc($course['image'], true, -1, '100%');
    echo "<img  src='" . CDN . "img/" . $_SESSION['course_id'] . "/" . $course['image'] . "' width=100% style='border-radius:10px;'>"; 
    
PrintDebugTime("Bef columns 2.1");
    $completed_pages = GetPagesCompleted();
//    $course = GetCourse($_SESSION["course_id"]);
    $pages_required = $course["pages_required"];//PAGES_REQUIRED_FOR_COMPLETION;
    $total_persentage = round(100 * $completed_pages / $pages_required);//TOTAL_PAGES);
//    $percentage = round(100 * GetCourseStatus()) ;//GetCertificateCompletion();
    //$percentage = GetCertificateCompletion();
//    $file = str_replace('xxxCERTIFICATEPERCENTAGExxx', strval($presentage) . "%", $file);
//    $percentage = strval(intval($_SESSION['compl_count'] / TOTAL_PAGES));
    $str = $str . "<div class='my-progress mx-auto' style='height:15px ; width:100%; background-color:#F2F2F2'>";
    $str = $str . "<div class='rounded progress-bar ' style='width: " . $total_persentage. "%; color: black'>";
    $str = $str . "<span class='text-center' align='center'>" . $total_persentage . "%</span>"; 
    $str = $str . "</div>";
    $str = $str . "</div>";
    echo $str;
//    echo "<br>";
PrintDebugTime("Bef columns 3.2");
    
    echo "<font size='1'>"; 
//CREATE SIDEMENU
    echo "<div style='margin-top:16px;margin-bottom:12px;'><a href='home.php?course=". $_SESSION["course_id"] ."' style='color:black;padding-right: 5px;padding-left: 5px;'> <img src='" . CDN . "img/icons5/house-fill.svg' width='12' height='12' class='filter-icon'>" . lan_home . "</a></div>";
PrintDebugTime("Bef columns 3.3");
    HandleMenu($_SESSION['loginname'], $_SERVER['DOCUMENT_ROOT'] . '/page/sidemenu.html', "xp_sidemenu", $page_id);
//    HandleMenu($_SESSION['fname'], 'sidemenu2.html', "sidemenu2", $page_id);
PrintDebugTime("Columns Menu");

    echo "</font>";
    echo "</div>";
    //echo $_SESSION['fname'] . $_SESSION['user_id'] . $_SESSION['member'];
     

    echo "<div class='col-md-9' style='background-color:#FFF;margin-left:15px'>";


//    echo "<div class='container mx-xl-5  '>"; //p-5
    
//    echo "<br><div class='mx-sm-5 '>"; //p-5

/*////////////////////////////////////////////////////////////////////////////////////////////////////////////
//BREADCRUMS
//    CreateBreadcrums();
    CreateBreadcrums2($page);

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CREATE TABS
//    CreateTabs1($conn, $page['parent_id'], $page_id);
    CreateTabs2($page['parent_id'], $page_id);
*/
    

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//PAGE COMPLETE STATUS
/*
    $sql = "SELECT *  ";
    $sql = $sql . " FROM completed WHERE  page = '"  . $page_id . "' AND  user_id = "  . $_SESSION['user_id'] ;
    //echo "HERE: " . $sql;
    $result_completed = $conn->query($sql);
    echo "<div class='container  '>";
    if ($result_completed->num_rows > 0)   
    {
//        <span class='glyphicon glyphicon-ok' style='color:#008455'></span>  Press completed at end of page to mark it completed.
        echo "<i class='fa fa-check-square-o' aria-hidden='true' style='color:#008455'> </i> ";
        echo lan_alreadycompleted'];
//        echo "<a href='/page.php?page=" . $page_id . "&uncompleted=" . $page_id . "'>" . lan_alreadycompleted'] . "</a>";        
                echo "<br>";
    }
    else
    {
        echo "<i class='fa fa-square-o' aria-hidden='true' style='color:#008455'> </i> <a href='/page.php?page=" . $page_id . "&completed=" . $page_id . "'>" . lan_complete'] . "</a>";        
        echo "<br>";
    }
    echo "</div>";
*/
    
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//ADD TITLE w READTIME
//        $_SESSION['read_time'][$row['page_name']] += $row[read_time];

    echo "<br>";
//    $compl = GetCompl();
//    $xp_collected = $_SESSION['xp_page_sections'][$page_id] + $_SESSION['xp_page_exercises'][$page_id];
//    if ($xp_collected == $_SESSION['xp_page_max'][$page_id])
    $str = GetPageStatus($page_id, true, 44);
//        $completed = $_SESSION['compllist'][$page_id];
/*    if ($_SESSION['xp_page_user'][$page_id] == $_SESSION['xp_page_max'][$page_id])    
        $str = $str . "    <img src='img/icons5/star-fill.svg' alt='' width='44' height='44' class='filter-icon-black' title='" . SITENAME . "'> ";//"  <i class='fa fa-check-square-o' aria-hidden='true' style='color:#008455'> </i> ";
    else
    if ($_SESSION['xp_page_user'][$page_id] > 0)
        $str = $str . "    <img src='img/icons5/star-half.svg' alt='' width='44' height='44' class='filter-icon-black' title='" . SITENAME . "'> ";//"  <i class='fa fa-check-square-o' aria-hidden='true' style='color:#008455'> </i> ";
    else
        $str = $str . "    <img src='img/icons5/star.svg' alt='' width='44' height='44' class='filter-icon-black' title='" . SITENAME . "'> ";//"  <i class='fa fa-check-square-o' aria-hidden='true' style='color:#008455'> </i> ";
*/
    echo "<h6>" . $course['course_name'] . " / " . $parent['parent_name'] . "</h6>";
    echo "<h1 style='margin-bottom: 0px;'>" . $str . $page['title'] . " </h1>";// . strval(ceil($_SESSION['read_time'][$page_id])) . " mins read and " . $_SESSION['exercise_time'][$page_id] . " mins for exercises";
    
/*    if (strpos($compl, ",".$page_id.","))
    {
        $xp_collected = $_SESSION['xp_page_sections'][$page_id] + $_SESSION['xp_page_exercises'][$page_id];
        $_SESSION['xp_page_max'][$page_id];
        echo "<h1 style='margin-bottom: 0px;'>" . "<img src='img/icons5/check-box.svg' alt='' width='44' height='44' class='filter-icon-black' title='" . SITENAME . "'> " . $page['title'] . " </h1>";// . strval(ceil($_SESSION['read_time'][$page_id])) . " mins read and " . $_SESSION['exercise_time'][$page_id] . " mins for exercises";
        //xp $xp_collected = $_SESSION['xp_page_sections'][$page_id] + $_SESSION['xp_page_exercises'][$page_id];
        //xp echo "<h3><img src='img/xp_star7.png' style='width:60px;'> " . $xp_collected. " / " . $_SESSION['xp_page_max'][$page_id] . " "  . xxxCOLLECTEDxxx . "</h3>";
    }
    else
    {
        echo "<h1 style='margin-bottom: 0px;'>" . $page['title'] ." </h1>";// . "  " . strval(ceil($_SESSION['read_time'][$page_id])) . " mins read and " . $_SESSION['exercise_time'][$page_id] . " mins for exercises";        
        //xp echo "<h3><img src='img/xp_star7.png'style='width:60px'> +" . $_SESSION['xp_page_max'][$page_id] . " " . xxxAVAILABLExxx . "</h3>";
    }
*/ 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//ADD IMAGE
    
    //echo "<h2>" . $_SESSION["course_id"] . "</h2>";
    $file = file_get_contents('top_image.html'); 
    $file = str_replace_first('xxxCDNxxx', CDN, $file);
    if ($_SESSION["course_id"] == 'gdg' || $_SESSION['course_id'] == 'gdg1' || $_SESSION['course_id'] == 'gdg2')        
        $file = str_replace_first('xxxIMAGExxx', "<img  src=" . CDN ."". $page['image'] . " class='img-fluid w-100 curved  lazyload' alt='". $page["header"] . "'>", $file);
    else 
    {
//        $file = str_replace_first('xxxIMAGExxx', "<img  src=" . CDN ."". $page['image'] . " class='img-fluid w-100  lazyload' alt='". $page["header"] . "'>", $file);
        if ($page['image'] != "")//
        {
            $img = "<img class='curved' src='" . CDN . "img/" . $_SESSION['course_id'] . "/" . $page["image"] . "' width=100%>"; 
            if ($preview == 1)
            {
                $preview_img = "<img class='curved' src='" . UPLOAD_URL . "/uploads/" . $_SESSION['course_id'] . "/" . $page["image"] . "' width=10%>"; 
                echo "This is shown here only in preview for caching purposes." . $preview_img;
            }
                
    //        $file = str_replace_first('xxxIMAGExxx', CreateImgSrc($page['image'], true, -1, "100%"), $file);
        }
        else
        {
            $img = "<img class='curved' src='" . CDN . "img/" . $_SESSION['course_id'] . "/" . $course["image"] . "' width=100%>"; 
//            $image_str =  "<img src='" . CDN . "img/" . $_SESSION['course_id'] . "/" . $course['image'] . "' width=100%>"; 
        }
        $file = str_replace_first('xxxIMAGExxx', $img, $file);
    }
    echo $file;            

//        $file = str_replace_first('xxxIMAGExxx', "img/" . $page['image'], $file);

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//AFTER THIS PAGE
PrintDebugTime("Part 1");

//echo "<body class=mx-sm-5 p-5'>"
    echo "<div class='container ' >"; 
    echo "<br>";
    echo "<font size='2'>".lan_afterpage;
    echo "</br>";
    echo $page['after'] . "</font>";
    echo "</div>";
    echo "</br>";

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//SHOW SUB
//
        ShowSubscribeIfNeeded($_SESSION['course_id']);
    
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//ADD BADGES
//now in home page
//    AddBadges();      

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//ADD CANVASGRID
//    echo $page['canvas_index'];
    if ($page['canvas_index'] == 1)
    {
        $file = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/canvas/canvasgrid.html'); 
        $file = HandleCanvas2($file);
        $file = HandleCanvasActive($file, $page_id);

        echo $file;
    }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//PAGE SECTIONS

/*    
    $sql = "SELECT type, sort_id, header, data, image as section_image ";
    $sql = $sql . " FROM section WHERE page_name = '"  . $page_id . "'";
    $sql = $sql . " order by sort_id ";
    
    $result = $conn->query($sql);
    if ($result->num_rows == 0) 
        die (lan_page_not_found']);
//        die("Page not found...");

//    echo "/".$result->num_rows."/";

//    CacheSections();
//                CacheCompl();
    while($row = $result->fetch_assoc()) 
*/        
    $result = GetSections($page_id);
    $all_exercises_completed = true;
    $status = "";
    $video_count = 1;
    foreach ($result as $row) 
    {
        $file = "";
//        echo "<h6>" .   $row['type'] . "imagefile: " , $row['image'] . "</h6>";
        if ($row['type'] == "basic")
        {
PrintDebugTime("Part 2 Basic");
            $file = file_get_contents('basic.html'); 
//            $file = str_replace_first('xxxREADTIMExxx',$row['read_time'] . " mins ", $file);
            
            /*if ($_SESSION["course_id"] == 'gdg')
                if ($row['image'] != "")
                {
    //                $image_str = "<img src='" . CDN . "img/xxxIMAGExxx' alt='xxxTITLExxx' class=' rounded' height=300>";
                    $image_str = CDN . "img/xxxIMAGExxx";
                    $image_str = str_replace('xxxIMAGExxx',$row['image'], $image_str);    
                    $image_str = str_replace('xxxTITLExxx',$row['title'], $image_str);    
                    $file = str_replace_first('xxxIMAGExxx', $image_str, $file);
                }
                else
                    $file = str_replace_first('xxxIMAGExxx', "", $file);*/
//            echo "<br>";
//xp            $status = $status . " +1<img src='img/xp_star7.png' style='width:40px;'> " . $row['header'] . "<br>";
            //echo $file;
        }
        if ($row['type'] == 'left')
        {
PrintDebugTime("Part 2 Left");
            $file = file_get_contents('left.html');
            //$file = str_replace_first('xxxCDNxxx', CDN, $file);
//xp            $file = str_replace('xxxHEADERxxx',$row['header'] . "<h3><img src='img/xp_star7.png' style='width:40px;'> +1</h3>", $file);
//            $file = str_replace_first('xxxREADTIMExxx', $row['read_time'] . " mins ", $file);
//            if ($_SESSION["course_id"] == 'gdg')
//                $file = str_replace_first('xxxIMAGExxx',$row['image'], $file);
            //echo $file;
//xp            $status = $status . " +1<img src='img/xp_star7.png' style='width:40px;'> " . $row['header'] . "<br>";
        }
        if ($row['type'] == "right")
        {
PrintDebugTime("Part 2 Right");
            $file = file_get_contents('right.html');
            //$file = str_replace_first('xxxCDNxxx', CDN, $file);
//xp            $file = str_replace('xxxHEADERxxx',$row['header'] . "<h3><img src='img/xp_star7.png' style='width:40px;'> +1</h3>", $file);
//            $file = str_replace_first('xxxREADTIMExxx',$row['read_time'] . " mins ", $file);
//            if ($_SESSION["course_id"] == 'gdg')
//                $file = str_replace_first('xxxIMAGExxx',$row['image'], $file);
            //echo $file;
//xp            $status = $status . " +1<img src='img/xp_star7.png' style='width:40px;'> " . $row['header'] . "<br>";
        }
        if ($row['type'] == "image")
        {
PrintDebugTime("Part 2 Image");
            $file = file_get_contents('image.html');
//            $file = str_replace_first('xxxCDNxxx', CDN, $file);
//xp            $file = str_replace_first('xxxHEADERxxx',$row['header'] . "<h3><img src='img/xp_star7.png' style='width:40px;'> +1</h3>", $file);
/*            $image_str = "<img  src='" . CDN . "img/" . $row['image'] . "' class='img-fluid lazyload' alt='" . $row['image'] . "'>";
            if ($_SESSION["course_id"] == 'gdg')
                $file = str_replace('xxxIMAGExxx', $image_str, $file);*/
            //echo "<br>";
            //echo $file;
//xp            $status = $status . " +1<img src='img/xp_star7.png' style='width:40px;'> " . $row['header'] . "<br>";
        }
        if ($row['type'] == "game")
        {
            PrintDebugTime("Part 2 Game");
            $file = AddGame($row);
            //echo $game;
        }
        if ($row['type'] == "tetris")
        {
            PrintDebugTime("Part 2 Tetris");
            $file = AddTetris($row);
            PrintDebugTime("Part 2 Tetris done");
        }
        if ($row['type'] == "video")
        {
            PrintDebugTime("Part 2 Video");
            //if (( $_SESSION['member'] >= VIDEO_MEMBERSHIP))// || ($page_id == 'ideatypes'))
            {
                if (($_SESSION["course_id"] == 'gdg1') || ($_SESSION["course_id"] == 'gdg2'))
                    $file = file_get_contents('video.html');
                else
                {
                    $file = file_get_contents('video_w_intros.html');
                    $file = str_replace('xxxCOUNTxxx', $video_count, $file);
                    $video_count = $video_count + 1;
                 }
                $file = str_replace('xxxDATAxxx', $row['data'], $file);
                $file = str_replace('xxxIMAGExxx', $row['image'], $file);
                echo "<br>";
                //echo $file;
//xp                $status = $status . " +1<img src='img/xp_star7.png' style='width:40px;'> " . $row['data'] . "<br>";
            } 
/*            else 
            {
                $str = AddVideoAvailable($row['data']);
                echo $str;
                echo "<br>";
            }*/
        }
        if ($row['type'] == "download")
        {
            PrintDebugTime("Part 2 Download");
            $file = file_get_contents('download.html');
            $file = str_replace_first('xxxCDNxxx', CDN, $file);
            //data = desc, image = file
            //changed 2025 sep
            $file = str_replace('xxxDATAxxx',$row['data'], $file);
            //$file = str_replace('xxxIMAGExxx',$row['image'], $file);
            $file = str_replace('xxxDOWNLOADFILExxx', $row['image'], $file);
/*            if ($_SESSION["course_id"] == 'gdg' || $_SESSION['course_id'] == 'gdg1' || $_SESSION['course_id'] == 'gdg2' )
            {
                $file = str_replace('xxxDATAxxx',$row['title'], $file);
                $file = str_replace('xxxIMAGExxx',$row['data'], $file);
                //$file = str_replace('xxxPLEASELOGINxxx',lan_pleaselogin, $file);
            }
            else
            {
                if ($row["data"] != '')
                {
                    $img = CDN . "img/" . $_SESSION['course_id'] . "/" . $row["data"]; 
                    $file = str_replace('xxxDATAxxx', $img, $file);
                }
                else
                    $file = str_replace('xxxDATAxxx', '', $file);
                
                $file = str_replace('xxxDOWNLOADFILExxx', $row['image'], $file);
            }*/
            echo "<br>";
//            echo $file;
//xp            $status = $status . " +1<img src='img/xp_star7.png' style='width:40px;'> " . $row['title'] . "<br>";
        }
        if ($row['type'] == "include")
        {
            PrintDebugTime("Part 2 Include");
            $file = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/page/' . $row['data']);
            if ($row['data'] == "featuregame.html")
            {
                $file = str_replace('xxxFEATUREGAMETITLExxx', xxxFEATUREGAMETITLExxx, $file);
                $file = str_replace('xxxFEATUREGAMEINSTRUCTIONSxxx', xxxFEATUREGAMEINSTRUCTIONSxxx, $file);
                $file = str_replace('xxxFEATUREGAMEBUTTON1xxx', xxxFEATUREGAMEBUTTON1xxx, $file);
                $file = str_replace('xxxFEATUREGAMEBUTTON2xxx', xxxFEATUREGAMEBUTTON2xxx, $file);
                $file = str_replace('xxxFEATUREGAMEBUTTON3xxx', xxxFEATUREGAMEBUTTON3xxx, $file);
                $file = str_replace('xxxFEATUREGAMEBUTTON4xxx', xxxFEATUREGAMEBUTTON4xxx, $file);
                $file = str_replace('xxxFEATUREGAMECORExxx', xxxFEATUREGAMECORExxx, $file);
                $file = str_replace('xxxFEATUREGAMEEXTxxx', xxxFEATUREGAMEEXTxxx, $file);
                $file = str_replace('xxxFEATUREGAMEWISHxxx', xxxFEATUREGAMEWISHxxx, $file);
                $file = str_replace('xxxFEATUREGAMEACTIONSxxx', xxxFEATUREGAMEACTIONSxxx, $file);
                $file = str_replace('xxxFEATUREGAMEBASICGAMEPLAYxxx', xxxFEATUREGAMEBASICGAMEPLAYxxx, $file);
                $file = str_replace('xxxFEATUREGAMECOPYRIGHTxxx', xxxFEATUREGAMECOPYRIGHTxxx, $file);
                
            }
        
            echo "<br>";
            //echo $file;
        }
        if ($row['type'] == "exercise")
        {
                    PrintDebugTime("Part 2 Exercise");
                    echo "<br>";
                    /*
                    $sql = "SELECT * ";
                    $sql = $sql . " FROM exercise WHERE name = '"  . $row['header'] . "'";
//                    echo $sql;

                    
                    $result2 = $conn->query($sql);
                    if ($result2->num_rows> 0) 
                    { 
                        $exercise = $result2->fetch_assoc();*/
//                        $exercise_list = "";
 
                        $exercise = GetExercise($row['header']);
                        //echo "Exercise - Sortid: -" . $row['header'] . $exercise['name'] . $exercise['sort_id'] . "-<br>";
                        $editor_access = CheckEditorAccess($_SESSION["course_id"]);
                        if ($exercise['sort_id'] == "0") 
                        {//add only the non paged ones
                            if ((($_SESSION['member'] > 0) || (($page["public"] == 1) && ($exercise['required'] == 0)))
                                || (($exercise['required'] == 1) && ($row['header'] == 'ontherock'))
                                    || ($editor_access > 0 ))
                               $file = AddExerciseNew($exercise, $row['header'], $page_id, 'exercise.html', "", true);
//                               $file = AddExercise($conn, $exercise, $row['header'], $page_id, 'exercise_xp.html');
                            else
                               $file = AddExerciseNew($exercise, $row['header'], $page_id, $_SERVER['DOCUMENT_ROOT'] . '/page/exercise_prorequired.html');

//                            echo $file;
                            //add to after list, and check if done already
                            $answer = GetAnswer($row['header']);
    //                        if (! empty($answer['answer']))  
    //                            $exercise_list = $exercise_list . "<img src='img/icons5/check-box.svg' alt='' width='16' height='16' class='filter-icon-white' title='" . SITENAME . "'> " . ucwords(strtolower($exercise['title'])) .  "<br>";
    //                        else
//                            if (($answer['answer'] == "")) && ($answer['upload_image'] == "") && (($exercise['exercise_type'] == "image") && ($_SESSION['uploads'][$name] != "")))//($result3->num_rows > 0)// &&  
                            if (($answer['answer'] == "") && ($answer['upload_image'] == ""))
                            {//page.php?page=" .$page_id . 
//                                $xp_points = $exercise['xp_amount'];
                                if ($exercise['exercise_type'] == "image") 
                                {
                                    if ($_SESSION['uploads'][$row['header']] == "")    //                            $xp_points = round($exercise['duration'] / XP_PERMINUTE);
                                    {
                                        $exercise_list = $exercise_list . "<a href='#". $row['header'] ."' style='color:white'>" . ucwords(strtoupper($exercise['title'])) .  "</a><br>";
                                        $all_exercises_completed = false;
                                    }
                                }
                                else
                                {
                                    $exercise_list = $exercise_list . "<a href='#". $row['header'] ."' style='color:white'>" . ucwords(strtoupper($exercise['title'])) .  "</a><br>";
                                    $all_exercises_completed = false;
                                }
                                
                            }
                        }
                    //}
                        
         }
        if ($row['type'] == "exercise_paged")
        {
//PrintDebugTime("Part 2 Exercise paged");
            $exercise = GetExercisePaged($row['header']);
//            echo "EXERCISE FOUND " . $exercise .$sort_id."<br>";
            $file = AddExercisePaged($page_id, $exercise, $row['header'], $sort_id, $_SERVER["DOCUMENT_ROOT"] . '/page/exercise_paged.html');
            //echo $file;
            
//            echo "<br>Looking for: " . $row['header'] . "<br>";
/*            $e = $_SESSION['exercises'][$row['header']];
            foreach($e as $row)
            {
                echo "Found: " . $row['name'] . " - " . $row['sort_id'] . " xp " . $row['xp_amount']. "<br>";
//                $xp_points = $row['xp_amount'];
                $answer = GetAnswer($row['name'], $row['sort_id']);
                if (empty($answer['answer']))  
                {//page.php?page=" .$page_id . 
//                    $xp_points = $row['xp_amount'];
                    $exercise_list = $exercise_list . "<a href='#". $row['header'] ."' style='color:white'>" . ucwords(strtoupper($exercise['title'])) . " - " . $row['title'] .  "</a><br>";
//                    $exercise_list = $exercise_list . "<a href='#". $row['header'] ."' style='color:#b1301b'>+" . $xp_points . " <img src='img/xp_star7.png' style='width:40px;'> " . ucwords(strtoupper($exercise['title'])) . " - " . $row['title'] .  "</a><br>";
                    $all_exercises_completed = false;
                }
                else
                {
//xp                    $status = $status . " +" . $row['xp_amount'] . "<img src='img/xp_star7.png' style='width:40px;'> " . ucwords(strtoupper($exercise['title'])) . " - " . $row['title'] . "<br>";  
                }
                
            }*/
        }

PrintDebugTime("Part 2 Rest start");
        $file = str_replace('xxxHEADERxxx',$row['header'], $file);
        $file = str_replace('xxxDATAxxx',$row['data'], $file);
        
//        if ($_SESSION['course_id'] === "gdg" )
        if (($_SESSION['course_id'] == 'gdg') || ($_SESSION['course_id'] == 'gdg1') || ($_SESSION['course_id'] == 'gdg2' ))
        {
            if ($row['image'] != "")
            {
                if ($row['type'] == 'image')
                    $file = str_replace_first('xxxIMAGExxx', "<img  src=" . CDN ."". $row['image'] . " class='img-fluid w-100 curved lazyload' style='width:100%;' alt='". $page['header'] . "'>", $file);
//otettu pois 100%& heihght                    $file = str_replace_first('xxxIMAGExxx', "<img  src=" . CDN ."". $row['image'] . " class='img-fluid w-100  lazyload' style='width:100%;height:100%' alt='". $page["header"] . "'>", $file);
                else
                    $file = str_replace_first('xxxIMAGExxx', "<img  src=" . CDN ."". $row['image'] . " class='img-fluid w-100 curved lazyload' style='width:240' alt='". $page['header'] . "'>", $file);
            }
            else
                    $file = str_replace_first('xxxIMAGExxx', "", $file);
        }
        else 
        {
            if ($row['image'] != "") 
            { 
                if (($row['type'] == "image") || ($row['type'] == "left") || ($row['type'] == "right"))
                    $img = "<img class='curved' src='" . CDN. "img/" . $_SESSION['course_id'] . "/" . $row["image"] ."' width='100%'>"; 
                else
                    $img = "<img class='curved' src='" . CDN . "img/" . $_SESSION['course_id'] . "/" . $row["image"] ."' height='240px'>"; 
                $file = str_replace_first('xxxIMAGExxx', $img, $file);
//                    $file = CreateImageStr($file, $row['image'], -1, '100%');
            }
            else
                    $file = str_replace_first('xxxIMAGExxx', "", $file);
/*            else
                $file = CreateImageStr($file, $row['image'], 240, -1);*/
        }
/*        if ($_SESSION["course_id"] != 'gdg')
            $file = str_replace_first('xxxIMAGExxx', CreateImgSrc($row['image'], true, -1, -1), $file);
        else {
            $image_str = "<img  src='" . CDN . "img/" . $row['image'] . "' class='img-fluid lazyload' alt='" . $row['image'] . "' height='200'>";
            if ($_SESSION["course_id"] == 'gdg')
                $file = str_replace('xxxIMAGExxx', $image_str, $file);
            
        }*/
PrintDebugTime("Part 2 Rest echo");
        echo $file;
        echo "<br>";
PrintDebugTime("Part 2 Rest done");

    }
    
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//uncomplete    
/*
    if ($uncompleted != "") 
    {
        SetCompleted($conn, $_SESSION['user_id'], $page_id, 0, "");
    }
*/   
PrintDebugTime("Part 2");
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//LATEST

    if ($_SESSION['user_id'] != '')
    {
        if ($_SESSION['latest'] != $page_id)
        {
            $_SESSION['latest'] = $page_id;
        //    $sql = "UPDATE users SET latest = '" . $page_id . "'";
        //    $sql = $sql . " WHERE user_id =  " . $_SESSION['user_id'];
            $conn = CreateConnection("vgd");
            $sql = "UPDATE access SET latest = '" . $page_id . "'";
            $sql = $sql . " WHERE user_id =  " . $_SESSION['user_id'];
            $sql = $sql . " AND course_id = '" . $_SESSION['course_id'] . "'";
        //    echo $sql;
            if (! mysqli_query($conn, $sql))
            {
                return lan_error_updatinglatest;

            }
            CloseConnection($conn);
        }
    }
PrintDebugTime("Latest done");
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//PAGE STATUS
/*    
    $file = file_get_contents('status.html');
    $file = str_replace_first('xxxCDNxxx', CDN, $file);

    $file = str_replace_first('xxxHEADERxxx',$page['title'], $file);
    $file = str_replace_first('xxxSTATUSxxx',xxxSTATUSxxx, $file);
    $file = str_replace_first('xxxCOLLECTEDxxx',xxxCOLLECTEDxxx, $file);
    $file = str_replace_first('xxxTOTALxxx',xxxTOTALxxx, $file);
    
    $file = str_replace_first('xxxSTATUSxxx', $status, $file);            
    if ($exercise_list != "") 
    {
        $str = $exercise_list ."<br>";
        $file = str_replace_first('xxxMISSINGxxx',xxxMISSINGxxx, $file);
        $file = str_replace_first('xxxEXERCISESxxx', $str, $file);            
    }
    else
    {
        $file = str_replace_first('xxxMISSINGxxx', "", $file);
        $file = str_replace_first('xxxEXERCISESxxx', "", $file);            
    }
    
    $xp_collected = $_SESSION['xp_page_sections'][$page_id] + $_SESSION['xp_page_exercises'][$page_id];
    $file = str_replace_first('xxxCOLLECTEDxxx', "<img src='img/xp_star7.png' style='width:60px;'> " . $xp_collected, $file);            
    $file = str_replace_first('xxxTOTALXPxxx', "/ " . $_SESSION['xp_page_max'][$page_id] . " ". xxxCOLLECTEDxxx, $file);            
    echo $file;
*/
//    $_SESSION['xp_page_user'][$row['page']] = $xp_collected;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//SET COMPLETED BASED ON XP AMOUNT
/*    $compl = GetCompl();
    if ($xp_collected == $_SESSION['xp_page_max'][$page_id])
    {
        if (! strpos($compl, ",".$page_id.","))
            SetCompleted($conn, $_SESSION['user_id'], $page_id, 1, "");        
    }
    else
    {
        if (strpos($compl, ",".$page_id.","))
            SetCompleted($conn, $_SESSION['user_id'], $page_id, 0, "");        
        
    }
 * 
 */
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//COMPLETED
////5fc5ed
//$colors = array('82b1ff','80d8fe','9ccc66','8bc24a','00bcd5','2196f3','689f3a','c5e1a6','aed582','9ccc66','8bc24a','80c783','a5d6a7','b9f6ca','00e676','01c853','7db343','b2ff59','cddc39','dde776','d4e056','c6ff00','aeea00');
//$colors = array('7db343','689f3a','8bc24a','2196f3');
/*$colors = array('a1c154','8ba647','8bd0ef','5fc5ed','29bbee','2a6271','133f62','d7dbde','a2a6a7','214043','ffe700','f5b10e','b1301b','ed8d1c');
//vaalea vihreä '8bc24a', //'7db343','9ccc66'
//tumma vihreä  '689f3a'
//tumma sin     '2196f3'
foreach ( $colors as $c )
{
    $file = file_get_contents('completed_total.html');
    $file = str_replace_first('xxxCDNxxx', CDN, $file);
    
    $file = str_replace_first('xxxXPUSERxxx', $_SESSION['xp_user'], $file);
    $file = str_replace_first('xxxXPTOTALxxx', $_SESSION['xp_total'], $file);
    
//    if ($all_exercises_completed)
   $file = str_replace('xxxCOLORxxx', $c, $file);
    {
        $file = str_replace_first('xxxCOMPLETEDxxx',"", $file);    
//        $file = str_replace_first('xxxCOMPLETEDxxx',"<img src='img/icons5/check-box.svg' alt='' width='16' height='16' class='filter-icon-white' title='xxxSITENAMExxx'>" .strtoupper(lan_nowcompleted), $file);    
        $file = str_replace_first('xxxICONxxx','UI_Icons_Complete.png', $file); 
        $file = str_replace_first('xxxBCKCOLORxxx','8bd0ef', $file); 
//        $file = str_replace_first('xxxBCKCOLORxxx','8bd0ef', $file); 
        
        //$file = str_replace_first('xxxBCKCOLORxxx','FFF', $file); 
        $file = str_replace_first('xxxTEXTCOLORxxx','white', $file);                
        $file = str_replace_first('xxxPAGESTATUSxxx', lan_alreadycompleted, $file);
    }
    $file = str_replace_first('xxxHEADERxxx',$page['title'], $file);
    $file = str_replace_first('xxxDATAxxx',$row['data'], $file);
    $file = str_replace('xxxSITENAMExxx', SITENAME, $file);
    $file = str_replace_first('xxxAFTERTITLExxx', lan_afterpage, $file);

    //uncompleted exercises
    if ($exercise_list != "") 
    {
        $str = xxxEXERCISESTATUSxxx . "<br>" . $exercise_list ."<br>";
        $file = str_replace_first('xxxEXERCISESxxx', $str, $file);            
    }
    else
        $file = str_replace_first('xxxEXERCISESxxx', "", $file);            
    
    //show after list
    $after = $page['after'];
    $after = $after;
    $file = str_replace_first('xxxAFTERxxx', $after, $file);
    
    //skill completion
    //$percentage_id = $page['parent_id'] . "_PARENT_COMPLETED";
    //$percentage = $_SESSION[$percentage_id];
    //$file = str_replace('xxxTOTALxxx', strval($percentage) . "%", $file);
    //$file = str_replace_first('xxxYOUHAVECOMPLETEDxxx', xxxYOUHAVECOMPLETEDxxx, $file);

    //total completion    
    $file = str_replace('xxxTOTALxxx', strval($total_persentage) . "%", $file);
    $file = str_replace_first('xxxYOUHAVECOMPLETEDxxx', xxxTOTALCOMPLETEDxxx, $file);
    $file = str_replace_first('xxxGUIDExxx', xxxGUIDE3xxx, $file);
    if ($total_persentage < 1)
        $file = str_replace('xxxTOTALCOLORxxx', "black", $file);
    else
        $file = str_replace('xxxTOTALCOLORxxx', "white", $file);

    echo "<br>";
    echo $file;
    echo "<br>"; 
}
*/    
PrintDebugTime("Part 3 Bef Completed");
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//COMPLETED SECTION
    
    $file = file_get_contents('completed.html');
//    if ($all_exercises_completed)
//    else
//    {
//        $file = str_replace_first('xxxICONxxx','UI_Icons_Uncomplete.png', $file);    
//    }
    $page_status = GetPageStatus($page_id, false, -1, "white");
//we got this already earlier    $completed_pages = GetPagesCompleted();
//we have this too from earlier    $pages_required = $course["pages_required"];//PAGES_REQUIRED_FOR_COMPLETION;
    if ($page_status == PAGE_COMPLETED)
    {
        $str = GetPageStatus($page_id, true, 44, "white");
        $file = str_replace_first('xxxHEADERxxx',$str .  " " . $page['title'], $file);
        $file = str_replace_first('xxxCOMPLETEDBCKCOLORxxx', '#8bd0ef', $file);        
        $file = str_replace_first('xxxCOMPLETEDxxx', strtoupper(lan_nowcompleted), $file);    
        $file = str_replace_first('xxxHOWTOCOMPLETExxx', "", $file);
        $file = str_replace_first('xxxGUIDExxx', "You have completed " . $completed_pages . " of the " . $pages_required . " pages.<br>" , $file);
        $file = str_replace_first('xxxICONxxx','UI_Icons_Complete_blue2.png', $file);    
        $after = $page['after'];
        $after = str_replace('<li>', "<img src='img/icons5/check-box.svg' alt='' width='16' height='16' class='filter-icon-white' title='" . SITENAME . "'> ", $after);
        $after = str_replace('</li>', "<br>", $after);
    //    $after = str_replace('</ul>', $exercise_list . "</ul>", $after);
        $file = str_replace_first('xxxAFTERTITLExxx', lan_afterpage, $file);
        $file = str_replace_first('xxxAFTERxxx', $after, $file);

        $bar = "<div class='progress' style='height:40px ; background-color:#F2F2F2; '>";
        $bar = $bar . "<div class='progress-bar' style='width: " . xxxTOTALxxx . "; background-color:#133f62;border-radius: 0px;'><span style='text-shadow: 2px 1px 0 black;'>" . xxxTOTALxxx . "<img class='" . xxxSTARCOLORxxx . "' src='img/icons5/star-fill.svg'></span></div>";
        $bar = $bar . "</div>";
        $file = str_replace_first('xxxEXERCISESxxx', "", $file);            
    }
    else
    {
        $str = GetPageStatus($page_id, true, 44, "black");
        $file = str_replace_first('xxxHEADERxxx', "", $file);
        $file = str_replace_first('xxxCOMPLETEDBCKCOLORxxx', '#ed8d1c', $file);        
        $file = str_replace_first('xxxCOMPLETEDxxx', strtoupper(lan_notyetcompleted), $file);    
        $file = str_replace_first('xxxHOWTOCOMPLETExxx', xxxHOWTOCOMPLETE1xxx, $file);
        
        $file = str_replace_first('xxxGUIDExxx', "You have completed " . $completed_pages . " of the " . $pages_required . " pages.<br>" . xxxHOWTOCOMPLETE2xxx, $file);
        $file = str_replace_first('xxxICONxxx','UI_Icons_Uncomplete.png', $file);    
        $file = str_replace_first('xxxAFTERTITLExxx', "", $file);
        $file = str_replace_first('xxxAFTERxxx', "", $file);
        if ($exercise_list != "") 
//            $file = str_replace_first('xxxEXERCISESxxx', "", $file);            
            $file = str_replace_first('xxxEXERCISESxxx', "<h5><u>" . $exercise_list . "</u></h5><br>", $file);            
        else
            $file = str_replace_first('xxxEXERCISESxxx', "", $file);            
    }
    $file = str_replace_first('xxxDATAxxx',$row['data'], $file);
    $file = str_replace('xxxSITENAMExxx', SITENAME, $file);
    //create after list
    
//    $file = str_replace('xxxSELECTCONTINUExxx', lan_selectcontinue'], $file);
//    $file = str_replace('xxxSELECTCOMPLETExxx', lan_selectcomplete'], $file);
    $file = str_replace_first('xxxSELECTCONTINUExxx', "", $file);
    $file = str_replace_first('xxxSELECTCOMPLETExxx', "", $file);
    

//    <i class='fa xxxCHECKBOXxxx' aria-hidden='true' style='color:#ffffff'> </i> <a href='/page.php?page=xxxCOMPLETEDPAGExxx&xxxCOMPLETEACTIONxxx=xxxCOMPLETEDPAGExxx' style='color:#ffffff'> xxxCOMPLETETEXTxxx </a>
//    $file = str_replace('xxxCONTINUExxx', lan_continue'], $file);
    $file = str_replace('xxxLINKxxx', $page['next'], $file);       
    $file = str_replace_first('xxxCONTINUExxx', xxxNEXTxxx . ": " . $next['title'], $file);
 
//    $total = $_SESSION['compl_count'];//$result_t->fetch_assoc();
//    $total_pages = TOTAL_PAGES; //CHECK FROM DATABASE!
//    $presentage =  strval(intval($total*100 / $total_pages));

    //skill completion
    $percentage_id = $page['parent_id'] . "_PARENT_COMPLETED";
    $percentage = $_SESSION[$percentage_id];
    //$file = str_replace('xxxTOTALxxx', strval($percentage) . "%", $file);
    //$file = str_replace_first('xxxYOUHAVECOMPLETEDxxx', xxxYOUHAVECOMPLETEDxxx, $file);

    //total completion    
//    $total_persentage = GetCourseStatus();//GetCertificateCompletion();
//this has been counted alreadt    $total_persentage = round(100 * $completed_pages / $pages_required);//TOTAL_PAGES);
//    $total_persentage = round(100 * GetCourseStatus()) ;//GetCertificateCompletion();
    //$total_persentage = round(100 * GetPagesCompleted() / PAGES_REQUIRED_FOR_COMPLETION);//TOTAL_PAGES);
    $file = str_replace('xxxTOTALxxx', strval($total_persentage) . "% ", $file);
    if ($total_persentage < 8)
        $file = str_replace_first('xxxSTARCOLORxxx',  'filter-icon', $file);
    else
        $file = str_replace_first('xxxSTARCOLORxxx',  'filter-icon-white', $file);
        
    $file = str_replace_first('xxxYOUHAVECOMPLETEDxxx',  xxxTOTALCOMPLETEDxxx, $file);
    /*    if (GetPageStatus($page_id) == PAGE_COMPLETED)
    {    
    }
    else
    {
    }*/
 // "<img src='img/icons5/star-fill.svg'>"
/*duplicate    $_SESSION['latest'] = $page_id;
//    $sql = "UPDATE users SET latest = '" . $page_id . "'";
//    $sql = $sql . " WHERE user_id =  " . $_SESSION['user_id'];
    $sql = "UPDATE access SET latest = '" . $page_id . "'";
    $sql = $sql . " WHERE user_id =  " . $_SESSION['user_id'];
    $sql = $sql . " AND course_id = '" . $_SESSION['course_id'] . "'";
//    echo $sql;
    if (! mysqli_query($conn, $sql))
    {
        return lan_error_updatinglatest;
         
    }
 * 
 */
/*
PrintDebugTime("Part 4 Inside Completed");
//    echo "Completed:" . $page_id;
    $file = str_replace('xxxCOMPLETEDPAGExxx', $page_id, $file);
    if ($completed != "")
    {
PrintDebugTime("Part 4 Inside Completed 1.1");
        SaveStats($_SESSION['user_id'], $page_id, "completed", $_SERVER['HTTP_REFERER']);
        //check if we need to insert or update
        $sql = "SELECT * FROM completed WHERE user_id = '" . $_SESSION['user_id'] . "' AND page = '" . $completed . "'";
        $sql = $sql . " AND course_id = '" . $_SESSION['course_id'] . "' ";
        //echo $sql;
        $result_completed = $conn->query($sql);
PrintDebugTime("Part 4 Inside Completed 1.2");
        if ($result_completed->num_rows > 0)   
//        if (strpos($compl, ",".$page_id.","))
        {
            $sql = " UPDATE completed SET uncompleted = NULL WHERE user_id = '" . $_SESSION['user_id'] . "' AND page = '" . $completed . "'";
            $sql = $sql . " AND course_id = '" . $_SESSION['course_id'] . "'";
        }
        else
        {
            $sql = " INSERT INTO completed (user_id, course_id, page, completed) ";
            $sql = $sql . " VALUES ( "; 
            $sql = $sql .  "'" . $_SESSION['user_id'] . "','" . $_SESSION['course_id'] . "','" . $completed .  "',  NOW())";
        }
PrintDebugTime("Part 4 Inside Completed 1.3");
        //echo $sql;
        if ( mysqli_query($conn, $sql))
        {
                //$id = mysqli_insert_id($conn);
                CacheCompl($conn);
//                header('Location: '.$_SERVER['REQUEST_URI']);
                //echo $id . "<br>"; 
                echo "<script language=\"javascript\" type=\"text/javascript\">";
                echo "window.location=\"page.php?page=". $page_id . "\"";
                echo "</script>";
                echo lan_completed_saved. "<br>";
        } 
        else 
        {
            echo $conn->error;
                if ($conn->errno != 1062) //duplicate entry
                    return lan_error_storingprogress;
//                    return "[{\"Result\":\"Error\", \"Code\":109, \"Msg\":\"Error stroring progress.\"}]";
                   $id = -1;
                //HandleError($conn, $sql, "");//die("Error: " . $conn->error);
        }
    }
 */ 
    
    echo "<br>";
    echo $file;
    echo "<br>";
    
PrintDebugTime("Part 4 Inside Completed 1.4");
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//SET COMPLETED
    if (($_SESSION['member'] > 0) || (($_SESSION['member'] < 1) && ($page['public'] == 1)))
    {
        if ($_SESSION['user_id'] != "")
        {
            $completed = $_SESSION['page_completed'][$page_id];
            if (! $completed)
            {
                $conn = CreateConnection("vgd");
                SetCompleted($conn, $_SESSION['user_id'], $page_id, 1, "");        
                CloseConnection($conn);
    //not needed anymore                        CacheCompl($conn);
    //not needed anymore            CacheStats();
            }
        }
    }
//    echo "Completed:" . $page_id;
//    $file = str_replace('xxxCOMPLETEDPAGExxx', $page_id, $file);
/*    if (($completed != ""))// || (($all_exercises_completed) && ((! strpos($compl, ",".$page_id.",")))))
    {
        SaveStats($_SESSION['user_id'], $page_id, "completed", $_SERVER['HTTP_REFERER']);
        //check if we need to insert or update
        $compl = GetCompl();
        //$sql = "SELECT * FROM completed WHERE user_id = '" . $_SESSION['user_id'] . "' AND page = '" . $completed . "'";
        //echo $sql;
        //$result_completed = $conn->query($sql);
        //if ($result_completed->num_rows > 0)   
        if (strpos($compl, ",".$page_id.","))
        {
            $sql = " UPDATE completed SET uncompleted = NULL WHERE user_id = '" . $_SESSION['user_id'] . "' AND page = '" . $completed . "'";
        }
        else
        {
            $sql = " INSERT INTO completed (user_id, page, completed) ";
            $sql = $sql . " VALUES ( "; 
            $sql = $sql .  "'" . $_SESSION['user_id'] . "','" . $completed .  "',  NOW())";
        }
        //echo $sql;
        if ( mysqli_query($conn, $sql))
        {
                //$id = mysqli_insert_id($conn);
                CacheCompl();
//                header('Location: '.$_SERVER['REQUEST_URI']);
                //echo $id . "<br>"; 
                echo "<script language=\"javascript\" type=\"text/javascript\">";
                echo "window.location=\"page.php?page=". $page_id . "\"";
                echo "</script>";
                echo lan_completed_saved. "<br>";
        } 
        else 
        {
            echo $conn->error;
                if ($conn->errno != 1062) //duplicate entry
                    return lan_error_storingprogress;
//                    return "[{\"Result\":\"Error\", \"Code\":109, \"Msg\":\"Error stroring progress.\"}]";
                   $id = -1;
                //HandleError($conn, $sql, "");//die("Error: " . $conn->error);
        }
    }
*/  
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//SHOW SUB
//
        ShowSubscribeIfNeeded($_SESSION['course_id']);
        
    
PrintDebugTime("Part 5 Completed Done");  
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//NOWONLY or NEXT BUTTON
//
/*    if (( $_SESSION['member'] != 1) && (strcmp($page_id, "learn") == 0))
    {
       AddGoPro();
    } 
    else*/
    { 
        
        $file = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/page/nextbutton.html');
        $next = GetNextPage($page_id);
        $compl = "";//GetCompl();
        
        if (($_SESSION['user_id'] > 0) && ($_SESSION['member'] > 0))
    //    if ($_SESSION['loginname'] != '') 
        {
            $file = str_replace_first('xxxOFFERxxx', "", $file);        
        }
        else 
        { 
            $file = str_replace_first('xxxOFFERxxx', "<a href='/payment/pricing.php?partner=INTROSALE'  class='btn btn-danger w-100'><h5  style='color:white'>Get your discount offer </h5></a><br><br>", $file);                
        }
        //echo "<br>Next "  . $next['page_id'] . $next['page_name'];
        $return_page = "";
        if ($next == "")
        {
                $file = str_replace_first('xxxCONTINUEBUTTONxxx', "<a href='home.php?course=" . $_SESSION['course_id'] . "' class='btn btn-primary w-100' ><b><h1  style='color:white'>" . lan_home . "</h1></b></a>", $file);
                $file = str_replace_first('xxxNEXTTEXTxxx', "This is the last page of the course.", $file);
//                $next = $page;
                $return_page = "&return_page=home";
        }
        else 
        {
                $file = str_replace_first('xxxNEXTTEXTxxx', xxxNEXTxxx . ": " . $next['title'], $file);
                if ($all_exercises_completed)
                {
                    if (GetPageStatus($page_id) == PAGE_COMPLETED)
        //            if (strpos($compl, ",".$page_id.","))
                        $file = str_replace_first('xxxPAGESTATUSxxx', lan_alreadycompleted, $file);
                    else
                        $file = str_replace_first('xxxPAGESTATUSxxx', lan_readyforcompletion, $file);

                    if (($page_id == "learn") && ($_SESSION['member'] < 1))
                        $file = str_replace_first('xxxCONTINUEBUTTONxxx', "<a href='/payment/pricing.php?button="  . $page_id . "&endoffree=1' class='btn btn-primary w-100' ><b><h1 style='color:white'>" . lan_continue . "</h1></b></a>", $file);
                    else
                        $file = str_replace_first('xxxCONTINUEBUTTONxxx', "<a href='/page.php?page=" . $next['page_name'] . "&completed="  . $page_id . $return_page . "' class='btn btn-primary w-100' ><b><h1 style='color:white'>" . lan_continue . "</h1></b></a>", $file);
                    $file = str_replace_first('xxxEXTRAACTIONxxx', "", $file);
                }
                else
                //marked as completed
        //        if (strpos($compl, ",".$page_id.","))
                if (GetPageStatus($page_id) == PAGE_COMPLETED)
                {                    
                    $file = str_replace_first('xxxPAGESTATUSxxx', lan_alreadycompleted, $file);
                    if (($page_id == "learn") && ($_SESSION['member'] < 1))
                        $file = str_replace_first('xxxCONTINUEBUTTONxxx', "<a href='/payment/pricing.php?button="  . $page_id . "&endoffree=1' class='btn btn-primary w-100' ><b><h1 style='color:white'>" . lan_continue . "</h1></b></a>", $file);
                    else
                        $file = str_replace_first('xxxCONTINUEBUTTONxxx', "<a href='/page.php?page=" . $next['page_name']  . $return_page . "' class='btn  btn-primary  w-100' ><b><h1 style='color:white'>" . lan_continue . "</h1></b></a>", $file);
                    $file = str_replace_first('xxxEXTRAACTIONxxx', "<a href='/page.php?page=" . $page_id . "&uncompleted="  . $page_id . "' >" . lan_uncompleted_button . "</a>", $file);
                    //$file = str_replace_first('xxxEXTRAACTIONxxx', "<a href='/page.php?page=" . $page['next'] . "' class='text-white' >" . lan_continuenocompletion . "</a>", $file);

                } 
                else
                {                    
                    $file = str_replace_first('xxxPAGESTATUSxxx', lan_missingexec, $file);
                    if (($page_id == "learn") && ($_SESSION['member'] < 1))
                        $file = str_replace_first('xxxCONTINUEBUTTONxxx', "<a href='/payment/pricing.php?button="  . $page_id . "&endoffree=1' class='btn btn-primary w-100' ><b><h1 style='color:white'>" . lan_continue . "</h1></b></a>", $file);
                    else //style='background-color:#F2F2F2'
                        $file = str_replace_first('xxxCONTINUEBUTTONxxx', "<a href='/page.php?page=" . $next['page_name'] . "&completed="  . $page_id . $return_page . "' class='btn btn-primary w-100' ><b><h1 style='color:white'>" . lan_continue . "</h1></b></a>", $file);

                    $file = str_replace_first('xxxEXTRAACTIONxxx', "<a href='/page.php?page=" . $page_id . "&completed="  . $page_id . "' >" . lan_completedcontinue . "</a>", $file);

                }     
        }
        echo "<br>";
        echo $file;
    }//time to go pro
    //
PrintDebugTime("Part 6 Next Done");
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//RATING
    $rating = $_SESSION['ratings'][$_SESSION['course_id']][$page_id];
/*    if ($_SESSION['user_id'] == 2)
    {
        echo "RATING: ";
        var_dump($_SESSION['rating']);
    }*/
    if ($new_rating != '') 
    {
        $conn = CreateConnection("vgd");
        if ($rating != '')
        {
            $sql = "UPDATE rating SET rating = " . $new_rating . " WHERE row_id = " . $rating['row_id'];
        }
        else
        {
            $sql = "INSERT INTO rating (user_id, course_id, page_id, rating) VALUES (" . $_SESSION['user_id'] . ",'" . $_SESSION['course_id'] . "','" . $page_id . "'," . $new_rating . ")";
        }
//        echo $sql;
        if ( mysqli_query($conn, $sql))
        {
            CacheRatings();
            $rating = $_SESSION['ratings'][$_SESSION['course_id']][$page_id];
            echo "<h6 align='center'>Your rating has been saved. Thank you!</h6>" . "<br>";
        }  
        CloseConnection($conn);
/*        $ratings = GetRatings();
        echo "ratings:" . $ratings . "<br>" . $page_id . "<br>";
        $to_find = ",".$page_id.",";
//        echo $to_find . "<br>";
//        echo "strpos:" . strpos($ratings, $to_find) . "<br>";
        $pos = strpos($ratings, $to_find);
        $rating_nro = substr($ratings, $pos, strlen($to_find)+1);
        $rating_nro = substr($rating_nro, -1);
//        echo "rating_nro:". $rating_nro;
        $conn = CreateConnection("vgd");
        if (strpos($ratings, $to_find))
        {
            $sql = "SELECT row_id FROM rating WHERE user_id = " . $_SESSION['user_id'] . " AND page_id = '" . $page_id . "'";
            $sql = $sql . " AND course_id = '" . $_SESSION['course_id'] . "' ";
//            echo $sql;
            $result = $conn->query($sql);
            if ($result->num_rows > 0) 
            {
                $rating_row = $result->fetch_assoc();
                $rating_row_id = $rating_row['row_id'];
                $sql = "UPDATE rating SET rating = " . $rating . " WHERE row_id = " . $rating_row_id;
            }
            SaveStats($_SESSION['user_id'], $page_id, "addrating", $_SERVER['HTTP_REFERER']);
        }
        else 
        {
            $sql = "INSERT INTO rating (user_id, course_id, page_id, rating) VALUES (" . $_SESSION['user_id'] . ",'" . $_SESSION['course_id'] . "','" . $page_id . "'," . $rating . ")";
            SaveStats($_SESSION['user_id'], $page_id, "addrating", $_SERVER['HTTP_REFERER']);            
            $_SESSION['badge_ratinggiven'] = true;
        }*/
 //       echo $sql;
/*        if ( mysqli_query($conn, $sql))
        {
            CacheRatings();
            $rating = $_SESSION['ratings'][$_SESSION['course_id']][$page_id];
            echo "Your rating has been saved. Thank you!" . "<br>";
        }  
        CloseConnection($conn);
 * 
 */
    }
    if ($_SESSION['user_id'] == 2)
    {
//        echo "RATING: " . $rating['rating'];
    }
    AddRating($rating, $page_id);   
    echo "<h6 align='center'><a href='contactus.php?title=report' style='font-size:14px;'>Report an issue</a></h6>";
    
    
    echo "</div>";//col
    echo "</div>";//row
    echo "</div>";//container
    echo "</div>"; //page margins
    echo "</div>"; //container

    
    //goto upsel, do it like this to save the progress of the page
    if (($page_id == "learn") && ($_SESSION['member'] < 1))
    {
            echo "<script language=\"javascript\" type=\"text/javascript\">";
            echo "window.location='/payment/pricing.php?button=learnpage&endoffree=1'";
//            echo "window.location='offer.php?button=uniquepage'";
            echo "</script>";            
    }   

    HandleCookies("page.php?page=" . $page_id);//$_SESSION['user_id'],  $page_id);
//    echo $crums;
//    $ini = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . "/../config/app.ini");    
//    echo "ini : " . $ini['SITENAME'];

    echo "<br>";
    echo $tabs;
    
    //this is ugly, but makes the menu button appear on the pages (for some reason doesn't work on this)
    //$file = file_get_contents('menu_style.html');
    //echo $file;
    
//    AddSearch();
    
PrintDebugTime("Part 7 Nexr end");
    
    AddChat();    
//    $result->free();
//    $conn->close();
//    CloseConnection($conn);

} catch ( Exception $e ) {
     
        echo "<br><br>" . lan_loginerror ;// . $e->getMessage();
        if ($_POST['email'] == "juha@hisome.co") 
        	echo "<br>". $e->getMessage();
         
    } 
 
//  <a href="#" id="scroll-top" class="scroll-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a>
?>

</body>

<?php
PrintDebugTime("Footer");
$footer = CreateFooter("page.php", $_SERVER["DOCUMENT_ROOT"] . "/footer2.html");
echo $footer;
/*echo $_SESSION['answers'] ."<br>" . $compl;
    $answers = $_SESSION['answerlist'];
    foreach ($answers as $row)
    {
        echo "<br>For - " . $row['name'];
        $e = GetExercise($row['name']);
        $s = FindExerciseFromSection($row['name']);
        echo "<br>Dura: " . $e['duration'];
        echo "<br>Page: " . $s['page_name'];
//        $_SESSION['xp_user'] += $e['duration'] / XP_PERMINUTE;
//        $_SESSION['xp_page_exercises'][$s['page_name']] += $e['duration'] / XP_PERMINUTE;
        echo "<br> XP from exercises: " . $_SESSION['xp_page_exercises']['what'];
    }
*/
PrintDebugTime("Done");
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
//var upload_server = 'https://gamedesigncanvas.org';
//https://stackoverflow.com/questions/63647653/upload-image-file-using-onclick-function-and-ajax
function SetSelectedImage(formname)
{
//    alert("SetSelectedImage");
    document.getElementById(formname).submit();
}
function Uploadfile(uploadable, upload_url, upload_name, upload_path)
{
//    alert("In Uploadfile");
    //alert(uploadable + upload_url + upload_name);
    var files = uploadable;//.files;  
//    alert(upload_name); 
//    alert(files.name);
//    alert(files.files[0]);
//    alert(files.files[0].name);
    $("#loader").css("display","block"); 
    $("#" + upload_name + "_image_text").text("Loading...");
    //var upload_files = $("#" + upload_name + "_uploadfile")[0].files;
    //var uploadable_files = uploadable.files[0];
    var fileData = new FormData();
//    fileData.append(uploadable.files[0].name, uploadable.files[0]);
//    fileData.append(uploadable_files[0].name, uploadable_files[0]);

    fileData.append('uploadfile', files.files[0]);
//    fileData.append(files.files[0].name, files.files[0]);
      //  alert('ajax' + e.target.action); 
//    alert("ajax now: "+upload_url + "-" + upload_files[0].name + "-" + upload_files[0]);
//    alert("ajax now: "+upload_url + "-" + uploadable.files[0].name + "-" + uploadable.files[0]);
    
    $.ajax({
     url: upload_url,
     method: "POST",
     type: "POST",
     data:  fileData, //new FormData(this),
      //dataType: 'json',
     contentType: false,
     cache: false,
     processData:false,
     crossDomain: true,
     success: function(response)
     { 
       var json = $.parseJSON(response);
//       alert('in scuucess' +response + json.data);
       if(response=='invalid')
       {
            // invalid file format.
            $("#err").html("Invalid File !").fadeIn();
       }
       else  
       {
            // view uploaded file.
            //alert ("in success" + upload_name);
            $("#" + upload_name + "_image").attr('src', json.data);
            $("#" + upload_name + "_uploadfile").attr('src', json.data);
            $("#" + upload_name + "_uploadfile").attr('text', json.data);
            //$("#course_image").attr('src', json.data);
            
            //$("#loader").css("display","none");
            $("#" + upload_name + "_image").css("opacity","1");
            $("#" + upload_name + "_image").removeClass('filter-icon-lightblue');
            $("#" + upload_name + "_image_text").text("Loaded!");
            $("#" + upload_name + "_image_text").css("display","none");
            $("#" + upload_name + "_uploadfile").css("display","none");

            $("#" + upload_name).text(json.data);
            $("#" + upload_name).trigger('change'); //has to be triggered manually
       } 
     },
     error: function(request, status, error) 
     {
         alert('error' + request.responseText);
         //alert('error' + error.message);
         //alert('error' + status);
          $("#err").html(e).fadeIn();
     }          
   });
    
}
</script>  
</html>