<?php
session_start();
if (!isset($_SESSION['student_id']) || !isset($_SESSION['exam_id'])) {
    header('Location: student_login.php');
    exit;
}
$student_id = $_SESSION['student_id'];
$exam_id = $_SESSION['exam_id'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Exam Terms and Conditions - MCQ Exam Portal</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<style>
  #studentCamera {
    width: 160px;
    height: 120px;
    border: 2px solid #2980b9;
    border-radius: 8px;
    background-color: black;
    display: block;
  }
</style>
</head>
<body>
<div class="container mt-5">
  <h2>Exam Terms and Conditions</h2>
  <p>Please read and accept the following terms before starting the exam:</p>
  <ul>
    <li>Camera access is mandatory during the exam.</li>
    <li>No screen capture or copying allowed.</li>
    <li>Do not switch tabs or minimize the window during the exam.</li>
    <li>Split screen or window resizing is not allowed.</li>
  </ul>
  <div class="mb-3">
    <video id="studentCamera" autoplay muted playsinline></video>
  </div>
  <div class="form-check mb-3">
    <input class="form-check-input" type="checkbox" id="acceptTerms" />
    <label class="form-check-label" for="acceptTerms">
      I have read and accept the terms and conditions.
    </label>
  </div>
  <button id="startExamBtn" class="btn btn-primary" disabled>Start Exam</button>
</div>
<script>
  const video = document.getElementById('studentCamera');
  const acceptTermsCheckbox = document.getElementById('acceptTerms');
  const startExamBtn = document.getElementById('startExamBtn');
  let cameraAccessGranted = false;

  function updateStartButtonState() {
    startExamBtn.disabled = !(cameraAccessGranted && acceptTermsCheckbox.checked);
  }

  acceptTermsCheckbox.addEventListener('change', updateStartButtonState);

  async function startCamera() {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: "user" } } });
      video.srcObject = stream;
      cameraAccessGranted = true;
      updateStartButtonState();
      console.log('Camera stream started successfully.');
    } catch (err) {
      console.error('Error accessing camera:', err);
      alert('Camera access is mandatory to start the exam. Please allow camera access.');
      cameraAccessGranted = false;
      updateStartButtonState();
    }
  }

  startCamera();

  startExamBtn.addEventListener('click', () => {
    if (cameraAccessGranted && acceptTermsCheckbox.checked) {
      window.location.href = 'take_exam.php';
    } else {
      alert('You must allow camera access and accept the terms to start the exam.');
    }
  });
</script>
</body>
</html>
