<?php
session_start();
$session=session_id();
$times=time();
$time_check=$times-600; //กำหนดเวลาในที่นี้ผมกำหนด 10 นาที
//require("../inc/config.inc.php");
//require("../inc/common.php");



?>
<!DOCTYPE html>
<html lang='en'>
  <head>
    <meta charset='utf-8' />
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<meta http-equiv="Content-Security-Policy" content="block-all-mixed-content">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css">
      
        <!-- ✅ Bootstrap -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
      
    <title>QRCode Scanner</title>
	<script src="lib/jsqr/jsQR.js"></script>
	<style>
		/* สไตล์ใหม่: กำหนดพื้นหลังสีดำและสีข้อความ */
        body {
            background-color: #000 !important; /* พื้นหลังสีดำ */
            color: #fff !important; /* ข้อความสีขาว */
            padding-top: 10px;
        }

		h3 {
			color: #fff; /* สีน้ำเงินสำหรับหัวข้อ */
		}

		.wrap-qrcode-scanner {
			max-width: 640px;
			margin: 0 auto;
			position: relative;
			padding: 15px; /* เพิ่ม padding เพื่อไม่ให้ชิดขอบจอเกินไป */
		}

		/* สไตล์สำหรับกล้องวิดีโอ (Canvas) */
		#canvas {
            width: 100%;
            height: auto;
            border: 2px solid #007bff; /* กรอบสีน้ำเงิน */
            border-radius: 5px;
		}

		/* สไตล์สำหรับข้อความโหลด */
		#loadingMessage {
			text-align: center;
			padding: 40px;
			background-color: #212529; /* พื้นหลังมืด */
			color: #fff;
            border-radius: 5px;
		}

		/* สไตล์สำหรับกล่องแสดงผลลัพธ์ */
		#output {
            margin-top: 20px;
            background: #343a40; /* พื้นหลังกล่องแสดงผลมืด */
            color: #fff;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
		}
		
        /* สไตล์สำหรับข้อความแสดงข้อมูล QR */
		#output div {
			padding-bottom: 10px;
			word-wrap: break-word;
		}
        
        /* สไตล์สำหรับข้อความบันทึกสำเร็จ (saveResult) */
        #saveResult {
            color: #28a745; /* สีเขียว */
            font-weight: bold;
            margin-top: 5px;
            padding: 5px 0;
            border-top: 1px solid #444;
        }

		#beepsound{width: 0px;height: 1px;}
	  </style>	
  </head>
<body class="bg-dark">


<div class="wrap-qrcode-scanner">
	<h3>สแกน QRCode บัตรนักศึกษา</h3>
	<div id="loadingMessage">🎥 Unable to access video stream (please make sure you have a webcam enabled)</div>
	<canvas id="canvas" hidden></canvas>
<div id="output" hidden>
    <div id="outputMessage">No QR code detected.</div>
   <div hidden><b>Data:</b> <span id="outputData"></span></div> 
</div>
    
      <div id="saveResult" style="color: green; font-weight: bold; margin-top: 5px;"></div> 
	<audio id="beepsound" controls>
	<source src="sound/scanner-beeps-barcode.mp3" type="audio/mpeg">
	Your browser does not support the audio tag.
	</audio>  
	<img id="outputqrcode">
	<canvas id="canvas2" ></canvas>
</div>
  <script>
    var video = document.createElement("video");
    var canvasElement = document.getElementById("canvas");
    var canvas = canvasElement.getContext("2d");
    var loadingMessage = document.getElementById("loadingMessage");
    var outputContainer = document.getElementById("output");
    var outputMessage = document.getElementById("outputMessage");
    var outputData = document.getElementById("outputData");
	var beepsound = document.getElementById("beepsound");
	var outputQrcode = document.getElementById('outputqrcode');
      
    var saveResult = document.getElementById("saveResult");  
      
	var TLR,TRR,BRL,BLL;
	var code;
	var waiting;

    function drawLine(begin, end, color) {
      canvas.beginPath();
      canvas.moveTo(begin.x, begin.y);
      canvas.lineTo(end.x, end.y);
      canvas.lineWidth = 4;
      canvas.strokeStyle = color;
      canvas.stroke();
	  return true;
    }

    // Use facingMode: environment to attemt to get the front camera on phones
    navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } }).then(function(stream) {
      video.srcObject = stream;
      video.setAttribute("playsinline", true); // required to tell iOS safari we don't want fullscreen
      video.play();
      requestAnimationFrame(tick);
    });

    function tick() {
      loadingMessage.innerText = "⌛ Loading video..."
      if (video.readyState === video.HAVE_ENOUGH_DATA) {
        loadingMessage.hidden = true;
        canvasElement.hidden = false;
        outputContainer.hidden = false;

        canvasElement.height = video.videoHeight;
        canvasElement.width = video.videoWidth;
		canvas.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);
		if(!video.paused){				
			var imageData = canvas.getImageData(0, 0, canvasElement.width, canvasElement.height);
			 code = jsQR(imageData.data, imageData.width, imageData.height, {
			  inversionAttempts: "dontInvert",
			});					
		}
        if (code) {
          TLR = drawLine(code.location.topLeftCorner, code.location.topRightCorner, "#FF3B58");
          TRR = drawLine(code.location.topRightCorner, code.location.bottomRightCorner, "#FF3B58");
          BRL = drawLine(code.location.bottomRightCorner, code.location.bottomLeftCorner, "#FF3B58");
          BLL = drawLine(code.location.bottomLeftCorner, code.location.topLeftCorner, "#FF3B58");
          outputMessage.hidden = true;
          outputData.parentElement.hidden = false;
          outputData.innerText = code.data;
		  if(code.data!="" && !waiting && TLR==true && TRR==true && BRL==true && BLL==true ){
		  	console.log(code.data);
			// สามารถส่งค่า code.data ไปทำงานอย่างอื่นๆ ผ่าน ajax ได้
             // ✅ ส่งข้อมูลไปยังเซิร์ฟเวอร์เพื่อบันทึกในฐานข้อมูล
                    fetch('save_qr.php', {
                      method: 'POST',
                      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                      body: 'qrcode=' + encodeURIComponent(code.data)
                    })
                    .then(res => res.text())

      .then(response => {
                      //console.log('Server response:', response);
                      //alert('บันทึกข้อมูลเรียบร้อย: ' + response);
                      alert(response);
                      // *** เปลี่ยนการใช้ alert() เป็นการแสดงผลที่ saveResult ***
                      // สมมติว่า server ตอบกลับด้วยข้อความ "บันทึกข้อมูลเรียบร้อย"
                      saveResult.innerText = ''+response;    
                     // ล้างข้อความหลังจากผ่านไป 4 วินาที 
                      setTimeout(() => {
                          saveResult.innerText = "";
                      }, 2500);

                    })
 
                    .catch(err => console.error('Error:', err));  
            //-----  
		  	video.pause();
        
			beepsound.play();
			beepsound.onended = function() {
            beepsound.muted = true;
			};	
			// ให้เริ่มเล่นวิดีโอก่อนล็กน้อย เพื่อล้างค่ารูป qrcod ล่าสุด เป็นการใช้รูปจากกล้องแทน
			setTimeout(function(){
				video.play();
			},1000);
			// ให้รอ 5 วินาทีสำหรับการ สแกนในครั้งจ่อไป
			 waiting = setTimeout(function(){
			 	TLR,TRR,BRL,BLL = null;
				beepsound.muted = false;
				if(waiting){
					clearTimeout(waiting);
					waiting = null;					
				}
			  },2500);					
		  }
        } else {
          outputMessage.hidden = false;
          outputData.parentElement.hidden = true;
        }
      }
      requestAnimationFrame(tick);
    }
      
      
  
  </script>
    
    
</body>
</html>