<script src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<?php

	//First Get Lesson Minimum Time Requirement
	$minimumrequirement = intval($lesson->completiontimespent);
	
	//Second Get the Lesson Time already spent from the table	
	if ($minimumrequirement > 0) {					
		$timealreadyspent = $DB->get_field_sql(
						"SELECT SUM(lessontime - starttime)
						   FROM {lesson_timer}
						  WHERE lessonid = :lessonid
							AND userid = :userid",
						array('userid' => $USER->id, 'lessonid' => $lesson->id));
		 if (!$timealreadyspent) {
			$timealreadyspent = 0;
		 }
	}
	$timealreadyspent = intval($timealreadyspent);

	 
	//echo "Time Req".$timealreadyspent."===".$minimumrequirement;
	if($timealreadyspent>=$minimumrequirement){
		//$lesson->add_message('Time requirement is now complete');
		$display='none';
	}else{
		//$lesson->add_message('You have not completed the time requirement. Please continue.');
		$display='block';
	}
	//echo '<pre>';print_r($completioncache);//die();
	//print_r($lesson);die();
?>
<div id="lesson-timer" style="max-width:300px;margin:3px;padding:15px;text-align:center;font-size:14px;color:#FFF;font-weight:bold;background-color:#001E3C;border:solid 2px #e8eaeb;text-weight:bold;position:fixed;top:13%;right:0px;float:right;z-index:15000;display:<?php echo $display; ?>"><p>Time Requirement<br><span id="timereq">00:00</span></p>
            	
            	<p>Time Left<br>
            	<span id="clockdiv">00:00</span></p>
            	</div>
<!--div id="clockdiv"></div-->


<!--button id="pause">Pause</button>
<button id="resume">Resume</button-->

<script>

var mintime = <?php echo $minimumrequirement*1000; ?>;
var timeRemaining =Number(<?php echo $minimumrequirement; ?> ) - Number(<?php echo $timealreadyspent; ?> );
var time_in_minutes = Number(timeRemaining); //sessionStorage['timeleft']

// 10 minutes from now
//var time_in_minutes = 10;
var current_time = Date.parse(new Date());
var deadline = new Date(current_time + time_in_minutes*1000);
var paused = false; // is the clock paused?
var time_left; // time left on the clock when paused
var lessonid = <?php echo $lesson->id; ?>;
var userid = <?php echo $USER->id; ?>;
var courseid = <?php echo $lesson->cm->course; ?>;

function time_remaining(endtime){
	var t = Date.parse(endtime) - Date.parse(new Date());
	//console.log(t)
	//sessionStorage['timeleft']=t/1000;
	var seconds = Math.floor( (t/1000) % 60 );
	var minutes = Math.floor( (t/1000/60) % 60 );
	var hours = Math.floor( (t/(1000*60*60)) % 24 );
	var days = Math.floor( t/(1000*60*60*24) );
	return {'total':t, 'days':days, 'hours':hours, 'minutes':minutes, 'seconds':seconds};
}

function msToTime(duration) {
	var milliseconds = parseInt((duration%1000)/100)
		, seconds = parseInt((duration/1000)%60)
		, minutes = parseInt((duration/(1000*60))%60)
		, hours = parseInt((duration/(1000*60*60))%24);

	hours = (hours < 10) ? "0" + hours : hours;
	minutes = (minutes < 10) ? "0" + minutes : minutes;
	seconds = (seconds < 10) ? "0" + seconds : seconds;
	
	return minutes + ":" + seconds ;
}

var timeinterval;
function run_clock(id,endtime){
	var clock = document.getElementById(id);
//	alert(lessonid+"=="+userid);
	var url = 'updateTimer.php';
	console.log(lessonid+"=="+userid);
	jQuery.post(url, { lessonid: lessonid, userid: userid, pauseResume:'resume' }, function (response) {
			console.log("Response==="+response);
			update_clock(); // run function once at first to avoid delay
	        timeinterval = setInterval(update_clock,1000);
	});

	function update_clock(){
		var t = time_remaining(endtime);
		if (t.seconds < 10) {
			t.seconds = "0" + t.seconds;
		}
		if (t.minutes < 10) {
			t.minutes = "0" + t.minutes;
		}
		clock.innerHTML = t.minutes+':'+t.seconds;
		
		var url = 'updateTimer.php';
		jQuery.post(url, { lessonid: lessonid, userid: userid, pauseResume:'pause' }, function (response) {
				console.log("Response==="+response);
		});
		
		if(t.total<=0){ 
			clearInterval(timeinterval); 
			clock.innerHTML = '<span style="color:red">Time requirement is now complete</span>'
			var url = 'updateTimer.php';
			console.log(lessonid+"=="+userid+"=="+courseid);
			jQuery.post(url, { lessonid: lessonid, userid: userid, courseid: courseid, pauseResume:'stop' }, function (response) {
					console.log("Response==="+response);
			});
		}
	}
	//jQuery('#timereq').html(msToTime(mintime));
	jQuery('#timereq').html(msToTime(mintime)+ " minutes");
	
	// both ways to register both beforeunload And unload events would work with window
    window.addEventListener("beforeunload", successful_listener2);
    window.addEventListener("unload", successful_listener2);
    window.onbeforeunload = successful_listener2;
    window.onunload = successful_listener2;
    function successful_listener2(e) {
        console.log("would fire!");
        clearInterval(timeinterval);
    }
}

run_clock('clockdiv',deadline);


/*function pause_clock(){
	if(!paused){
		paused = true;
		clearInterval(timeinterval); // stop the clock
		time_left = time_remaining(deadline).total; // preserve remaining time
		console.log(lessonid+"=="+userid);
		/*var url = 'updateTimer.php';
		jQuery.post(url, { lessonid: lessonid, userid: userid, pauseResume:'pause' }, function (response) {
				console.log("Response==="+response);
		});
	}
}

function resume_clock(){
	if(paused){

		paused = false;

		// update the deadline to preserve the amount of time remaining
		deadline = new Date(Date.parse(new Date()) + time_left);

		// start the clock
		run_clock('clockdiv',deadline);

	}
}*/

// handle pause and resume button clicks
/*document.getElementById('pause').onclick = pause_clock;
document.getElementById('resume').onclick = resume_clock;

window.addEventListener("beforeunload", pause_clock);
window.addEventListener("unload", pause_clock);
window.onbeforeunload = pause_clock;
window.onunload = pause_clock;*/

</script>