<!-- Terms and Conditions Modal for Student Dashboard -->
<div class="modal fade" id="termsModal" tabindex="-1" aria-labelledby="termsModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="termsModalLabel">Exam Terms and Conditions</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <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 style="width: 160px; height: 120px; border: 2px solid #2980b9; border-radius: 8px; background-color: black;"></video>
        </div>
        <div class="mb-3">
          <label for="examCodeInput" class="form-label">Enter Exam Code</label>
          <input type="text" id="examCodeInput" class="form-control" placeholder="Enter exam code" />
        </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>
      </div>
      <div class="modal-footer">
        <button id="startExamBtn" class="btn btn-primary" disabled>Start Exam</button>
      </div>
    </div>
  </div>
</div>

<script>
  const video = document.getElementById('studentCamera');
  const acceptTermsCheckbox = document.getElementById('acceptTerms');
  const startExamBtn = document.getElementById('startExamBtn');
  const examCodeInput = document.getElementById('examCodeInput');
  let cameraAccessGranted = false;
  let selectedExamId = null;

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

  acceptTermsCheckbox.addEventListener('change', updateStartButtonState);
  examCodeInput.addEventListener('input', 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', () => {
    const enteredCode = examCodeInput.value.trim();
    if (!enteredCode) {
      alert('Please enter the exam code.');
      return;
    }
    // Disable button to prevent multiple clicks during validation
    startExamBtn.disabled = true;

    // Validate exam code with server
    fetch('validate_exam_code.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ exam_id: selectedExamId, exam_code: enteredCode })
    })
    .then(response => response.json())
    .then(data => {
      if (data.valid) {
        if (cameraAccessGranted && acceptTermsCheckbox.checked) {
          window.location.href = 'start_exam.php?exam_id=' + selectedExamId;
        } else {
          alert('You must allow camera access and accept the terms to start the exam.');
        }
      } else {
        alert('Exam code invalid. Please try again.');
      }
    })
    .catch(() => {
      alert('Error validating exam code. Please try again.');
    })
    .finally(() => {
      // Re-enable the button after validation completes
      startExamBtn.disabled = false;
    });
  });

  // Event delegation for start exam buttons
  document.addEventListener('click', function(event) {
    if (event.target && event.target.classList.contains('start-exam-btn')) {
      selectedExamId = event.target.getAttribute('data-exam-id');
      acceptTermsCheckbox.checked = false;
      examCodeInput.value = '';
      updateStartButtonState();
      var termsModal = new bootstrap.Modal(document.getElementById('termsModal'));
      termsModal.show();
    }
  });
</script>
</create_file>
