<?php
if(isset($_POST['input_submit'])){
  $query = "SELECT learning_unit_answer.* FROM learning_unit_answer LEFT JOIN learning_unit_question ON learning_unit_question.id = learning_unit_answer.question_id WHERE learning_unit_id = ".$unit_id;
  $result = @mysqli_query($GLOBALS['mysql_con'], $query);
  $correct_answers = 0;
  while($answers = @mysqli_fetch_array($result)){
      $answer_post = ($_POST['input_answer_'.$answers['id']] == "on") ? 1 : 0;
      if($answers['correct'] == $answer_post){
          $correct_answers++;
      }
  }
  $datetime = new DateTime();

  if (@mysqli_num_rows($result) == $correct_answers) { 
    $query_select = "SELECT * FROM main_certificate WHERE learning_unit_id = ".$unit_id;
    $result_select = @mysqli_query($GLOBALS['mysql_con'], $query_select);
    if (@mysqli_num_rows($result_select) >= 1) { 
      $row = @mysqli_fetch_array($result_select);
      $query    = "INSERT INTO certificate_contact_link (id, certificate_id, main_contact_id, issue_date, active) VALUES (
        NULL,
        '" . $row['certificate_id'] . "',
        '" . $GLOBALS['main_contact']['id'] . "',
        '" . $datetime->format('Y-m-d') . "',
        '1'
        )";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }
    $correct = 1;
  }else{
    $correct = 0;
  }

  $query    = "INSERT INTO learning_unit_submit (id, learning_unit_id, main_contact_id, datetime, correct) VALUES (
    NULL,
    '" . $unit_id . "',
    '" . $GLOBALS['main_contact']['id'] . "',
    '" . $datetime->format('Y-m-d H:i:s') . "',
    '" . $correct . "'
    )";
  @mysqli_query($GLOBALS['mysql_con'], $query);

  $host  = $_SERVER['HTTP_HOST'];
	$uri   = $_SERVER["REDIRECT_URL"];
	echo "<script type='text/javascript'>window.location.href = 'https://".$host.$uri."';</script>";
}

function load_questions($unit_id){
  $query = "SELECT * FROM learning_unit_question WHERE learning_unit_id = ".$unit_id;
  $result = @mysqli_query($GLOBALS['mysql_con'], $query);
  while($question = @mysqli_fetch_array($result)){
      echo "<div class='certificate_question'>";
      echo "<h3 class='certificate_question_headline'>".$question['description']."</h3>";
      load_answers($question['id']);
      echo "</div>";
  }
}

function load_answers($question_id){
  $query = "SELECT * FROM learning_unit_answer WHERE question_id = ".$question_id. " ORDER BY RAND()";
  $result = @mysqli_query($GLOBALS['mysql_con'], $query);
  echo "<div class='answer_input_group'>";
  while($answer = @mysqli_fetch_array($result)){
      echo "<div class='answer_input'>";
      echo input($answer['description'], "input_answer_".$answer['id'], "checkbox");
      echo "</div>";

  }
  echo "</div>";
}

function load_submit_mask($submit){
  $datetime = new DateTime($submit['datetime']);
  if($submit['correct'] == 1){
    echo "<div class='learning_success_modal'>";
      echo "<div class='learning_success'>";
      ?>
      <div class="success-animation">
        <svg class="checkmark" xmlns="https://www.w3.org/2000/svg" viewBox="0 0 52 52"><circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" /><path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" /></svg>
      </div>
      <?php
      echo "<h3>Du hast diese Einheit am ".$datetime->format('d.m.Y')." erfolgreich abgeschlossen.</h3>";
      ?>
      <div class="button_group">
        <a href="#" id="close_overlay" class=""><button>Video erneut ansehen</button></a>
        <a href="/intranet/de/e-learning/" class=""><button>zum E-Learning</button></a>
      </div>
      <?php
      echo "</div>";
    echo "</div>";
  }else{
    echo "<div class='learning_success_modal'>";
      echo "<div class='learning_error'>";
        ?>

        <div class="ui-error">
            <svg  viewBox="0 0 87 87" version="1.1" xmlns="https://www.w3.org/2000/svg" xmlns:xlink="https://www.w3.org/1999/xlink">
              <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                  <g id="Group-2" transform="translate(2.000000, 2.000000)">
                    <circle id="Oval-2" stroke="rgba(252, 191, 191, .5)" stroke-width="4" cx="41.5" cy="41.5" r="41.5"></circle>
                    <circle  class="ui-error-circle" stroke="#F74444" stroke-width="4" cx="41.5" cy="41.5" r="41.5"></circle>
                      <path class="ui-error-line1" d="M22.244224,22 L60.4279902,60.1837662" id="Line" stroke="#F74444" stroke-width="3" stroke-linecap="square"></path>
                      <path class="ui-error-line2" d="M60.755776,21 L23.244224,59.8443492" id="Line" stroke="#F74444" stroke-width="3" stroke-linecap="square"></path>
                  </g>
              </g>
          </svg>
          </div>

        <?php
        echo "<h3>Du kannst erst morgen wieder versuchen, diese Einheit abzuschließen.</h3>";
        ?>
        <div class="button_group">
          <a href="#" id="close_overlay" class=""><button>Video erneut ansehen</button></a>
          <a href="/intranet/de/e-learning/" class=""><button>zum E-Learning</button></a>
        </div>
        <?php
      echo "</div>";
    echo "</div>";
  }
}

$query = "SELECT * FROM learning_unit WHERE id = ".$unit_id;
$result = @mysqli_query($GLOBALS['mysql_con'], $query);
$unit = @mysqli_fetch_array($result);

$current_date = new DateTime();
$query_submit = "SELECT * FROM learning_unit_submit WHERE learning_unit_id = ".$unit_id." AND main_contact_id = ".$GLOBALS['main_contact']['id'] . " ORDER BY id DESC LIMIT 1";
$result_submit = @mysqli_query($GLOBALS['mysql_con'], $query_submit);
$row_submit = @mysqli_fetch_array($result_submit);
?>

<!-- <div class='el_back_button'>
    <button class='back_button' onclick='history.back()'>Zurück</button>
</div> -->
<div class="certificate_container">
    <h2 class="certificate_title"><?= $unit['title']?></h2>
    <p class="certificate_paragraph"><?= $unit['description']?></p>
    <div class='certificate_frame'>
        <?= $unit['link'] ?>
    </div>

    <?php if(@mysqli_num_rows($result_submit) >= 1){
      load_submit_mask($row_submit);
    }else{ ?>
    <button class="to_the_questions">zu den Fragen</button>
    <div class='certificate_questions' style="display:none;">
        <form id="certificate_questions_form"method='post'>
            <?php load_questions($unit_id); ?>
            <div class="question_nav">
                <div class="prev">Vorherige Frage</div>
                <div class="next">Nächste Frage</div>
                <input class="submit_answers" type='submit' value="Meine Antworten absenden"name='input_submit'>
            </div>
        </form>
    </div>
    <?php } ?>
</div>

<script>
    $(document).ready(function() {

  // Zählt alle divs mit der Klasse certificate_question

  var currentIndex = 0;
  var maxIndex = $('.certificate_question').length - 1;

  $('.certificate_question').eq(currentIndex).addClass('active');


  if (currentIndex === 0) {
    $('.prev').css('opacity', '0');
  }

  $('.next').click(function() {
    if (currentIndex < maxIndex) {
      $('.certificate_question').eq(currentIndex).removeClass('active');
      currentIndex++;
      $('.certificate_question').eq(currentIndex).addClass('active');

      if (currentIndex === 1) {
        $('.prev').css('opacity', '1');
        $('.submit_answers').css('display', 'none');

      }
    }

    // Überprüfe, ob wir uns im letzten Schritt befinden, und blende den "Weiter"-Button aus
    if (currentIndex === maxIndex) {
        
      $('.next').css('display', 'none');
      $('.submit_answers').css('display', 'block');
    }
  });

  $('.prev').click(function() {

    if (currentIndex > 0) {
      $('.certificate_question').eq(currentIndex).removeClass('active');
      currentIndex--;
      $('.certificate_question').eq(currentIndex).addClass('active');

      if (currentIndex === 0) {
        $('.prev').css('opacity', '0');

      }
    }

    // Überprüfe, ob wir uns nicht mehr im letzten Schritt befinden, und blende den "Weiter"-Button ein
    if (currentIndex < maxIndex) {
        $('.next').css('display', 'block');
        $('.submit_answers').css('display', 'none');
    }
  });
});

const form = document.getElementById('certificate_questions_form');

// form.addEventListener('submit', (event) => {
//   event.preventDefault(); // Verhindert das Standardverhalten des Formulars (neu laden der Seite)

//   if (window.confirm('Sicher, dass die Fragen abgesendet werden sollen?')) {
//     // Popup-Bestätigung erhalten
//     form.submit(); // Sendet das Formular
//   } else {
//     // Popup-Bestätigung abgelehnt
//     return false;
//   }
// });

$(document).ready(function() {
  // Wenn die Checkbox angeklickt wird
  $('.answer_input input[type="checkbox"]').click(function() {
    // Wenn die Checkbox angeklickt wurde und ausgewählt ist
    if ($(this).is(':checked')) {
      // Füge der Umrandung des div die Klasse "checked" hinzu
      $(this).closest('.answer_input').addClass('checked');
    } else {
      // Entferne die Klasse "checked", wenn die Checkbox abgewählt wird
      $(this).closest('.answer_input').removeClass('checked');
    }
  });
});

</script>